Compare commits

...
5 Commits
Author SHA1 Message Date
Yves Rutschle f842e2e081 v1.14: 21DEC2012
Corrected OpenVPN probe to support pre-shared secret
	mode (OpenVPN port-sharing code is... wrong). Thanks
	to Kai Ellinger for help in investigating and
	testing.

	Added an actual TLS/SSL probe.

	Added configurable --on-timeout protocol
	specification.

	Added a --anyprot protocol probe (equivalent to what
	--ssl was).

	Makefile respects the user's compiler and CFLAG
	choices (falling back to the current values if
	undefined), as well as LDFLAGS.
	(Michael Palimaka)

	Added "After" and "KillMode" to systemd.sslh.service
	(Thomas Weißschuh).

	Added LSB tags to etc.init.d.sslh
	(Thomas Varis).
2013-07-10 23:19:33 +02:00
Yves Rutschle 5cd1fa1875 v1.13: 18MAY2012
Write PID file before dropping privileges.

	Added --background, which overrides 'foreground'
	configuration file setting.

	Added example systemd service file from Archlinux in
	scripts/
	https://projects.archlinux.org/svntogit/community.git/tree/trunk/sslh.service?h=packages/sslh
	(Sébastien Luttringer)
2013-07-10 23:16:50 +02:00
Yves Rutschle 9bcb2cdd7a v1.12: 08MAY2012
Added support for configuration file.

	New protocol probes can be defined using regular
	expressions that match the first packet sent by the
	client.

	sslh now connects timed out connections to the first
	configured protocol instead of 'ssh' (just make sure
	ssh is the first defined protocol).

	sslh now tries protocols in the order in which they
	are defined (just make sure sslh is the last defined
	protocol).
2013-07-10 23:15:38 +02:00
Yves Rutschle 26b4bcd089 v1.11: 21APR2012
WARNING: defaults have been removed for --user and
	--pidfile options, update your start-up scripts!

	No longer stop sslh when reverse DNS requests fail
	for logging.

	Added HTTP probe.

	No longer create new session if running in
	foreground.

	No longer default to changing user to 'nobody'. If
	--user isn't specified, just run as current user.

	No longer create PID file by default, it should be
	explicitely set with --pidfile.

	No longer log to syslog if in foreground. Logs are
	instead output to stderr.

	The four changes above make it straightforward to
	integrate sslh with systemd, and should help with
	launchd.
2013-07-10 23:14:48 +02:00
Yves Rutschle ae008179f0 v1.10:
Fixed calls referring to sockaddr length so they work
	with FreeBSD.

	Try target addresses in turn until one works if
	there are several (e.g. "localhost:22" resolves to
	an IPv6 address and an IPv4 address and sshd does
	not listen on IPv6).

	Fixed sslh-fork so killing the head process kills
	the listener processes.

	Heavily cleaned up test suite. Added stress test
	t_load script. Added coverage (requires lcov).

	Support for XMPP (Arnaud Gendre).

	Updated README.MacOSX (Aaron Madlon-Kay).
2013-07-10 23:14:15 +02:00
21 changed files with 2079 additions and 748 deletions

No files matched your search

+98
View File
@@ -1,4 +1,102 @@
v1.14: 21DEC2012
Corrected OpenVPN probe to support pre-shared secret
mode (OpenVPN port-sharing code is... wrong). Thanks
to Kai Ellinger for help in investigating and
testing.
Added an actual TLS/SSL probe.
Added configurable --on-timeout protocol
specification.
Added a --anyprot protocol probe (equivalent to what
--ssl was).
Makefile respects the user's compiler and CFLAG
choices (falling back to the current values if
undefined), as well as LDFLAGS.
(Michael Palimaka)
Added "After" and "KillMode" to systemd.sslh.service
(Thomas Weißschuh).
Added LSB tags to etc.init.d.sslh
(Thomas Varis).
v1.13: 18MAY2012
Write PID file before dropping privileges.
Added --background, which overrides 'foreground'
configuration file setting.
Added example systemd service file from Archlinux in
scripts/
https://projects.archlinux.org/svntogit/community.git/tree/trunk/sslh.service?h=packages/sslh
(Sébastien Luttringer)
v1.12: 08MAY2012
Added support for configuration file.
New protocol probes can be defined using regular
expressions that match the first packet sent by the
client.
sslh now connects timed out connections to the first
configured protocol instead of 'ssh' (just make sure
ssh is the first defined protocol).
sslh now tries protocols in the order in which they
are defined (just make sure sslh is the last defined
protocol).
v1.11: 21APR2012
WARNING: defaults have been removed for --user and
--pidfile options, update your start-up scripts!
No longer stop sslh when reverse DNS requests fail
for logging.
Added HTTP probe.
No longer create new session if running in
foreground.
No longer default to changing user to 'nobody'. If
--user isn't specified, just run as current user.
No longer create PID file by default, it should be
explicitely set with --pidfile.
No longer log to syslog if in foreground. Logs are
instead output to stderr.
The four changes above make it straightforward to
integrate sslh with systemd, and should help with
launchd.
v1.10: 27NOV2011
Fixed calls referring to sockaddr length so they work
with FreeBSD.
Try target addresses in turn until one works if
there are several (e.g. "localhost:22" resolves to
an IPv6 address and an IPv4 address and sshd does
not listen on IPv6).
Fixed sslh-fork so killing the head process kills
the listener processes.
Heavily cleaned up test suite. Added stress test
t_load script. Added coverage (requires lcov).
Support for XMPP (Arnaud Gendre).
Updated README.MacOSX (Aaron Madlon-Kay).
v1.9: 02AUG2011
WARNING: This version does not work with FreeBSD and
derivatives!
WARNING: Options changed, you'll need to update your
start-up scripts! Log format changed, you'll need to
update log processing scripts!
+30 -11
View File
@@ -1,7 +1,9 @@
# Configuration
VERSION="v1.9"
VERSION="1.14"
USELIBCONFIG=1 # Use libconfig? (necessary to use configuration files)
USELIBWRAP= # Use libwrap?
COV_TEST= # Perform test coverage?
PREFIX=/usr/local
MAN=sslh.8.gz # man page name
@@ -9,19 +11,27 @@ MAN=sslh.8.gz # man page name
# End of configuration -- the rest should take care of
# itself
CC = gcc
CFLAGS=-Wall -g
ifneq ($(strip $(COV_TEST)),)
CFLAGS_COV=-fprofile-arcs -ftest-coverage
endif
#LIBS=-lnet
LIBS=
OBJS=common.o
CC ?= gcc
CFLAGS ?=-Wall -g $(CFLAGS_COV)
LIBS=$(LDFLAGS)
OBJS=common.o sslh-main.o probe.o
ifneq ($(strip $(USELIBWRAP)),)
LIBS:=$(LIBS) -lwrap
CFLAGS:=$(CFLAGS) -DLIBWRAP
endif
all: sslh $(MAN)
ifneq ($(strip $(USELIBCONFIG)),)
LIBS:=$(LIBS) -lconfig
CFLAGS:=$(CFLAGS) -DLIBCONFIG
endif
all: sslh $(MAN) echosrv
.c.o: *.h
$(CC) $(CFLAGS) -D'VERSION=$(VERSION)' -c $<
@@ -31,16 +41,25 @@ sslh: $(OBJS) sslh-fork sslh-select
sslh-fork: $(OBJS) sslh-fork.o Makefile common.h
$(CC) $(CFLAGS) -D'VERSION=$(VERSION)' -o sslh-fork sslh-fork.o $(OBJS) $(LIBS)
strip sslh-fork
#strip sslh-fork
sslh-select: $(OBJS) sslh-select.o Makefile common.h
$(CC) $(CFLAGS) -D'VERSION=$(VERSION)' -o sslh-select sslh-select.o $(OBJS) $(LIBS)
strip sslh-select
#strip sslh-select
echosrv: $(OBJS) echosrv.o
$(CC) $(CFLAGS) -o echosrv echosrv.o probe.o common.o $(LIBS)
$(MAN): sslh.pod Makefile
pod2man --section=8 --release=$(VERSION) --center=" " sslh.pod | gzip -9 - > $(MAN)
# Create release: export clean tree and tag current
# configuration
release:
svn export . /tmp/sslh-$(VERSION)
( cd /tmp; tar zcvf /tmp/sslh-$(VERSION).tar.gz sslh-$(VERSION) )
( cd .. ; svn copy trunk tags/sslh-$(VERSION) ; cd tags/sslh-$(VERSION) ; make clean )
# generic install: install binary and man page
install: sslh $(MAN)
install -D sslh-fork $(PREFIX)/sbin/sslh
@@ -58,10 +77,10 @@ uninstall:
update-rc.d sslh remove
clean:
rm -f sslh-fork sslh-select $(MAN) *.o
rm -f sslh-fork sslh-select echosrv $(MAN) *.o *.gcov *.gcno *.gcda *.png *.html *.css *.info
tags:
ctags -T *.[ch]
ctags --globals -T *.[ch]
test:
./t
+48 -12
View File
@@ -1,17 +1,55 @@
===== sslh -- A ssl/ssh multiplexer. =====
sslh accepts HTTPS, SSH and OpenVPN connections on the same
port. This makes it possible to connect to an SSH server or
an OpenVPN on port 443 (e.g. from inside a corporate
firewall, which almost never block port 443) while still
serving HTTPS on that port.
Sslh accepts connections on specified ports, and forwards
them further based on tests performed on the first data
packet sent by the remote client.
Probes for HTTP, SSL, SSH, OpenVPN, tinc, XMPP are
implemented, and any other protocol that can be tested using
a regular expression, can be recognised. A typical use case
is to allow serving several services on port 443 (e.g. to
connect to ssh from inside a corporate firewall, which
almost never block port 443) while still serving HTTPS on
that port.
Hence sslh acts as a protocol demultiplexer, or a
switchboard. Its name comes from its original function to
serve SSH and HTTPS on the same port.
==== Compile and install ====
If you're lucky, the Makefile will work for you:
sslh uses libconfig (http://www.hyperrealm.com/libconfig/)
and libwrap.
For Debian, these are contained in packages libwrap0-dev and
libconfig8-dev.
For OpenSUSE, these are contained in packages libconfig9 and
libconfig-dev in repository
http://download.opensuse.org/repositories/multimedia:/libs/openSUSE_12.1/
For Fedora, this package should work:
https://admin.fedoraproject.org/pkgdb/acls/name/libconfig
(feedback from Fedorans appreciated).
If you can't find libconfig, or just don't want a
configuration file, set 'USELIBCONFIG=' in the Makefile.
After this, the Makefile should work:
make install
There are a couple of configuration options at the beginning
of the Makefile:
USELIBWRAP compiles support for host access control (see
hosts_access(3)), you will need libwrap headers and
library to compile (libwrap0-dev in Debian).
USELIBCONFIG compiles support for the configuration
file. You will need libconfig headers to compile
(libconfig8-dev in Debian).
The Makefile produces two different executables: sslh-fork
and sslh-select.
@@ -27,7 +65,7 @@ If you are going to use sslh for a "small" setup (less than
a dozen ssh connections and a low-traffic https server) then
sslh-fork is probably more suited for you. If you are going
to use sslh on a "medium" setup (a few thousand ssh
connections, and another few thousand sslh connections),
connections, and another few thousand ssl connections),
sslh-select will be better. If you have a very large site
(tens of thousands of connections), you'll need a vapourware
version that would use libevent or something like that.
@@ -109,17 +147,15 @@ Web browser --------http/ssl------> stunnel ---http---> sslh --> http:80
Configuration goes like this:
On the server side, using stunnel3:
stunnel -f -p mycert.pem -d thelonious:443 -l /usr/local/sbin/sslh -- sslh -i --ssl localhost:80 --ssh localhost:22
stunnel -f -p mycert.pem -d thelonious:443 -l /usr/local/sbin/sslh -- sslh -i --http localhost:80 --ssh localhost:22
stunnel options: -f for foreground/debugging, -p specifies
the key + certificate, -d specifies which interface and port
we're listening to for incoming connexions, -l summons sslh
in inetd mode.
sslh options: -i for inetd mode, --ssl to forward SSL
connexions (in fact normal HTTP at that stage) to port 80,
and SSH connexions to port 22. This works because sslh
considers that any protocol it doesn't recognise is SSL.
sslh options: -i for inetd mode, --http to forward http
connexions to port 80, and SSH connexions to port 22.
==== IP_TPROXY support ====
+32 -32
View File
@@ -13,42 +13,42 @@ with launchctl or simply reboot.
----BEGIN FILE----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Disabled</key>
<false/>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>net.rutschle.sslh</string>
<key>ProgramArguments</key>
<array>
<string>/opt/local/sbin/sslh</string>
<string>-f</string>
<string>-v</string>
<string>-u</string>
<string>nobody</string>
<string>-p</string>
<string>0.0.0.0:443</string>
<string>-s</string>
<string>localhost:22</string>
<string>-l</string>
<string>localhost:443</string>
</array>
<key>QueueDirectories</key>
<array/>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Library/Logs/sslh.log</string>
<key>StandardOutPath</key>
<string>/Library/Logs/sslh.log</string>
<key>WatchPaths</key>
<array/>
<key>Disabled</key>
<false/>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>net.rutschle.sslh</string>
<key>ProgramArguments</key>
<array>
<string>/opt/local/sbin/sslh</string>
<string>-f</string>
<string>-v</string>
<string>-u</string>
<string>nobody</string>
<string>-p</string>
<string>0.0.0.0:443</string>
<string>--ssh</string>
<string>localhost:22</string>
<string>--ssl</string>
<string>localhost:443</string>
</array>
<key>QueueDirectories</key>
<array/>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Library/Logs/sslh.log</string>
<key>StandardOutPath</key>
<string>/Library/Logs/sslh.log</string>
<key>WatchPaths</key>
<array/>
</dict>
</plist>
----END FILE----
+28
View File
@@ -0,0 +1,28 @@
# This is a basic configuration file that should provide
# sensible values for "standard" setup.
verbose: false;
foreground: false;
inetd: false;
numeric: false;
timeout: 2;
user: "nobody";
pidfile: "/var/run/sslh.pid";
# Change hostname with your external address name.
listen:
(
{ host: "thelonious"; port: "443"; }
);
protocols:
(
{ name: "ssh"; service: "ssh"; host: "localhost"; port: "22"; probe: "builtin"; },
{ name: "openvpn"; host: "localhost"; port: "1194"; probe: "builtin"; },
{ name: "xmpp"; host: "localhost"; port: "5222"; probe: "builtin"; },
{ name: "http"; host: "localhost"; port: "80"; probe: "builtin"; },
{ name: "ssl"; host: "localhost"; port: "443"; probe: "builtin"; },
{ name: "anyprot"; host: "localhost"; port: "443"; probe: "builtin"; }
);
+159 -373
View File
@@ -5,23 +5,7 @@
**/
#define _GNU_SOURCE
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pwd.h>
#include <syslog.h>
#include <libgen.h>
#include <getopt.h>
#include "common.h"
@@ -31,55 +15,20 @@
#define SA_NOCLDWAIT 0
#endif
int is_ssh_protocol(const char *p, int len);
int is_openvpn_protocol(const char *p, int len);
int is_tinc_protocol(const char *p, int len);
int is_true(const char *p, int len) { return 1; }
struct proto protocols[] = {
/* affected description service saddr probe */
{ 0, "ssh", "sshd", {0}, is_ssh_protocol },
{ 0, "openvpn", NULL, {0}, is_openvpn_protocol },
{ 0, "tinc", NULL, {0}, is_tinc_protocol },
/* probe for SSL always successes: it's the default, and must be tried last
**/
{ 0, "ssl", NULL, {0}, is_true }
};
const char* USAGE_STRING =
"sslh " VERSION "\n" \
"usage:\n" \
"\tsslh [-v] [-i] [-V] [-f]\n"
"\t[-t <timeout>] [-P <pidfile>] -u <username> -p <add> [-p <addr> ...] \n" \
"\t[--ssh <addr>] [--ssl <addr>] [--openvpn <addr>] [--tinc <addr>]\n\n" \
"-v: verbose\n" \
"-V: version\n" \
"-f: foreground\n" \
"-p: address and port to listen on. default: 0.0.0.0:443.\n Can be used several times to bind to several addresses.\n" \
"--ssh: SSH address: where to connect an SSH connection.\n" \
"--ssl: SSL address: where to connect an SSL connection.\n" \
"--openvpn: OpenVPN address: where to connect an OpenVPN connection.\n" \
"--tinc: tinc address: where to connect a tinc connection.\n" \
"-P: PID file. Default: /var/run/sslh.pid.\n" \
"-i: Run as a inetd service.\n" \
"";
/*
* Settings that depend on the command line.
* They're set in main(), but also used in other places, and it'd be
* heavy-handed to pass it all as parameters
* Settings that depend on the command line. They're set in main(), but also
* used in other places in common.c, and it'd be heavy-handed to pass it all as
* parameters
*/
int verbose = 0;
int probing_timeout = 2;
int inetd = 0;
int foreground = 0;
int background = 0;
int numeric = 0;
char *user_name, *pid_file;
const char *user_name, *pid_file;
struct sockaddr_storage *addr_listen = NULL; /* what addresses do we listen to? */
int num_addr_listen = 0; /* How many addresses do we listen to? */
struct addrinfo *addr_listen = NULL; /* what addresses do we listen to? */
#ifdef LIBWRAP
#include <tcpd.h>
@@ -88,13 +37,13 @@ int allow_severity =0, deny_severity = 0;
/* check result and die, printing the offending address and error */
void check_res_dumpdie(int res, struct sockaddr_storage *sock, char* syscall)
void check_res_dumpdie(int res, struct addrinfo *addr, char* syscall)
{
char buf[64];
char buf[NI_MAXHOST];
if (res == -1) {
fprintf(stderr, "%s:%s: %s\n",
sprintaddr(buf, sizeof(buf), sock),
sprintaddr(buf, sizeof(buf), addr),
syscall,
strerror(errno));
exit(1);
@@ -103,31 +52,77 @@ void check_res_dumpdie(int res, struct sockaddr_storage *sock, char* syscall)
/* Starts listening sockets on specified addresses.
* IN: addr[], num_addr
* OUT: sockfd[]
* Bound file descriptors are returned in alread-allocated *sockfd pointer
Returns file descriptor
* OUT: *sockfd[] pointer to newly-allocated array of file descriptors
* Returns number of addresses bound
* Bound file descriptors are returned in newly-allocated *sockfd pointer
*/
void start_listen_sockets(int sockfd[], struct sockaddr_storage addr[], int num_addr)
int start_listen_sockets(int *sockfd[], struct addrinfo *addr_list)
{
struct sockaddr_storage *saddr;
struct addrinfo *addr;
int i, res, reuse;
int num_addr = 0;
for (i = 0; i < num_addr; i++) {
saddr = &addr[i];
for (addr = addr_list; addr; addr = addr->ai_next)
num_addr++;
sockfd[i] = socket(saddr->ss_family, SOCK_STREAM, 0);
check_res_dumpdie(sockfd[i], saddr, "socket");
if (verbose)
fprintf(stderr, "listening to %d addresses\n", num_addr);
*sockfd = malloc(num_addr * sizeof(*sockfd[0]));
for (i = 0, addr = addr_list; i < num_addr && addr; i++, addr = addr->ai_next) {
if (!addr) {
fprintf(stderr, "FATAL: Inconsistent listen number. This should not happen.\n");
exit(1);
}
saddr = (struct sockaddr_storage*)addr->ai_addr;
(*sockfd)[i] = socket(saddr->ss_family, SOCK_STREAM, 0);
check_res_dumpdie((*sockfd)[i], addr, "socket");
reuse = 1;
res = setsockopt(sockfd[i], SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
check_res_dumpdie(res, saddr, "setsockopt");
res = setsockopt((*sockfd)[i], SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
check_res_dumpdie(res, addr, "setsockopt");
res = bind (sockfd[i], (struct sockaddr*)saddr, sizeof(*saddr));
check_res_dumpdie(res, saddr, "bind");
res = bind((*sockfd)[i], addr->ai_addr, addr->ai_addrlen);
check_res_dumpdie(res, addr, "bind");
res = listen ((*sockfd)[i], 50);
check_res_dumpdie(res, addr, "listen");
res = listen (sockfd[i], 50);
check_res_dumpdie(res, saddr, "listen");
}
return num_addr;
}
/* Connect to first address that works and returns a file descriptor, or -1 if
* none work. cnx_name points to the name of the service (for logging) */
int connect_addr(struct addrinfo *addr, const char* cnx_name)
{
struct addrinfo *a;
char buf[NI_MAXHOST];
int fd, res;
for (a = addr; a; a = a->ai_next) {
if (verbose)
fprintf(stderr, "connecting to %s family %d len %d\n",
sprintaddr(buf, sizeof(buf), a),
a->ai_addr->sa_family, a->ai_addrlen);
fd = socket(a->ai_family, SOCK_STREAM, 0);
if (fd == -1) {
log_message(LOG_ERR, "forward to %s failed:socket: %s\n", cnx_name, strerror(errno));
} else {
res = connect(fd, a->ai_addr, a->ai_addrlen);
if (res == -1) {
log_message(LOG_ERR, "forward to %s failed:connect: %s\n",
cnx_name, strerror(errno));
} else {
return fd;
}
}
}
return -1;
}
/* Store some data to write to the queue later */
@@ -170,7 +165,6 @@ int flush_defered(struct queue *q)
q->defered_data_size -= n;
}
return n;
}
@@ -198,8 +192,6 @@ void dump_connection(struct connection *cnx)
* returns FD_NODATA if no data was available
* returns FD_STALLED if data was read, could not be written, and has been
* stored in temporary buffer.
*
* slot for debug only and may go away at some point
*/
int fd2fd(struct queue *target_q, struct queue *from_q)
{
@@ -253,105 +245,61 @@ int fd2fd(struct queue *target_q, struct queue *from_q)
return size_w;
}
/* If the client wrote something first, read it and check if it's a SSH banner.
* Data is left in appropriate defered write buffer.
*/
int is_ssh_protocol(const char *p, int len)
{
if (!strncmp(p, "SSH-", 4)) {
return 1;
}
return 0;
}
/* Is the buffer the beginning of an OpenVPN connection?
* (code lifted from OpenVPN port-share option)
*/
int is_openvpn_protocol (const char*p,int len)
{
#define P_OPCODE_SHIFT 3
#define P_CONTROL_HARD_RESET_CLIENT_V2 7
if (len >= 3)
{
return p[0] == 0
&& p[1] >= 14
&& p[2] == (P_CONTROL_HARD_RESET_CLIENT_V2<<P_OPCODE_SHIFT);
}
else if (len >= 2)
{
return p[0] == 0 && p[1] >= 14;
}
else
return 0;
}
/* Is the buffer the beginning of a tinc connections?
* (protocol is undocumented, but starts with "0 " in 1.0.15)
* */
int is_tinc_protocol( const char *p, int len)
{
return !strncmp(p, "0 ", len);
}
/*
* Read the beginning of data coming from the client connection and check if
* it's a known protocol. Then leave the data on the defered
* write buffer of the connection and returns the protocol index in the
* protocols[] array *
*/
T_PROTO_ID probe_client_protocol(struct connection *cnx)
{
char buffer[BUFSIZ];
int n, i;
n = read(cnx->q[0].fd, buffer, sizeof(buffer));
/* It's possible that read() returns an error, e.g. if the client
* disconnected between the previous call to select() and now. If that
* happens, we just connect to the default protocol so the caller of this
* function does not have to deal with a specific failure condition (the
* connection will just fail later normally). */
if (n > 0) {
defer_write(&cnx->q[1], buffer, n);
for (i = 0; i < ARRAY_SIZE(protocols); i++) {
if (protocols[i].affected) {
if (protocols[i].probe(buffer, n)) {
return i;
}
}
}
}
/* If none worked, return the first one affected (that's completely
* arbitrary) */
for (i = 0; i < ARRAY_SIZE(protocols); i++)
if (protocols[i].affected)
return i;
/* At this stage... nothing is affected. This shouldn't happen as we check
* at least one target exists when we parse the commnand line */
fprintf(stderr, "FATAL: No protocol affected. This should not happen.\n");
exit(1);
}
/* returns a string that prints the IP and port of the sockaddr */
char* sprintaddr(char* buf, size_t size, struct sockaddr_storage* s)
char* sprintaddr(char* buf, size_t size, struct addrinfo *a)
{
char host[NI_MAXHOST], serv[NI_MAXSERV];
int res;
res = getnameinfo(a->ai_addr, a->ai_addrlen,
host, sizeof(host),
serv, sizeof(serv),
numeric ? NI_NUMERICHOST | NI_NUMERICSERV : 0 );
if (res) {
log_message(LOG_ERR, "sprintaddr:getnameinfo: %s\n", gai_strerror(res));
/* Name resolution failed: do it numerically instead */
res = getnameinfo(a->ai_addr, a->ai_addrlen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV);
/* should not fail but... */
if (res) {
log_message(LOG_ERR, "sprintaddr:getnameinfo(NUM): %s\n", gai_strerror(res));
strcpy(host, "?");
strcpy(serv, "?");
}
}
getnameinfo((struct sockaddr*)s, sizeof(*s), host, sizeof(host), serv, sizeof(serv), numeric ? NI_NUMERICHOST | NI_NUMERICSERV : 0 );
snprintf(buf, size, "%s:%s", host, serv);
return buf;
}
/* turns a "hostname:port" string into a struct sockaddr;
sock: socket address to which to copy the addr
/* Turns a hostname and port (or service) into a list of struct addrinfo
* returns 0 on success, -1 otherwise and logs error
**/
int resolve_split_name(struct addrinfo **out, const char* host, const char* serv)
{
struct addrinfo hint;
int res;
memset(&hint, 0, sizeof(hint));
hint.ai_family = PF_UNSPEC;
hint.ai_socktype = SOCK_STREAM;
res = getaddrinfo(host, serv, &hint, out);
if (res)
log_message(LOG_ERR, "%s `%s:%s'\n", gai_strerror(res), host, serv);
return res;
}
/* turns a "hostname:port" string into a list of struct addrinfo;
out: list of newly allocated addrinfo (see getaddrinfo(3)); freeaddrinfo(3) when done
fullname: input string -- it gets clobbered
*/
void resolve_name(struct sockaddr_storage *sock, char* fullname)
void resolve_name(struct addrinfo **out, char* fullname)
{
struct addrinfo *addr, hint;
char *serv, *host;
int res;
@@ -359,7 +307,7 @@ void resolve_name(struct sockaddr_storage *sock, char* fullname)
if (!sep) /* No separator: parameter is just a port */
{
fprintf(stderr, "names must be fully specified as hostname:port\n");
fprintf(stderr, "%s: names must be fully specified as hostname:port\n", fullname);
exit(1);
}
@@ -367,76 +315,65 @@ void resolve_name(struct sockaddr_storage *sock, char* fullname)
serv = sep+1;
*sep = 0;
memset(&hint, 0, sizeof(hint));
hint.ai_family = PF_UNSPEC;
hint.ai_socktype = SOCK_STREAM;
res = getaddrinfo(host, serv, &hint, &addr);
res = resolve_split_name(out, host, serv);
if (res) {
fprintf(stderr, "%s `%s'\n", gai_strerror(res), fullname);
if (res == EAI_SERVICE)
fprintf(stderr, "(Check you have specified all ports)\n");
exit(1);
exit(4);
}
memcpy(sock, addr->ai_addr, sizeof(*sock));
freeaddrinfo(addr);
}
/* Log to syslog, and to stderr if foreground */
/* Log to syslog or stderr if foreground */
void log_message(int type, char* msg, ...)
{
va_list ap;
va_start(ap, msg);
vsyslog(type, msg, ap);
va_end(ap);
va_start(ap, msg);
if (foreground)
vfprintf(stderr, msg, ap);
else
vsyslog(type, msg, ap);
va_end(ap);
}
/* syslogs who connected to where */
void log_connection(struct connection *cnx)
{
struct sockaddr_storage peeraddr; /* Who's connecting to sshd */
struct sockaddr_storage listenaddr; /* Where is it connecting to */
struct sockaddr_storage forwardfromaddr; /* Where is it forwarded from */
struct sockaddr_storage targetaddr; /* Where is it forwarded to */
socklen_t size = sizeof(peeraddr);
struct addrinfo addr;
struct sockaddr_storage ss;
#define MAX_NAMELENGTH (NI_MAXHOST + NI_MAXSERV + 1)
char buf[MAX_NAMELENGTH], buf2[MAX_NAMELENGTH], buf3[MAX_NAMELENGTH], buf4[MAX_NAMELENGTH];
char peer[MAX_NAMELENGTH], service[MAX_NAMELENGTH],
local[MAX_NAMELENGTH], target[MAX_NAMELENGTH];
int res;
memset(&peeraddr, 0, sizeof(peeraddr));
memset(&listenaddr, 0, sizeof(listenaddr));
memset(&forwardfromaddr, 0, sizeof(forwardfromaddr));
memset(&targetaddr, 0, sizeof(targetaddr));
addr.ai_addr = (struct sockaddr*)&ss;
addr.ai_addrlen = sizeof(ss);
res = getpeername(cnx->q[0].fd, (struct sockaddr*)&peeraddr, &size);
res = getpeername(cnx->q[0].fd, addr.ai_addr, &addr.ai_addrlen);
if (res == -1) return; /* that should never happen, right? */
sprintaddr(peer, sizeof(peer), &addr);
size = sizeof(listenaddr);
res = getsockname(cnx->q[0].fd, (struct sockaddr*)&listenaddr, &size);
addr.ai_addrlen = sizeof(ss);
res = getsockname(cnx->q[0].fd, addr.ai_addr, &addr.ai_addrlen);
if (res == -1) return;
sprintaddr(service, sizeof(service), &addr);
size = sizeof(targetaddr);
res = getpeername(cnx->q[1].fd, (struct sockaddr*)&targetaddr, &size);
addr.ai_addrlen = sizeof(ss);
res = getpeername(cnx->q[1].fd, addr.ai_addr, &addr.ai_addrlen);
if (res == -1) return;
sprintaddr(target, sizeof(target), &addr);
size = sizeof(forwardfromaddr);
res = getsockname(cnx->q[1].fd, (struct sockaddr*)&forwardfromaddr, &size);
addr.ai_addrlen = sizeof(ss);
res = getsockname(cnx->q[1].fd, addr.ai_addr, &addr.ai_addrlen);
if (res == -1) return;
sprintaddr(local, sizeof(local), &addr);
log_message(LOG_INFO, "connection from %s to %s forwarded from %s to %s\n",
sprintaddr(buf, sizeof(buf), &peeraddr),
sprintaddr(buf2, sizeof(buf2), &listenaddr),
sprintaddr(buf3, sizeof(buf3), &forwardfromaddr),
sprintaddr(buf4, sizeof(buf4), &targetaddr));
log_message(LOG_INFO, "connection from %s to %s forwarded from %s to %s\n",
peer,
service,
local,
target);
}
@@ -446,7 +383,7 @@ void log_connection(struct connection *cnx)
*
* Returns -1 if access is denied, 0 otherwise
*/
int check_access_rights(int in_socket, char* service)
int check_access_rights(int in_socket, const char* service)
{
#ifdef LIBWRAP
struct sockaddr peeraddr;
@@ -485,7 +422,6 @@ int check_access_rights(int in_socket, char* service)
return 0;
}
void setup_signals(void)
{
int res;
@@ -498,11 +434,24 @@ void setup_signals(void)
action.sa_flags = SA_NOCLDWAIT;
res = sigaction(SIGCHLD, &action, NULL);
CHECK_RES_DIE(res, "sigaction");
/* Set SIGTERM to exit. For some reason if it's not set explicitely,
* coverage information is lost when killing the process */
memset(&action, 0, sizeof(action));
action.sa_handler = exit;
res = sigaction(SIGTERM, &action, NULL);
CHECK_RES_DIE(res, "sigaction");
/* Ignore SIGPIPE . */
action.sa_handler = SIG_IGN;
res = sigaction(SIGPIPE, &action, NULL);
CHECK_RES_DIE(res, "sigaction");
}
/* Open syslog connection with appropriate banner;
* banner is made up of basename(bin_name)+"[pid]" */
void setup_syslog(char* bin_name) {
void setup_syslog(const char* bin_name) {
char *name1, *name2;
name1 = strdup(bin_name);
@@ -515,13 +464,13 @@ void setup_syslog(char* bin_name) {
}
/* We don't want to run as root -- drop priviledges if required */
void drop_privileges(char* user_name)
void drop_privileges(const char* user_name)
{
int res;
struct passwd *pw = getpwnam(user_name);
if (!pw) {
fprintf(stderr, "%s: not found\n", user_name);
exit(1);
exit(2);
}
if (verbose)
fprintf(stderr, "turning into %s\n", user_name);
@@ -533,180 +482,17 @@ void drop_privileges(char* user_name)
}
/* Writes my PID */
void write_pid_file(char* pidfile)
void write_pid_file(const char* pidfile)
{
FILE *f;
f = fopen(pidfile, "w");
if (!f) {
perror(pidfile);
exit(1);
exit(3);
}
fprintf(f, "%d\n", getpid());
fclose(f);
}
void printsettings(void)
{
char buf[64];
int i;
for (i = 0; i < ARRAY_SIZE(protocols); i++) {
if (protocols[i].affected)
fprintf(stderr,
"%s addr: %s. libwrap service: %s\n",
protocols[i].description,
sprintaddr(buf, sizeof(buf), &protocols[i].saddr),
protocols[i].service);
}
fprintf(stderr, "listening on:\n");
for (i = 0; i < num_addr_listen; i++) {
fprintf(stderr, "\t%s\n", sprintaddr(buf, sizeof(buf), &addr_listen[i]));
}
fprintf(stderr, "timeout to ssh: %d\n", probing_timeout);
}
/* Adds protocols to the list of options, so command-line parsing uses the
* protocol definition array
* options: array of options to add to; must be big enough
* n_opts: number of options in *options before calling (i.e. where to append)
* prot: array of protocols
* n_prots: number of protocols in *prot
* */
#define PROT_SHIFT 1000 /* protocol options will be 1000, 1001, etc */
void append_protocols(struct option *options, int n_opts, struct proto *prot, int n_prots)
{
int o, p;
for (o = n_opts, p = 0; p < n_prots; o++, p++) {
options[o].name = prot[p].description;
options[o].has_arg = required_argument;
options[o].flag = 0;
options[o].val = p + PROT_SHIFT;
}
}
void parse_cmdline(int argc, char* argv[])
{
int c, affected = 0;
struct option const_options[] = {
{ "inetd", no_argument, &inetd, 1 },
{ "foreground", no_argument, &foreground, 1 },
{ "verbose", no_argument, &verbose, 1 },
{ "numeric", no_argument, &numeric, 1 },
{ "user", required_argument, 0, 'u' },
{ "pidfile", required_argument, 0, 'P' },
{ "timeout", required_argument, 0, 't' },
{ "listen", required_argument, 0, 'p' },
};
struct option all_options[ARRAY_SIZE(const_options) + ARRAY_SIZE(protocols) + 1];
memset(all_options, 0, sizeof(all_options));
memcpy(all_options, const_options, sizeof(const_options));
append_protocols(all_options, ARRAY_SIZE(const_options), protocols, ARRAY_SIZE(protocols));
while ((c = getopt_long_only(argc, argv, "t:l:s:o:T:p:VP:", all_options, NULL)) != -1) {
if (c == 0) continue;
if (c >= PROT_SHIFT) {
affected++;
protocols[c - PROT_SHIFT].affected = 1;
resolve_name(&protocols[c - PROT_SHIFT].saddr, optarg);
continue;
}
switch (c) {
case 't':
probing_timeout = atoi(optarg);
break;
case 'p':
num_addr_listen++;
addr_listen = realloc(addr_listen, num_addr_listen * sizeof(addr_listen[0]));
resolve_name(&addr_listen[num_addr_listen - 1], optarg);
break;
case 'V':
printf("%s %s\n", server_type, VERSION);
exit(0);
case 'u':
user_name = optarg;
break;
case 'P':
pid_file = optarg;
break;
default:
fprintf(stderr, USAGE_STRING);
exit(2);
}
}
if (!affected) {
fprintf(stderr, "At least one target protocol must be specified.\n");
exit(2);
}
if (!num_addr_listen) {
fprintf(stderr, "No listening address specified; use at least one -p option\n");
exit(1);
}
}
int main(int argc, char *argv[])
{
extern char *optarg;
extern int optind;
int res;
int *listen_sockets;
/* Init defaults */
pid_file = "/var/run/sslh.pid";
user_name = "nobody";
foreground = 0;
parse_cmdline(argc, argv);
if (inetd)
{
verbose = 0;
start_shoveler(0);
exit(0);
}
if (verbose)
printsettings();
listen_sockets = malloc(num_addr_listen * sizeof(*listen_sockets));
start_listen_sockets(listen_sockets, addr_listen, num_addr_listen);
free(addr_listen);
if (!foreground)
if (fork() > 0) exit(0); /* Detach */
setup_signals();
write_pid_file(pid_file);
drop_privileges(user_name);
/* New session -- become group leader */
if (getuid() == 0) {
res = setsid();
CHECK_RES_DIE(res, "setsid: already process leader");
}
/* Open syslog connection */
setup_syslog(argv[0]);
main_loop(listen_sockets, num_addr_listen);
return 0;
}
+22 -35
View File
@@ -1,3 +1,7 @@
#ifndef __COMMON_H_
#define __COMMON_H_
#define _GNU_SOURCE
#include <sys/types.h>
#include <fcntl.h>
@@ -16,6 +20,7 @@
#include <syslog.h>
#include <libgen.h>
#include <time.h>
#include <getopt.h>
#ifndef VERSION
#define VERSION "v?"
@@ -46,27 +51,8 @@ enum connection_state {
ST_SHOVELING /* Connexion is established */
};
/* Different types of protocols we support.
* These must match the order of the protocols[] array in common.c */
typedef enum protocol_type {
PROT_SSH,
PROT_OPENVPN,
PROT_TINC,
PROT_SSL,
} T_PROTO_ID;
/* For each protocol we need: */
struct proto {
int affected; /* are we actually using it? */
char* description; /* a string that says what it is (for logging and command-line parsing) */
char* service; /* service name to do libwrap checks */
struct sockaddr_storage saddr; /* where to switch that protocol */
int (*probe)(const char*, int); /* function to probe that protocol */
};
/* A table in common.c contains all the known protocols */
extern struct proto protocols[];
/* this is used to pass protocols through the command-line parameter parsing */
#define PROT_SHIFT 1000 /* protocol options will be 1000, 1001, etc */
/* A 'queue' is composed of a file descriptor (which can be read from or
* written to), and a queue for defered write data */
@@ -94,30 +80,31 @@ struct connection {
/* common.c */
void init_cnx(struct connection *cnx);
void start_listen_sockets(int sockfd[], struct sockaddr_storage addr[], int num_addr);
int connect_addr(struct addrinfo *addr, const char* cnx_name);
int fd2fd(struct queue *target, struct queue *from);
char* sprintaddr(char* buf, size_t size, struct sockaddr_storage* s);
void resolve_name(struct sockaddr_storage *sock, char* fullname) ;
T_PROTO_ID probe_client_protocol(struct connection *cnx);
char* sprintaddr(char* buf, size_t size, struct addrinfo *a);
void resolve_name(struct addrinfo **out, char* fullname);
struct proto* probe_client_protocol(struct connection *cnx);
void log_connection(struct connection *cnx);
int check_access_rights(int in_socket, char* service);
int check_access_rights(int in_socket, const char* service);
void setup_signals(void);
void setup_syslog(char* bin_name);
void drop_privileges(char* user_name);
void write_pid_file(char* pidfile);
void printsettings(void);
void parse_cmdline(int argc, char* argv[]);
void setup_syslog(const char* bin_name);
void drop_privileges(const char* user_name);
void write_pid_file(const char* pidfile);
void log_message(int type, char* msg, ...);
void dump_connection(struct connection *cnx);
int resolve_split_name(struct addrinfo **out, const char* hostname, const char* port);
int start_listen_sockets(int *sockfd[], struct addrinfo *addr_list);
int defer_write(struct queue *q, void* data, int data_size);
int flush_defered(struct queue *q);
extern int probing_timeout, verbose, inetd;
extern struct sockaddr_storage *addr_listen, addr_ssl, addr_ssh, addr_openvpn;
extern int probing_timeout, verbose, inetd, foreground, background, numeric;
extern struct sockaddr_storage addr_ssl, addr_ssh, addr_openvpn;
extern struct addrinfo *addr_listen;
extern const char* USAGE_STRING;
extern char* user_name, *pid_file;
extern const char* user_name, *pid_file;
extern const char* server_type;
/* sslh-fork.c */
@@ -125,4 +112,4 @@ void start_shoveler(int);
void main_loop(int *listen_sockets, int num_addr_listen);
#endif
Executable
+160
View File
@@ -0,0 +1,160 @@
/* echosrv: a simple line echo server with optional prefix adding.
*
* echsrv --listen localhost6:1234 --prefix "ssl: "
*
* This will bind to 1234, and echo every line pre-pending "ssl: ". This is
* used for testing: we create several such servers with different prefixes,
* then we connect test clients that can then check they get the proper data
* back (thus testing that shoveling works both ways) with the correct prefix
* (thus testing it connected to the expected service).
* **/
#define _GNU_SOURCE
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pwd.h>
#include <syslog.h>
#include <libgen.h>
#include <getopt.h>
#include "common.h"
/* Added to make the code compilable under CYGWIN
* */
#ifndef SA_NOCLDWAIT
#define SA_NOCLDWAIT 0
#endif
const char* USAGE_STRING =
"echosrv\n" \
"usage:\n" \
"\techosrv [-v] --listen <address:port> [--prefix <prefix>]\n"
"-v: verbose\n" \
"--listen: address to listen on. Can be specified multiple times.\n" \
"--prefix: add specified prefix before every line echoed.\n"
"";
const char* server_type = "echsrv"; /* keep setup_syslog happy */
/*
* Settings that depend on the command line.
*/
char* prefix = "";
int port;
void parse_cmdline(int argc, char* argv[])
{
int c;
struct option options[] = {
{ "verbose", no_argument, &verbose, 1 },
{ "numeric", no_argument, &numeric, 1 },
{ "listen", required_argument, 0, 'l' },
{ "prefix", required_argument, 0, 'p' },
};
struct addrinfo **a;
while ((c = getopt_long_only(argc, argv, "l:p:", options, NULL)) != -1) {
if (c == 0) continue;
switch (c) {
case 'l':
/* find the end of the listen list */
for (a = &addr_listen; *a; a = &((*a)->ai_next));
/* append the specified addresses */
resolve_name(a, optarg);
break;
case 'p':
prefix = optarg;
break;
default:
fprintf(stderr, "%s", USAGE_STRING);
exit(2);
}
}
if (!addr_listen) {
fprintf(stderr, "No listening port specified\n");
exit(1);
}
}
void start_echo(int fd)
{
int res;
char buffer[1 << 20];
int ret, prefix_len;
prefix_len = strlen(prefix);
memset(buffer, 0, sizeof(buffer));
strcpy(buffer, prefix);
while (1) {
ret = read(fd, buffer + prefix_len, sizeof(buffer));
if (ret == -1) {
fprintf(stderr, "%s", strerror(errno));
return;
}
res = write(fd, buffer, ret + prefix_len);
if (res < 0) {
fprintf(stderr, "%s", strerror(errno));
return;
}
}
}
void main_loop(int listen_sockets[], int num_addr_listen)
{
int in_socket, i;
for (i = 0; i < num_addr_listen; i++) {
if (!fork()) {
while (1)
{
in_socket = accept(listen_sockets[i], 0, 0);
if (verbose) fprintf(stderr, "accepted fd %d\n", in_socket);
if (!fork())
{
close(listen_sockets[i]);
start_echo(in_socket);
exit(0);
}
close(in_socket);
}
}
}
wait(NULL);
}
int main(int argc, char *argv[])
{
extern char *optarg;
extern int optind;
int num_addr_listen;
int *listen_sockets;
parse_cmdline(argc, argv);
num_addr_listen = start_listen_sockets(&listen_sockets, addr_listen);
main_loop(listen_sockets, num_addr_listen);
return 0;
}
+52
View File
@@ -0,0 +1,52 @@
# This file is provided as documentation to show what is
# possible. It should not be used as-is, and probably should
# not be used as a starting point for a working
# configuration. Instead use basic.cfg.
verbose: true;
foreground: true;
inetd: false;
numeric: false;
timeout: 2;
user: "nobody";
pidfile: "/var/run/sslh.pid";
# List of interfaces on which we should listen
listen:
(
{ host: "thelonious"; port: "443"; },
{ host: "thelonious"; port: "8080"; }
);
# List of protocols
#
# Each protocol entry consists of:
# name: name of the protocol
# service: (optional) libwrap service name (see hosts_access(5))
# host: host name to connect that protocol
# port: port number to connect that protocol
# probe: "builtin" or a list of regular expressions
# (can be left out, e.g. to use with on-timeout)
#
# sslh will try each probe in order they are declared, and
# connect to the first that matches.
protocols:
(
{ name: "ssh"; service: "ssh"; host: "localhost"; port: "22"; probe: "builtin"; },
{ name: "openvpn"; host: "localhost"; port: "1194"; probe: [ "^\x00[\x0D-\xFF]$", "^\x00[\x0D-\xFF]\x38" ]; },
{ name: "xmpp"; host: "localhost"; port: "5222"; probe: [ "jabber" ]; },
{ name: "http"; host: "localhost"; port: "80"; probe: "builtin"; },
{ name: "ssl"; host: "localhost"; port: "443"; probe: [ "" ]; },
{ name: "timeout"; service: "daytime"; host: "localhost"; port: "daytime"; }
);
# Optionally, specify to which protocol to connect in case
# of timeout (defaults to "ssh").
# You can timeout to any arbitrary address by setting a
# protocol with no probe, as is the case with this example.
# This enables you to set a tcpd service name for this
# protocol too.
on-timeout: "timeout";
+288
View File
@@ -0,0 +1,288 @@
/*
# probe.c: Code for probing protocols
#
# Copyright (C) 2007-2012 Yves Rutschle
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more
# details.
#
# The full text for the General Public License is here:
# http://www.gnu.org/licenses/gpl.html
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <regex.h>
#include <ctype.h>
#include "probe.h"
static int is_ssh_protocol(const char *p, int len, struct proto*);
static int is_openvpn_protocol(const char *p, int len, struct proto*);
static int is_tinc_protocol(const char *p, int len, struct proto*);
static int is_xmpp_protocol(const char *p, int len, struct proto*);
static int is_http_protocol(const char *p, int len, struct proto*);
static int is_tls_protocol(const char *p, int len, struct proto*);
static int is_true(const char *p, int len, struct proto* proto) { return 1; }
/* Table of protocols that have a built-in probe
*/
static struct proto builtins[] = {
/* description service saddr probe */
{ "ssh", "sshd", NULL, is_ssh_protocol},
{ "openvpn", NULL, NULL, is_openvpn_protocol },
{ "tinc", NULL, NULL, is_tinc_protocol },
{ "xmpp", NULL, NULL, is_xmpp_protocol },
{ "http", NULL, NULL, is_http_protocol },
{ "ssl", NULL, NULL, is_tls_protocol },
{ "tls", NULL, NULL, is_tls_protocol },
{ "anyprot", NULL, NULL, is_true }
};
static struct proto *protocols;
static char* on_timeout = "ssh";
struct proto* get_builtins(void) {
return builtins;
}
int get_num_builtins(void) {
return ARRAY_SIZE(builtins);
}
/* Sets the protocol name to connect to in case of timeout */
void set_ontimeout(const char* name)
{
asprintf(&on_timeout, "%s", name);
}
/* Returns the protocol to connect to in case of timeout;
* if not found, return the first protocol specified
*/
struct proto* timeout_protocol(void)
{
struct proto* p = get_first_protocol();
for (; p && strcmp(p->description, on_timeout); p = p->next);
if (p) return p;
return get_first_protocol();
}
/* returns the first protocol (caller can then follow the *next pointers) */
struct proto* get_first_protocol(void)
{
return protocols;
}
void set_protocol_list(struct proto* prots)
{
protocols = prots;
}
/* From http://grapsus.net/blog/post/Hexadecimal-dump-in-C */
#define HEXDUMP_COLS 16
void hexdump(const char *mem, unsigned int len)
{
unsigned int i, j;
for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++)
{
/* print offset */
if(i % HEXDUMP_COLS == 0)
printf("0x%06x: ", i);
/* print hex data */
if(i < len)
printf("%02x ", 0xFF & mem[i]);
else /* end of block, just aligning for ASCII dump */
printf(" ");
/* print ASCII dump */
if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1)) {
for(j = i - (HEXDUMP_COLS - 1); j <= i; j++) {
if(j >= len) /* end of block, not really printing */
putchar(' ');
else if(isprint(mem[j])) /* printable char */
putchar(0xFF & mem[j]);
else /* other char */
putchar('.');
}
putchar('\n');
}
}
}
/* Is the buffer the beginning of an SSH connection? */
static int is_ssh_protocol(const char *p, int len, struct proto *proto)
{
if (!strncmp(p, "SSH-", 4)) {
return 1;
}
return 0;
}
/* Is the buffer the beginning of an OpenVPN connection?
*
* Code inspired from OpenVPN port-share option; however, OpenVPN code is
* wrong: users using pre-shared secrets have non-initialised key_id fields so
* p[3] & 7 should not be looked at, and also the key_method can be specified
* to 1 which changes the opcode to P_CONTROL_HARD_RESET_CLIENT_V1.
* See:
* http://www.fengnet.com/book/vpns%20illustrated%20tunnels%20%20vpnsand%20ipsec/ch08lev1sec5.html
* and OpenVPN ssl.c, ssl.h and options.c
*/
static int is_openvpn_protocol (const char*p,int len, struct proto *proto)
{
int packet_len = ntohs(*(uint16_t*)p);
return packet_len == len - 2;
}
/* Is the buffer the beginning of a tinc connections?
* (protocol is undocumented, but starts with "0 " in 1.0.15)
* */
static int is_tinc_protocol( const char *p, int len, struct proto *proto)
{
return !strncmp(p, "0 ", 2);
}
/* Is the buffer the beginning of a jabber (XMPP) connections?
* (Protocol is documented (http://tools.ietf.org/html/rfc6120) but for lazy
* clients, just checking first frame containing "jabber" in xml entity)
* */
static int is_xmpp_protocol( const char *p, int len, struct proto *proto)
{
return strstr(p, "jabber") ? 1 : 0;
}
static int probe_http_method(const char *p, const char *opt)
{
return !strcmp(p, opt);
}
/* Is the buffer the beginning of an HTTP connection? */
static int is_http_protocol(const char *p, int len, struct proto *proto)
{
/* If it's got HTTP in the request (HTTP/1.1) then it's HTTP */
if (strstr(p, "HTTP"))
return 1;
/* Otherwise it could be HTTP/1.0 without version: check if it's got an
* HTTP method (RFC2616 5.1.1) */
probe_http_method(p, "OPTIONS");
probe_http_method(p, "GET");
probe_http_method(p, "HEAD");
probe_http_method(p, "POST");
probe_http_method(p, "PUT");
probe_http_method(p, "DELETE");
probe_http_method(p, "TRACE");
probe_http_method(p, "CONNECT");
return 0;
}
static int is_tls_protocol(const char *p, int len, struct proto *proto)
{
/* TLS packet starts with a record "Hello" (0x16), followed by version
* (0x03 0x00-0x03) (RFC6101 A.1)
* This means we reject SSLv2 and lower, which is actually a good thing (RFC6176)
*/
return p[0] == 0x16 && p[1] == 0x03 && ( p[2] >= 0 && p[2] <= 0x03);
}
static int regex_probe(const char *p, int len, struct proto *proto)
{
regex_t** probe_list = (regex_t**)(proto->data);
int i=0;
while (probe_list[i]) {
if (!regexec(probe_list[i], p, 0, NULL, 0)) {
return 1;
}
i++;
}
return 0;
}
/*
* Read the beginning of data coming from the client connection and check if
* it's a known protocol. Then leave the data on the defered
* write buffer of the connection and returns a pointer to the protocol
* structure
*/
struct proto* probe_client_protocol(struct connection *cnx)
{
char buffer[BUFSIZ];
struct proto *p;
int n;
n = read(cnx->q[0].fd, buffer, sizeof(buffer));
/* It's possible that read() returns an error, e.g. if the client
* disconnected between the previous call to select() and now. If that
* happens, we just connect to the default protocol so the caller of this
* function does not have to deal with a specific failure condition (the
* connection will just fail later normally). */
if (n > 0) {
defer_write(&cnx->q[1], buffer, n);
for (p = protocols; p; p = p->next) {
if (! p->probe) continue;
if (verbose) fprintf(stderr, "probing for %s\n", p->description);
if (p->probe(buffer, n, p)) {
if (verbose) fprintf(stderr, "probe %s successful\n", p->description);
return p;
}
}
}
if (verbose)
fprintf(stderr,
"all probes failed, connecting to first protocol: %s\n",
protocols->description);
/* If none worked, return the first one affected (that's completely
* arbitrary) */
return protocols;
}
/* Returns the structure for specified protocol or NULL if not found */
static struct proto* get_protocol(const char* description)
{
int i;
for (i = 0; i < ARRAY_SIZE(builtins); i++) {
if (!strcmp(builtins[i].description, description)) {
return &builtins[i];
}
}
return NULL;
}
/* Returns the probe for specified protocol:
* parameter is the description in builtins[], or "regex"
* */
T_PROBE* get_probe(const char* description) {
struct proto* p = get_protocol(description);
if (p)
return p->probe;
/* Special case of "regex" probe (we don't want to set it in builtins
* because builtins is also used to build the command-line options and
* regexp is not legal on the command line)*/
if (!strcmp(description, "regex"))
return regex_probe;
return NULL;
}
+59
View File
@@ -0,0 +1,59 @@
/* API for probe.c */
#ifndef __PROBE_H_
#define __PROBE_H_
#include "common.h"
struct proto;
typedef int T_PROBE(const char*, int, struct proto*);
/* For each protocol we need: */
struct proto {
const char* description; /* a string that says what it is (for logging and command-line parsing) */
const char* service; /* service name to do libwrap checks */
struct addrinfo *saddr; /* list of addresses to try and switch that protocol */
/* function to probe that protocol; parameters are buffer and length
* containing the data to probe, and a pointer to the protocol structure */
T_PROBE* probe;
void* data; /* opaque pointer ; used to pass list of regex to regex probe */
struct proto *next; /* pointer to next protocol in list, NULL if last */
};
/* Returns a pointer to the array of builtin protocols */
struct proto * get_builtins(void);
/* Returns the number of builtin protocols */
int get_num_builtins(void);
/* Returns the probe for specified protocol */
T_PROBE* get_probe(const char* description);
/* Returns the head of the configured protocols */
struct proto* get_first_protocol(void);
/* Set the list of configured protocols */
void set_protocol_list(struct proto*);
/* probe_client_protocol
*
* Read the beginning of data coming from the client connection and check if
* it's a known protocol. Then leave the data on the defered
* write buffer of the connection and returns a pointer to the protocol
* structure
*/
struct proto* probe_client_protocol(struct connection *cnx);
/* set the protocol to connect to in case of timeout */
void set_ontimeout(const char* name);
/* timeout_protocol
*
* Returns the protocol to connect to in case of timeout
*/
struct proto* timeout_protocol(void);
void hexdump(const char*, unsigned int);
#endif
+2
View File
@@ -1,3 +1,5 @@
LISTEN=ifname:443
SSH=localhost:22
SSL=localhost:443
USER=nobody
PID=/var/run/sslh.pid
+3 -6
View File
@@ -2,6 +2,8 @@
### BEGIN INIT INFO
# Provides: sslh
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 1
# Short-Description: sslh proxy ssl & ssh connections
@@ -13,11 +15,6 @@ facility=user.info
# /etc/init.d/sslh: start and stop the sslh proxy daemon
# Defaults -- can be overridden in /etc/default/sslh
LISTEN=thelonious:443
SSH=localhost:22
SSL=localhost:443
if test -f /etc/default/sslh; then
. /etc/default/sslh
fi
@@ -30,7 +27,7 @@ DAEMON=$PREFIX/sbin/sslh
start()
{
echo "Start services: sslh"
$DAEMON --user nobody --listen ${LISTEN} --ssh ${SSH} --ssl ${SSL}
$DAEMON --user ${USER} --pidfile ${PID} --listen ${LISTEN} --ssh ${SSH} --ssl ${SSL}
logger -t ${tag} -p ${facility} -i 'Started sslh'
}
+1 -1
View File
@@ -20,7 +20,7 @@
SSLH="/usr/local/sbin/sslh"
PIDFILE="/var/run/sslh"
OPTIONS="-p 0.0.0.0:8443 --ssl 127.0.0.1:443 --ssh 127.0.0.1:22"
OPTIONS="--user nobody --pidfile $PIDFILE -p 0.0.0.0:8443 --ssl 127.0.0.1:443 --ssh 127.0.0.1:22"
if [ -f /etc/sysconfig/sslh ]; then
. /etc/sysconfig/sslh
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=SSL/SSH multiplexer
After=network.target
[Service]
EnvironmentFile=/etc/conf.d/sslh
ExecStart=/usr/bin/sslh --foreground $DAEMON_OPTS
KillMode=process
[Install]
WantedBy=multi-user.target
+45 -19
View File
@@ -1,7 +1,7 @@
/*
Reimplementation of sslh in C
sslh-fork: forking server
# Copyright (C) 2007-2008 Yves Rutschle
# Copyright (C) 2007-2012 Yves Rutschle
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
@@ -21,6 +21,7 @@
*/
#include "common.h"
#include "probe.h"
const char* server_type = "sslh-fork";
@@ -68,12 +69,11 @@ void start_shoveler(int in_socket)
{
fd_set fds;
struct timeval tv;
struct sockaddr_storage *saddr;
struct addrinfo *saddr;
int res;
int out_socket;
char *target;
struct connection cnx;
T_PROTO_ID prot;
struct proto *prot;
init_cnx(&cnx);
@@ -92,22 +92,18 @@ void start_shoveler(int in_socket)
prot = probe_client_protocol(&cnx);
} else {
/* Timed out: it's necessarily SSH */
prot = PROT_SSH;
prot = timeout_protocol();
}
saddr = &protocols[prot].saddr;
target = protocols[prot].description;
if (protocols[prot].service &&
check_access_rights(in_socket, protocols[prot].service)) {
saddr = prot->saddr;
if (prot->service &&
check_access_rights(in_socket, prot->service)) {
exit(0);
}
/* Connect the target socket */
out_socket = socket(saddr->ss_family, SOCK_STREAM, 0);
res = connect(out_socket, (struct sockaddr*)saddr, sizeof(addr_ssl));
CHECK_RES_DIE(res, "connect");
if (verbose)
fprintf(stderr, "connected to something\n");
out_socket = connect_addr(saddr, prot->description);
CHECK_RES_DIE(out_socket, "connect");
cnx.q[1].fd = out_socket;
@@ -126,12 +122,32 @@ void start_shoveler(int in_socket)
exit(0);
}
void main_loop(int *listen_sockets, int num_addr_listen)
{
int in_socket, i;
static int *listener_pid;
static int listener_pid_number = 0;
void stop_listeners(int sig)
{
int i;
for (i = 0; i < listener_pid_number; i++) {
kill(listener_pid[i], sig);
}
}
void main_loop(int listen_sockets[], int num_addr_listen)
{
int in_socket, i, res;
struct sigaction action;
listener_pid_number = num_addr_listen;
listener_pid = malloc(listener_pid_number * sizeof(listener_pid[0]));
/* Start one process for each listening address */
for (i = 0; i < num_addr_listen; i++) {
if (!fork()) {
if (!(listener_pid[i] = fork())) {
/* Listening process just accepts a connection, forks, and goes
* back to listening */
while (1)
{
in_socket = accept(listen_sockets[i], 0, 0);
@@ -147,6 +163,16 @@ void main_loop(int *listen_sockets, int num_addr_listen)
}
}
}
/* Set SIGTERM to "stop_listeners" which further kills all listener
* processes. Note this won't kill processes that listeners forked, which
* means active connections remain active. */
memset(&action, 0, sizeof(action));
action.sa_handler = stop_listeners;
res = sigaction(SIGTERM, &action, NULL);
CHECK_RES_DIE(res, "sigaction");
wait(NULL);
}
/* The actual main is in common.c: it's the same for both version of
+512
View File
@@ -0,0 +1,512 @@
/*
# main: processing of config file, command line options and start the main
# loop.
#
# Copyright (C) 2007-2012 Yves Rutschle
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more
# details.
#
# The full text for the General Public License is here:
# http://www.gnu.org/licenses/gpl.html
*/
#define _GNU_SOURCE
#ifdef LIBCONFIG
#include <libconfig.h>
#endif
#include <regex.h>
#include "common.h"
#include "probe.h"
const char* USAGE_STRING =
"sslh " VERSION "\n" \
"usage:\n" \
"\tsslh [-v] [-i] [-V] [-f] [-n] [-F <file>]\n"
"\t[-t <timeout>] [-P <pidfile>] -u <username> -p <add> [-p <addr> ...] \n" \
"%s\n\n" /* Dynamically built list of builtin protocols */ \
"\t[--on-timeout <addr>]\n" \
"-v: verbose\n" \
"-V: version\n" \
"-f: foreground\n" \
"-n: numeric output\n" \
"-F: use configuration file\n" \
"--on-timeout: connect to specified address upon timeout (default: ssh address)\n" \
"-t: seconds to wait before connecting to --on-timeout address.\n" \
"-p: address and port to listen on.\n Can be used several times to bind to several addresses.\n" \
"--[ssh,ssl,...]: where to connect connections from corresponding protocol.\n" \
"-F: specify a configuration file\n" \
"-P: PID file.\n" \
"-i: Run as a inetd service.\n" \
"";
/* Constants for options that have no one-character shorthand */
#define OPT_ONTIMEOUT 257
static struct option const_options[] = {
{ "inetd", no_argument, &inetd, 1 },
{ "foreground", no_argument, &foreground, 1 },
{ "background", no_argument, &background, 1 },
{ "numeric", no_argument, &numeric, 1 },
{ "verbose", no_argument, &verbose, 1 },
{ "user", required_argument, 0, 'u' },
{ "config", required_argument, 0, 'F' },
{ "pidfile", required_argument, 0, 'P' },
{ "timeout", required_argument, 0, 't' },
{ "on-timeout", required_argument, 0, OPT_ONTIMEOUT },
{ "listen", required_argument, 0, 'p' },
{}
};
static struct option* all_options;
static struct proto* builtins;
static const char *optstr = "vt:T:p:VP:F:";
static void print_usage(void)
{
struct proto *p;
int i;
char *prots = "";
p = get_builtins();
for (i = 0; i < get_num_builtins(); i++)
asprintf(&prots, "%s\t[--%s <addr>]\n", prots, p[i].description);
fprintf(stderr, USAGE_STRING, prots);
}
static void printsettings(void)
{
char buf[NI_MAXHOST];
struct addrinfo *a;
struct proto *p;
for (p = get_first_protocol(); p; p = p->next) {
fprintf(stderr,
"%s addr: %s. libwrap service: %s family %d %d\n",
p->description,
sprintaddr(buf, sizeof(buf), p->saddr),
p->service,
p->saddr->ai_family,
p->saddr->ai_addr->sa_family);
}
fprintf(stderr, "listening on:\n");
for (a = addr_listen; a; a = a->ai_next) {
fprintf(stderr, "\t%s\n", sprintaddr(buf, sizeof(buf), a));
}
fprintf(stderr, "timeout: %d\non-timeout: %s\n", probing_timeout,
timeout_protocol()->description);
}
/* Extract configuration on addresses and ports on which to listen.
* out: newly allocated list of addrinfo to listen to
*/
#ifdef LIBCONFIG
static int config_listen(config_t *config, struct addrinfo **listen)
{
config_setting_t *setting, *addr;
int len, i;
const char *hostname, *port;
setting = config_lookup(config, "listen");
if (setting) {
len = config_setting_length(setting);
for (i = 0; i < len; i++) {
addr = config_setting_get_elem(setting, i);
if (! (config_setting_lookup_string(addr, "host", &hostname) &&
config_setting_lookup_string(addr, "port", &port))) {
fprintf(stderr,
"line %d:Incomplete specification (hostname and port required)\n",
config_setting_source_line(addr));
return -1;
}
resolve_split_name(listen, hostname, port);
/* getaddrinfo returned a list of addresses corresponding to the
* specification; move the pointer to the end of that list before
* processing the next specification */
for (; *listen; listen = &((*listen)->ai_next));
}
}
return 0;
}
#endif
#ifdef LIBCONFIG
static void setup_regex_probe(struct proto *p, config_setting_t* probes)
{
int num_probes, errsize, i, res;
char *err;
const char * expr;
regex_t** probe_list;
num_probes = config_setting_length(probes);
if (!num_probes) {
fprintf(stderr, "%s: no probes specified\n", p->description);
exit(1);
}
p->probe = get_probe("regex");
probe_list = calloc(num_probes + 1, sizeof(*probe_list));
p->data = (void*)probe_list;
for (i = 0; i < num_probes; i++) {
probe_list[i] = malloc(sizeof(*(probe_list[i])));
expr = config_setting_get_string_elem(probes, i);
res = regcomp(probe_list[i], expr, 0);
if (res) {
err = malloc(errsize = regerror(res, probe_list[i], NULL, 0));
regerror(res, probe_list[i], err, errsize);
fprintf(stderr, "%s:%s\n", expr, err);
free(err);
exit(1);
}
}
}
#endif
/* Extract configuration for protocols to connect to.
* out: newly-allocated list of protocols
*/
#ifdef LIBCONFIG
static int config_protocols(config_t *config, struct proto **prots)
{
config_setting_t *setting, *prot, *probes;
const char *hostname, *port, *name;
int i, num_prots;
struct proto *p, *prev = NULL;
setting = config_lookup(config, "protocols");
if (setting) {
num_prots = config_setting_length(setting);
for (i = 0; i < num_prots; i++) {
p = calloc(1, sizeof(*p));
if (i == 0) *prots = p;
if (prev) prev->next = p;
prev = p;
prot = config_setting_get_elem(setting, i);
if ((config_setting_lookup_string(prot, "name", &name) &&
config_setting_lookup_string(prot, "host", &hostname) &&
config_setting_lookup_string(prot, "port", &port)
)) {
p->description = name;
config_setting_lookup_string(prot, "service", &(p->service));
resolve_split_name(&(p->saddr), hostname, port);
probes = config_setting_get_member(prot, "probe");
if (probes) {
if (config_setting_is_array(probes)) {
/* If 'probe' is an array, setup a regex probe using the
* array of strings as pattern */
setup_regex_probe(p, probes);
} else {
/* if 'probe' is 'builtin', set the probe to the
* appropriate builtin protocol */
if (!strcmp(config_setting_get_string(probes), "builtin")) {
p->probe = get_probe(name);
if (!p->probe) {
fprintf(stderr, "%s: no builtin probe for this protocol\n", name);
exit(1);
}
} else {
fprintf(stderr, "%s: illegal probe name\n", name);
exit(1);
}
}
}
}
}
}
return 0;
}
#endif
/* Parses a config file
* in: *filename
* out: *listen, a newly-allocated linked list of listen addrinfo
* *prots, a newly-allocated linked list of protocols
*/
#ifdef LIBCONFIG
static int config_parse(char *filename, struct addrinfo **listen, struct proto **prots)
{
config_t config;
long int timeout;
const char* str;
config_init(&config);
if (config_read_file(&config, filename) == CONFIG_FALSE) {
fprintf(stderr, "%s:%d:%s\n",
filename,
config_error_line(&config),
config_error_text(&config));
exit(1);
}
config_lookup_bool(&config, "verbose", &verbose);
config_lookup_bool(&config, "inetd", &inetd);
config_lookup_bool(&config, "foreground", &foreground);
config_lookup_bool(&config, "numeric", &numeric);
if (config_lookup_int(&config, "timeout", &timeout) == CONFIG_TRUE) {
probing_timeout = timeout;
}
if (config_lookup_string(&config, "on-timeout", &str)) {
set_ontimeout(str);
}
config_lookup_string(&config, "user", &user_name);
config_lookup_string(&config, "pidfile", &pid_file);
config_listen(&config, listen);
config_protocols(&config, prots);
return 0;
}
#endif
/* Adds protocols to the list of options, so command-line parsing uses the
* protocol definition array
* options: array of options to add to; must be big enough
* n_opts: number of options in *options before calling (i.e. where to append)
* prot: array of protocols
* n_prots: number of protocols in *prot
* */
static void append_protocols(struct option *options, int n_opts, struct proto *prot , int n_prots)
{
int o, p;
for (o = n_opts, p = 0; p < n_prots; o++, p++) {
options[o].name = prot[p].description;
options[o].has_arg = required_argument;
options[o].flag = 0;
options[o].val = p + PROT_SHIFT;
}
}
static void make_alloptions(void)
{
builtins = get_builtins();
/* Create all_options, composed of const_options followed by one option per
* known protocol */
all_options = calloc(ARRAY_SIZE(const_options) + get_num_builtins(), sizeof(struct option));
memcpy(all_options, const_options, sizeof(const_options));
append_protocols(all_options, ARRAY_SIZE(const_options) - 1, builtins, get_num_builtins());
}
/* Performs a first scan of command line options to see if a configuration file
* is specified. If there is one, parse it now before all other options (so
* configuration file settings can be overridden from the command line).
*
* prots: newly-allocated list of configured protocols, if any.
*/
static void cmdline_config(int argc, char* argv[], struct proto** prots)
{
#ifdef LIBCONFIG
int c, res;
char *config_filename;
#endif
make_alloptions();
#ifdef LIBCONFIG
optind = 1;
opterr = 0; /* we're missing protocol options at this stage so don't output errors */
while ((c = getopt_long_only(argc, argv, optstr, all_options, NULL)) != -1) {
if (c == 'F') {
config_filename = optarg;
/* find the end of the listen list */
res = config_parse(config_filename, &addr_listen, prots);
if (res)
exit(4);
break;
}
}
#endif
}
/* Parse command-line options. prots points to a list of configured protocols,
* potentially non-allocated */
static void parse_cmdline(int argc, char* argv[], struct proto* prots)
{
int c;
struct addrinfo **a;
struct proto *p;
optind = 1;
opterr = 1;
next_arg:
while ((c = getopt_long_only(argc, argv, optstr, all_options, NULL)) != -1) {
if (c == 0) continue;
if (c >= PROT_SHIFT) {
if (prots)
for (p = prots; p && p->next; p = p->next) {
/* override if protocol was already defined by config file
* (note it only overrides address and use builtin probe) */
if (!strcmp(p->description, builtins[c-PROT_SHIFT].description)) {
resolve_name(&(p->saddr), optarg);
p->probe = builtins[c-PROT_SHIFT].probe;
goto next_arg;
}
}
/* At this stage, it's a new protocol: add it to the end of the
* list */
if (!prots) {
/* No protocols yet -- create the list */
p = prots = calloc(1, sizeof(*p));
} else {
p->next = calloc(1, sizeof(*p));
p = p->next;
}
memcpy(p, &builtins[c-PROT_SHIFT], sizeof(*p));
resolve_name(&(p->saddr), optarg);
continue;
}
switch (c) {
case 'F':
/* Legal option, but do nothing, it was already processed in
* cmdline_config() */
#ifndef LIBCONFIG
fprintf(stderr, "Built without libconfig support: configuration file not available.\n");
exit(1);
#endif
break;
case 't':
probing_timeout = atoi(optarg);
break;
case OPT_ONTIMEOUT:
set_ontimeout(optarg);
break;
case 'p':
/* find the end of the listen list */
for (a = &addr_listen; *a; a = &((*a)->ai_next));
/* append the specified addresses */
resolve_name(a, optarg);
break;
case 'V':
printf("%s %s\n", server_type, VERSION);
exit(0);
case 'u':
user_name = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'v':
verbose++;
break;
default:
print_usage();
exit(2);
}
}
if (!prots) {
fprintf(stderr, "At least one target protocol must be specified.\n");
exit(2);
}
set_protocol_list(prots);
if (!addr_listen) {
fprintf(stderr, "No listening address specified; use at least one -p option\n");
exit(1);
}
/* Did command-line override foreground setting? */
if (background)
foreground = 0;
}
int main(int argc, char *argv[])
{
extern char *optarg;
extern int optind;
int res, num_addr_listen;
struct proto* protocols = NULL;
int *listen_sockets;
/* Init defaults */
pid_file = NULL;
user_name = NULL;
cmdline_config(argc, argv, &protocols);
parse_cmdline(argc, argv, protocols);
if (inetd)
{
verbose = 0;
start_shoveler(0);
exit(0);
}
if (verbose)
printsettings();
num_addr_listen = start_listen_sockets(&listen_sockets, addr_listen);
if (!foreground) {
if (fork() > 0) exit(0); /* Detach */
/* New session -- become group leader */
if (getuid() == 0) {
res = setsid();
CHECK_RES_DIE(res, "setsid: already process leader");
}
}
setup_signals();
if (pid_file)
write_pid_file(pid_file);
if (user_name)
drop_privileges(user_name);
/* Open syslog connection */
setup_syslog(argv[0]);
main_loop(listen_sockets, num_addr_listen);
return 0;
}
+31 -28
View File
@@ -1,5 +1,5 @@
/*
sslh: a SSL/SSH multiplexer
sslh-select: mono-processus server
# Copyright (C) 2007-2010 Yves Rutschle
#
@@ -23,6 +23,7 @@
#define __LINUX__
#include "common.h"
#include "probe.h"
const char* server_type = "sslh-select";
@@ -30,7 +31,8 @@ const char* server_type = "sslh-select";
* and then every time we get too many simultaneous connections: e.g. start
* with 100 slots, then if we get more than 100 connections allocate another
* 100 slots, and so on). We never free up connection structures. We try to
* allocate as many structures at once as will fit in one page.
* allocate as many structures at once as will fit in one page (which is 102
* in sslh 1.9 on Linux on x86)
*/
static long cnx_num_alloc;
@@ -55,14 +57,16 @@ int tidy_connection(struct connection *cnx, fd_set *fds, fd_set *fds2)
int i;
for (i = 0; i < 2; i++) {
if (verbose)
fprintf(stderr, "closing fd %d\n", cnx->q[i].fd);
if (cnx->q[i].fd != -1) {
if (verbose)
fprintf(stderr, "closing fd %d\n", cnx->q[i].fd);
close(cnx->q[i].fd);
FD_CLR(cnx->q[i].fd, fds);
FD_CLR(cnx->q[i].fd, fds2);
if (cnx->q[i].defered_data)
free(cnx->q[i].defered_data);
close(cnx->q[i].fd);
FD_CLR(cnx->q[i].fd, fds);
FD_CLR(cnx->q[i].fd, fds2);
if (cnx->q[i].defered_data)
free(cnx->q[i].defered_data);
}
}
init_cnx(cnx);
return 0;
@@ -110,22 +114,17 @@ int accept_new_connection(int listen_socket, struct connection *cnx[], int* cnx_
return in_socket;
}
/* Connect queue 1 of connection to SSL; returns new file descriptor */
int connect_queue(struct connection *cnx, struct sockaddr_storage *addr,
char* cnx_name,
int connect_queue(struct connection *cnx, struct addrinfo *addr,
const char* cnx_name,
fd_set *fds_r, fd_set *fds_w)
{
struct queue *q = &cnx->q[1];
int res;
q->fd = socket(addr->ss_family, SOCK_STREAM, 0);
res = connect(q->fd, (struct sockaddr*)addr, sizeof(*addr));
log_connection(cnx);
if (res == -1) {
tidy_connection(cnx, fds_r, fds_w);
log_message(LOG_ERR, "forward to %s failed\n", cnx_name);
return -1;
} else {
q->fd = connect_addr(addr, cnx_name);
if (q->fd != -1) {
log_connection(cnx);
set_nonblock(q->fd);
flush_defered(q);
if (q->defered_data) {
@@ -134,6 +133,9 @@ int connect_queue(struct connection *cnx, struct sockaddr_storage *addr,
FD_SET(q->fd, fds_r);
}
return q->fd;
} else {
tidy_connection(cnx, fds_r, fds_w);
return -1;
}
}
@@ -188,14 +190,14 @@ int is_fd_active(int fd, fd_set* set)
* That way, each pair of file descriptor (read from one, write to the other)
* is monitored either for read or for write, but never for both.
*/
void main_loop(int *listen_sockets, int num_addr_listen)
void main_loop(int listen_sockets[], int num_addr_listen)
{
fd_set fds_r, fds_w; /* reference fd sets (used to init the next 2) */
fd_set readfds, writefds; /* working read and write fd sets */
struct timeval tv;
int max_fd, in_socket, i, j, res;
struct connection *cnx;
T_PROTO_ID prot;
struct proto *prot;
int num_cnx; /* Number of connections in *cnx */
int num_probing = 0; /* Number of connections currently probing
* We use this to know if we need to time out of
@@ -236,7 +238,8 @@ void main_loop(int *listen_sockets, int num_addr_listen)
for (i = 0; i < num_addr_listen; i++) {
if (FD_ISSET(listen_sockets[i], &readfds)) {
in_socket = accept_new_connection(listen_sockets[i], &cnx, &num_cnx);
num_probing++;
if (in_socket != -1)
num_probing++;
if (in_socket > 0) {
FD_SET(in_socket, &fds_r);
@@ -292,20 +295,20 @@ void main_loop(int *listen_sockets, int num_addr_listen)
/* If timed out it's SSH, otherwise the client sent
* data so probe the protocol */
if ((cnx[i].probe_timeout < time(NULL))) {
prot = PROT_SSH;
prot = timeout_protocol();
} else {
prot = probe_client_protocol(&cnx[i]);
}
/* libwrap check if required for this protocol */
if (protocols[prot].service &&
check_access_rights(in_socket, protocols[prot].service)) {
if (prot->service &&
check_access_rights(in_socket, prot->service)) {
tidy_connection(&cnx[i], &fds_r, &fds_w);
res = -1;
} else {
res = connect_queue(&cnx[i],
&protocols[prot].saddr,
protocols[prot].description,
prot->saddr,
prot->description,
&fds_r, &fds_w);
}
+101 -48
View File
@@ -2,56 +2,75 @@
=head1 NAME
sslh - ssl/ssh multiplexer
sslh - protocol demultiplexer
=head1 SYNOPSIS
sslh [ B<-t> I<num> ] [B<-p> I<listening address> [B<-p> I<listening address> ...] [B<-l> I<target address for SSL>] [B<-s> I<target address for SSH>] [B<-o> I<target address for OpenVPN>] [B<-u> I<username>] [B<-P> I<pidfile>] [-v] [-i] [-V] [-f] [-n]
sslh [B<-F> I<config file>] [ B<-t> I<num> ] [B<-p> I<listening address> [B<-p> I<listening address> ...] [B<--ssl> I<target address for SSL>] [B<--ssh> I<target address for SSH>] [B<--openvpn> I<target address for OpenVPN>] [B<--http> I<target address for HTTP>] [B<--anyprot> I<default target address>] [B<--on-timeout> I<protocol name>] [B<-u> I<username>] [B<-P> I<pidfile>] [-v] [-i] [-V] [-f] [-n]
=head1 DESCRIPTION
B<sslh> accepts HTTPS, SSH and OpenVPN connections on the
same port. This makes it possible to connect to an SSH
server or an OpenVPN on port 443 (e.g. from inside a
corporate firewall, which almost never block port 443) while
still serving HTTPS on that port.
B<sslh> accepts connections on specified ports, and forwards
them further based on tests performed on the first data
packet sent by the remote client.
The idea is to have B<sslh> listen to the external 443 port,
accept the incoming connections, work out what type of
connection it is, and then fordward to the appropriate
server.
Probes for HTTP, SSL, SSH, OpenVPN, tinc, XMPP are
implemented, and any other protocol that can be tested using
a regular expression, can be recognised. A typical use case
is to allow serving several services on port 443 (e.g. to
connect to ssh from inside a corporate firewall, which
almost never block port 443) while still serving HTTPS on
that port.
=head2 Protocol detection
The protocol detection is made based on the first bytes sent
by the client: SSH connections start by identifying each
other's versions using clear text "SSH-2.0" strings (or
equivalent version strings). This is defined in RFC4253,
4.2. Meanwhile, OpenVPN clients start with 0x00 0x0D 0x38.
Additionally, two kind of SSH clients exist: the client
waits for the server to send its version string ("Shy"
client, which is the case of OpenSSH and Putty), or the
client sends its version first ("Bold" client, which is the
case of Bitvise Tunnelier and ConnectBot).
B<sslh> waits for some time for the incoming connection to
send data. If it stays quiet after the timeout period, it is
assumed to be a shy SSH client, and is connected to the SSH
server. Otherwise, B<sslh> reads the first packet the client
provides, and connects it to the SSH server if it starts
with "SSH-", or connects it to the SSL server otherwise.
Hence B<sslh> acts as a protocol demultiplexer, or a
switchboard. Its name comes from its original function to
serve SSH and HTTPS on the same port.
=head2 Libwrap support
One drawback of B<sslh> is that the B<ssh> and B<httpd>
servers do not see the original IP address of the client
anymore, as the connection is forwarded through B<sslh>.
B<sslh> provides enough logging to circumvent that problem.
However it is common to limit access to B<ssh> using
B<libwrap> or B<tcpd>. For this reason, B<sslh> can be
compiled to check SSH accesses against SSH access lists as
defined in F</etc/hosts.allow> and F</etc/hosts.deny>.
One drawback of B<sslh> is that the servers do not see the
original IP address of the client anymore, as the connection
is forwarded through B<sslh>.
For this reason, B<sslh> can be compiled with B<libwrap> to
check accesses defined in F</etc/hosts.allow> and
F</etc/hosts.deny>. Libwrap services can be defined using
the configuration file.
=head2 Configuration file
A configuration file can be supplied to B<sslh>. Command
line arguments override file settings. B<sslh> uses
B<libconfig> to parse the configuration file, so the general
file format is indicated in
L<http://www.hyperrealm.com/libconfig/libconfig_manual.html>.
Please refer to the example configuration file provided with
B<sslh> for the specific format (Options have the same names
as on the command line, except for the list of listen ports
and the list of protocols).
The configuration file makes it possible to specify
protocols using regular expressions: a list of regular
expressions is given as the I<probe> parameter, and if the
first packet received from the client matches any of these
expressions, B<sslh> connects to that protocol.
Alternatively, the I<probe> parameter can be set to
"builtin", to use the compiled probes which are much faster
than regular expressions.
=head2 Probing protocols
When receiving an incoming connection, B<sslh> will read the
first bytes sent be the connecting client. It will then
probe for the protocol in the order specified on the command
line (or the configuration file). Therefore B<--anyprot>
should alway be used last, as it always succeeds and further
protocols will never be tried.
If no data is sent by the client, B<sslh> will eventually
time out and connect to the protocol specified with
B<--on-timeout>, or I<ssh> if none is specified.
=head1 OPTIONS
@@ -59,8 +78,13 @@ defined in F</etc/hosts.allow> and F</etc/hosts.deny>.
=item B<-t> I<num>, B<--timeout> I<num>
Timeout before a connection is considered to be SSH. Default
is 2s.
Timeout before forwarding the connection to the timeout
protocol (which should usually be SSH). Default is 2s.
=item B<--on-timeout> I<protocol name>
Name of the protocol to connect to after the timeout period
is over. Default is 'ssh'.
=item B<-p> I<listening address>, B<--listen> I<listening address>
@@ -72,6 +96,7 @@ This can be specified several times to bind B<sslh> to
several addresses.
=item B<--ssl> I<target address>
=item B<--tls> I<target address>
Interface and port on which to forward SSL connection,
typically I<localhost:443>.
@@ -80,6 +105,11 @@ Note that you can set B<sslh> to listen on I<ext_ip:443> and
B<httpd> to listen on I<localhost:443>: this allows clients
inside your network to just connect directly to B<httpd>.
Also, B<sslh> probes for SSLv3 (or TLSv1) handshake and will
reject connections from clients requesting SSLv2. This is
compliant to RFC6176 which prohibits the usage of SSLv2. If
you wish to accept SSLv2, use B<--default> instead.
=item B<--ssh> I<target address>
Interface and port on which to forward SSH connections,
@@ -90,6 +120,16 @@ typically I<localhost:22>.
Interface and port on which to forward OpenVPN connections,
typically I<localhost:1194>.
=item B<--xmpp> I<target address>
Interface and port on which to forward XMPP connections,
typically I<localhost:5222>.
=item B<--http> I<target address>
Interface and port on which to forward HTTP connections,
typically I<localhost:80>.
=item B<--tinc> I<target address>
Interface and port on which to forward tinc connections,
@@ -98,6 +138,14 @@ typically I<localhost:655>.
This is experimental. If you use this feature, please report
the results (even if it works!)
=item B<--anyprot> I<target address>
Interface and port on which to forward if no other protocol
has been found. Because B<sslh> tries protocols in the order
specified on the command line, this should be specified
last. If no default is specified, B<sslh> will forward
unknown protocols to the first protocol specified.
=item B<-v>, B<--verbose>
Increase verboseness.
@@ -115,14 +163,12 @@ Prints B<sslh> version.
=item B<-u> I<username>, B<--user> I<username>
Requires to run under the specified username. Defaults to
I<nobody> (which is not perfect -- ideally B<sslh> should
run under its own UID).
Requires to run under the specified username.
=item B<-P> I<pidfile>, B<--pid-file> I<pidfile>
=item B<-P> I<pidfile>, B<--pidfile> I<pidfile>
Specifies the file in which to write the PID of the main
server. Defaults to I</var/run/sslh.pid>.
Specifies a file in which to write the PID of the main
server.
=item B<-i>, B<--inetd>
@@ -135,6 +181,13 @@ Runs in foreground. The server will not fork and will remain connected
to the terminal. Messages normally sent to B<syslog> will also be sent
to I<stderr>.
=item B<--background>
Runs in background. This overrides B<foreground> if set in
the configuration file (or on the command line, but there is
no point setting both on the command line unless you have a
personality disorder).
=back
=head1 FILES
@@ -159,7 +212,7 @@ detailed explanation of the variables used by B<sslh>.
Last version available from
L<http://www.rutschle.net/tech/sslh>, and can be tracked
from L<http://freshmeat.net/projects/sslh/>.
from L<http://freecode.com/projects/sslh>.
=head1 AUTHOR
+269 -183
View File
@@ -2,25 +2,17 @@
# Test script for sslh
# The principle is to create two listening sockets which
# will act as the ssh and ssl servers, and then perform a
# number of connections in various combinations to check
# that the server behaves properly.
use strict;
use IO::Socket::INET;
use IO::Socket::INET6;
use Test::More qw/no_plan/;
# We use ports 9000, 9001 and 9002 -- hope that won't clash
# with anything...
my $ssh_port = 9000;
my $ssl_port = 9001;
my $ssh_address = "ip6-localhost:9000";
my $ssl_address = "ip6-localhost:9001";
my $sslh_port = 9002;
my $pidfile = "/tmp/sslh.pid";
# How many connections will be created during the last test
my $NUM_SSL_CNX = 20;
my $NUM_SSH_CNX = 20;
my $no_listen = 9003; # Port on which no-one listens
my $pidfile = "/tmp/sslh_test.pid";
# Which tests do we run
my $SSL_CNX = 1;
@@ -28,202 +20,296 @@ my $SSH_SHY_CNX = 1;
my $SSH_BOLD_CNX = 1;
my $SSL_MIX_SSH = 1;
my $SSH_MIX_SSL = 1;
my $BIG_MSG = 1;
my $MANY_CNX = 1;
my $BIG_MSG = 0; # This test is unreliable
my $STALL_CNX = 0; # This test needs fixing
# the Listen parameter needs to be bigger than the max number of connexions
# we'll make during the last test (we open a bunch of SSH connexions, and
# accept them all at once afterwards)
my $ssh_listen = new IO::Socket::INET(LocalHost=> "localhost:$ssh_port", Blocking => 1, Reuse => 1, Listen => $NUM_SSH_CNX + 1);
die "error1: $!\n" unless $ssh_listen;
# Robustness tests. These are mostly to achieve full test
# coverage, but do not necessarily result in an actual test
# (e.g. some tests need to be run with valgrind to check all
# memory management code).
my $RB_CNX_NOSERVER = 1;
my $RB_PARAM_NOHOST = 1;
my $RB_WRONG_USERNAME = 1;
my $RB_OPEN_PID_FILE = 1;
my $RB_BIND_ADDRESS = 1;
my $RB_RESOLVE_ADDRESS = 1;
my $ssl_listen = new IO::Socket::INET(LocalHost=> "localhost:$ssl_port", Blocking => 1, Reuse => 1, Listen => $NUM_SSL_CNX + 1);
die "error2: $!\n" unless $ssl_listen;
`lcov --directory . --zerocounters`;
my ($ssh_pid, $ssl_pid);
if (!($ssh_pid = fork)) {
exec "./echosrv --listen $ssh_address --prefix 'ssh: '";
}
if (!($ssl_pid = fork)) {
exec "./echosrv --listen $ssl_address --prefix 'ssl: '";
}
my @binaries = ('sslh-select', 'sslh-fork');
for my $binary (@binaries) {
warn "Testing $binary\n";
# Start sslh with the right plumbing
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-fork -v -u $user -p localhost:$sslh_port -s localhost:$ssh_port -l localhost:$ssl_port -P $pidfile";
#exec "./sslh-select -v -f -u $user -p localhost:$sslh_port -s localhost:$ssh_port -l localhost:$ssl_port -P $pidfile";
#exec "valgrind --leak-check=full ./sslh-select -v -f -u $user -p localhost:$sslh_port -s localhost:$ssh_port -l localhost:$ssl_port -P $pidfile";
exit 0;
}
warn "spawned $sslh_pid\n";
sleep 1;
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
my $cmd = "./$binary -v -f -u $user --listen localhost:$sslh_port --ssh $ssh_address --ssl $ssl_address -P $pidfile";
warn "$cmd\n";
#exec $cmd;
exec "valgrind --leak-check=full ./sslh-select -v -f -u $user --listen localhost:$sslh_port --ssh $ssh_address -ssl $ssl_address -P $pidfile";
exit 0;
}
warn "spawned $sslh_pid\n";
sleep 1; # valgrind can be heavy -- wait 5 seconds
my $test_data = "hello world\n";
my $test_data = "hello world\n";
# my $ssl_test_data = (pack 'n', ((length $test_data) + 2)) . $test_data;
my $ssl_test_data = "\x16\x03\x03$test_data\n";
# Test: SSL connection
if ($SSL_CNX) {
print "***Test: SSL connection\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
if (defined $cnx_l) {
print $cnx_l $test_data;
my $ssl_data = $ssl_listen->accept;
my $data = <$ssl_data>;
is($data, $test_data, "SSL connection");
}
}
# Test: Shy SSH connection
if ($SSH_SHY_CNX) {
print "***Test: Shy SSH connection\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 3;
my $ssh_data = $ssh_listen->accept;
print $cnx_h $test_data;
my $data = <$ssh_data>;
is($data, $test_data, "Shy SSH connection");
}
}
# Test: Bold SSH connection
if ($SSH_BOLD_CNX) {
print "***Test: Bold SSH connection\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
my $td = "SSH-2.0 testsuite\n$test_data";
print $cnx_h $td;
my $ssh_data = $ssh_listen->accept;
my $data = <$ssh_data>;
$data .= <$ssh_data>;
is($data, $td, "Bold SSH connection");
}
}
# Test: One SSL half-started then one SSH
if ($SSL_MIX_SSH) {
print "***Test: One SSL half-started then one SSH\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
if (defined $cnx_l) {
print $cnx_l $test_data;
my $cnx_h= new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 3;
my $ssh_data = $ssh_listen->accept;
print $cnx_h $test_data;
my $data_h = <$ssh_data>;
is($data_h, $test_data, "SSH during SSL being established");
}
my $ssl_data = $ssl_listen->accept;
my $data = <$ssl_data>;
is($data, $test_data, "SSL connection interrupted by SSH");
}
}
# Test: One SSH half-started then one SSL
if ($SSH_MIX_SSL) {
print "***Test: One SSH half-started then one SSL\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 3;
if ($SSL_CNX) {
print "***Test: SSL connection\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
if (defined $cnx_l) {
print $cnx_l $test_data;
my $ssl_data = $ssl_listen->accept;
my $data = <$ssl_data>;
is($data, $test_data, "SSL during SSH being established");
print $cnx_l $ssl_test_data;
my $data;
my $n = sysread $cnx_l, $data, 1024;
is($data, "ssl: $ssl_test_data", "SSL connection");
}
my $ssh_data = $ssh_listen->accept;
print $cnx_h $test_data;
my $data = <$ssh_data>;
is($data, $test_data, "SSH connection interrupted by SSL");
}
}
# Test: Big messages
if ($BIG_MSG) {
print "***Test: big message\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
my $test_data2 = "helloworld";
my $rept = 10000;
if (defined $cnx_l) {
print $cnx_l ($test_data2 x $rept);
print $cnx_l "\n";
my $ssl_data = $ssl_listen->accept;
my $data = <$ssl_data>;
is($data, $test_data2 x $rept . "\n", "Big message");
}
}
# Test: several connections active at once
# We start 50 SSH connexions, then open 50 SSL connexion, then accept the 50
# SSH connexions, then we randomize the order of connexions and write 1000
# messages on each connexion and check we get it on the other end.
if ($MANY_CNX) {
print "***Test: several connexions active at once\n";
my (@cnx_h, @ssh_data);
for (1..$NUM_SSH_CNX) {
# Test: Shy SSH connection
if ($SSH_SHY_CNX) {
print "***Test: Shy SSH connection\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "----> $!\n" unless defined $cnx_h;
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
push @cnx_h, $cnx_h;
sleep 3;
print $cnx_h $test_data;
my $data = <$cnx_h>;
is($data, "ssh: $test_data", "Shy SSH connection");
}
}
my (@cnx_l, @ssl_data);
for (1..$NUM_SSL_CNX) {
# Test: Bold SSH connection
if ($SSH_BOLD_CNX) {
print "***Test: Bold SSH connection\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
my $td = "SSH-2.0 testsuite\t$test_data";
print $cnx_h $td;
my $data = <$cnx_h>;
is($data, "ssh: $td", "Bold SSH connection");
}
}
# Test: One SSL half-started then one SSH
if ($SSL_MIX_SSH) {
print "***Test: One SSL half-started then one SSH\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "----> $!\n" unless defined $cnx_l;
warn "$!\n" unless $cnx_l;
if (defined $cnx_l) {
push @cnx_l, $cnx_l;
print $cnx_l " ";
push @ssl_data, ($ssl_listen->accept)[0];
}
}
# give time to the connections to turn to SSH
sleep 4;
# and accept all SSH connections...
for (1..$NUM_SSH_CNX) {
push @ssh_data, $ssh_listen->accept;
}
# Make up a random order so we don't always hit the
# connexions in the same order
# fisher_yates_shuffle( \@array ) : generate a random permutation
# of @array in place (from
# http://docstore.mik.ua/orelly/perl/cookbook/ch04_18.htm,
# modified to shuffle two arrays in the same way)
sub fisher_yates_shuffle {
my ($array1, $array2) = @_;
my $i;
for ($i = @$array1; --$i; ) {
my $j = int rand ($i+1);
next if $i == $j;
@$array1[$i,$j] = @$array1[$j,$i];
@$array2[$i,$j] = @$array2[$j,$i];
print $cnx_l $ssl_test_data;
my $cnx_h= new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 3;
print $cnx_h $test_data;
my $data_h = <$cnx_h>;
is($data_h, "ssh: $test_data", "SSH during SSL being established");
}
my $data;
my $n = sysread $cnx_l, $data, 1024;
is($data, "ssl: $ssl_test_data", "SSL connection interrupted by SSH");
}
}
my @cnx = (@cnx_l, @cnx_l);
my @rcv = (@ssl_data, @ssl_data);
fisher_yates_shuffle(\@rcv, \@cnx);
# Send a bunch of messages
for my $cnt (1..1000) {
foreach (@cnx) {
print $_ "$cnt$test_data";
}
foreach (@rcv) {
my $data = <$_>;
like($data, qr/ ?$cnt$test_data/, "Multiple messages [$cnt]");
# Test: One SSH half-started then one SSL
if ($SSH_MIX_SSL) {
print "***Test: One SSH half-started then one SSL\n";
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 3;
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
if (defined $cnx_l) {
print $cnx_l $ssl_test_data;
my $data;
my $n = sysread $cnx_l, $data, 1024;
is($data, "ssl: $ssl_test_data", "SSL during SSH being established");
}
print $cnx_h $test_data;
my $data = <$cnx_h>;
is($data, "ssh: $test_data", "SSH connection interrupted by SSL");
}
}
# Test: Big messages (careful: don't go over echosrv's buffer limit (1M))
if ($BIG_MSG) {
print "***Test: big message\n";
my $cnx_l = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_l;
my $rept = 1000;
my $test_data2 = $ssl_test_data . ("helloworld"x$rept);
if (defined $cnx_l) {
my $n = syswrite $cnx_l, $test_data2;
my ($data);
$n = sysread $cnx_l, $data, 1 << 20;
is($data, "ssl: ". $test_data2, "Big message");
}
}
# Test: Stalled connection
# Create two connections, stall one, check the other one
# works, unstall first and check it works fine
# This test needs fixing.
# Now that echosrv no longer works on "lines" (finishing
# with '\n'), it may cut blocks randomly with prefixes.
# The whole thing needs to be re-thought as it'll only
# work by chance.
if ($STALL_CNX) {
print "***Test: Stalled connection\n";
my $cnx_1 = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless defined $cnx_1;
my $cnx_2 = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless defined $cnx_2;
my $test_data2 = "helloworld";
sleep 4;
my $rept = 1000;
if (defined $cnx_1 and defined $cnx_2) {
print $cnx_1 ($test_data2 x $rept);
print $cnx_1 "\n";
print $cnx_2 ($test_data2 x $rept);
print $cnx_2 "\n";
my $data = <$cnx_2>;
is($data, "ssh: " . ($test_data2 x $rept) . "\n", "Stalled connection (1)");
print $cnx_2 ($test_data2 x $rept);
print $cnx_2 "\n";
$data = <$cnx_2>;
is($data, "ssh: " . ($test_data2 x $rept) . "\n", "Stalled connection (2)");
$data = <$cnx_1>;
is($data, "ssh: " . ($test_data2 x $rept) . "\n", "Stalled connection (3)");
}
}
my $pid = `cat $pidfile`;
warn "killing $pid\n";
kill TERM => $pid or warn "kill process: $!\n";
sleep 1;
}
# Robustness: Connecting to non-existant server
if ($RB_CNX_NOSERVER) {
print "***Test: Connecting to non-existant server\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u $user --listen localhost:$sslh_port --ssh localhost:$no_listen --ssl localhost:$no_listen -P $pidfile";
}
warn "spawned $sslh_pid\n";
sleep 1;
my $cnx_h = new IO::Socket::INET(PeerHost => "localhost:$sslh_port");
warn "$!\n" unless $cnx_h;
if (defined $cnx_h) {
sleep 1;
my $test_data = "hello";
print $cnx_h $test_data;
}
# Ideally we should check a log is emitted.
kill TERM => `cat $pidfile` or warn "kill: $!\n";
sleep 1;
}
# Robustness: No hostname in address
if ($RB_PARAM_NOHOST) {
print "***Test: No hostname in address\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u $user --listen $sslh_port --ssh $ssh_address --ssl $ssl_address -P $pidfile";
}
warn "spawned $sslh_pid\n";
waitpid $sslh_pid, 0;
my $code = $? >> 8;
warn "exited with $code\n";
is($code, 1, "Exit status on illegal option");
}
# Robustness: User does not exist
if ($RB_WRONG_USERNAME) {
print "***Test: Changing to non-existant username\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u ${user}_doesnt_exist --listen localhost:$sslh_port --ssh $ssh_address --ssl $ssl_address -P $pidfile";
}
warn "spawned $sslh_pid\n";
waitpid $sslh_pid, 0;
my $code = $? >> 8;
warn "exited with $code\n";
is($code, 2, "Exit status on non-existant username");
}
# Robustness: Can't open PID file
if ($RB_OPEN_PID_FILE) {
print "***Test: Can't open PID file\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u $user --listen localhost:$sslh_port --ssh $ssh_address --ssl $ssl_address -P /dont_exist/$pidfile";
# You don't have a /dont_exist/ directory, do you?!
}
warn "spawned $sslh_pid\n";
waitpid $sslh_pid, 0;
my $code = $? >> 8;
warn "exited with $code\n";
is($code, 3, "Exit status if can't open PID file");
}
# Robustness: Can't bind address
if ($RB_BIND_ADDRESS) {
print "***Test: Can't bind address\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u $user --listen 74.125.39.106:9000 --ssh $ssh_address --ssl $ssl_address -P $pidfile";
}
warn "spawned $sslh_pid\n";
waitpid $sslh_pid, 0;
my $code = $? >> 8;
warn "exited with $code\n";
is($code, 1, "Exit status if can't bind address");
}
# Robustness: Can't resolve address
if ($RB_RESOLVE_ADDRESS) {
print "***Test: Can't resolve address\n";
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
exec "./sslh-select -v -f -u $user --listen blahblah.dontexist:9000 --ssh $ssh_address --ssl $ssl_address -P $pidfile";
}
warn "spawned $sslh_pid\n";
waitpid $sslh_pid, 0;
my $code = $? >> 8;
warn "exited with $code\n";
is($code, 4, "Exit status if can't resolve address");
}
`lcov --directory . --capture --output-file sslh_cov.info`;
`genhtml sslh_cov.info`;
`killall echosrv`;
kill 15, `cat $pidfile` or warn "kill: $!\n";
Executable
+128
View File
@@ -0,0 +1,128 @@
#! /usr/bin/perl -w
# Test script for sslh -- mass communication
# This creates many clients that perform concurrent
# connections, disconnect at any time, and try to generally
# behave as badly as possible.
# It can be used to test sslh behaves properly with many
# clients, however its main use is to get an idea of how
# much load it can take on your system before things start
# to go wrong.
use strict;
use IO::Socket::INET6;
use Data::Dumper;
## BEGIN TEST CONFIG
# Do we test sslh-select or sslh-fork?
my $sslh_binary = "./sslh-select";
# How many clients to we start for each protocol?
my $NUM_CNX = 30;
# Delay between starting new processes when starting up. If
# you start 200 processes in under a second, things go wrong
# and it's not sslh's fault (typically the echosrv won't be
# forking fast enough).
my $start_time_delay = 1;
# If you test 4 protocols, you'll start $NUM_CNX * 4 clients
# (e.g. 40), starting one every $start_time_delay seconds.
# Max times we repeat the test string: allows to test for
# large messages.
my $block_rpt = 4096;
# Probability to stop a client after a message (e.g. with
# .01 a client will send an average of 100 messages before
# disconnecting).
my $stop_client_probability = .001;
# What protocols we test, and on what ports
# Just comment out protocols you don't want to use.
my %protocols = (
"ssh" => { address => "localhost:9001", client => client("ssh") },
"ssl" => { address => "localhost:9002", client => client("ssl") },
"openvpn" => {address => "localhost:9003", client => client("openvpn") },
"tinc" => {address => "localhost:9004", client => client("tinc") },
);
##END CONFIG
# We use ports 9000, 9001 and 9002 -- hope that won't clash
# with anything...
my $sslh_address = "localhost:9000";
my $pidfile = "/tmp/sslh_test.pid";
sub client {
my ($service) = @_;
return sub {
while (1) {
my $cnx = new IO::Socket::INET(PeerHost => $sslh_address);
my $test_data = "$service testing " x int(rand($block_rpt)+1) . "\n";
sleep 5 if $service eq "ssh";
if ($service eq "openvpn") {
syswrite $cnx, "\x00\x0F\x38\n";
my $msg;
sysread $cnx, $msg, 14; # length "openvpn: \x0\xF\x38\n" => 14
}
if ($service eq "tinc") {
syswrite $cnx, "0 \n";
my $msg;
sysread $cnx, $msg, 10; # length "tinc: 0 \n" => 10
}
while (1) {
print $cnx $test_data;
my $r = <$cnx>;
($? = 1, die "$service got [$r]\n") if ($r ne "$service: $test_data");
last if rand(1) < $stop_client_probability;
}
}
exit 0;
}
}
foreach my $p (keys %protocols) {
if (!fork) {
exec "./echosrv --listen $protocols{$p}->{address} --prefix '$p: '";
}
}
# Start sslh with the right plumbing
my $sslh_pid;
if (!($sslh_pid = fork)) {
my $user = (getpwuid $<)[0]; # Run under current username
my $prots = join " ", map "--$_ $protocols{$_}->{address}", keys %protocols;
my $cmd = "$sslh_binary -f -t 3 -u $user --listen $sslh_address $prots -P $pidfile";
print "$cmd\n";
exec $cmd;
exit 0;
}
warn "spawned $sslh_pid\n";
sleep 2; # valgrind can be heavy -- wait 5 seconds
for (1 .. $NUM_CNX) {
foreach my $p (keys %protocols) {
if (!fork) {
warn "starting $p\n";
&{$protocols{$p}->{client}};
exit;
}
# Give a little time so we don't overrun the
# listen(2) backlog.
select undef, undef, undef, $start_time_delay;
}
}
wait;
`killall echosrv`;