1
/* -- sslhelper.c -- */
8
#include "connections.h"
11
#define OPENSSL_INETD 1
13
#define OPENSSL_HTTPS 3
14
#define OPENSSL_REVERSE 4
18
#if LIBVNCSERVER_HAVE_FORK
19
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
24
#ifdef NO_SSL_OR_UNIXPW
26
#undef LIBVNCSERVER_HAVE_LIBSSL
27
#define LIBVNCSERVER_HAVE_LIBSSL 0
31
int openssl_sock = -1;
32
int openssl_port_num = 0;
34
pid_t openssl_last_helper_pid = 0;
35
char *openssl_last_ip = NULL;
37
static char *certret = NULL;
38
static int certret_fd = -1;
40
char *certret_str = NULL;
42
void raw_xfer(int csock, int s_in, int s_out);
44
#if !LIBVNCSERVER_HAVE_LIBSSL
45
int openssl_present(void) {return 0;}
46
static void badnews(void) {
49
rfbLog("** not compiled with libssl OpenSSL support **\n");
52
void openssl_init(int isclient) {badnews();}
53
void openssl_port(void) {badnews();}
54
void https_port(void) {badnews();}
55
void check_openssl(void) {if (use_openssl) badnews();}
56
void check_https(void) {if (use_openssl) badnews();}
57
void ssl_helper_pid(pid_t pid, int sock) {badnews(); sock = pid;}
58
void accept_openssl(int mode, int presock) {mode = 0; presock = 0; badnews();}
59
char *find_openssl_bin(void) {badnews(); return NULL;}
60
char *get_saved_pem(char *string, int create) {badnews(); return NULL;}
64
* This is because on older systems both zlib.h and ssl.h define
65
* 'free_func' nothing we do below (currently) induces an external
66
* dependency on 'free_func'.
68
#define free_func my_jolly_little_free_func
70
#include <openssl/ssl.h>
71
#include <openssl/err.h>
72
#include <openssl/rand.h>
74
int openssl_present(void);
75
void openssl_init(int isclient);
76
void openssl_port(void);
77
void check_openssl(void);
78
void check_https(void);
79
void ssl_helper_pid(pid_t pid, int sock);
80
void accept_openssl(int mode, int presock);
81
char *find_openssl_bin(void);
82
char *get_saved_pem(char *string, int create);
84
static SSL_CTX *ctx = NULL;
85
static RSA *rsa_512 = NULL;
86
static RSA *rsa_1024 = NULL;
87
static SSL *ssl = NULL;
90
static void init_prng(void);
91
static void sslerrexit(void);
92
static char *get_input(char *tag, char **in);
93
static char *create_tmp_pem(char *path, int prompt);
94
static int ssl_init(int s_in, int s_out);
95
static void ssl_xfer(int csock, int s_in, int s_out, int is_https);
98
void openssl_init(int isclient) {
99
rfbLog("openssl_init: fork is not supported. cannot create"
100
" ssl helper process.\n");
103
int openssl_present(void) {return 0;}
105
int openssl_present(void) {return 1;}
107
static void sslerrexit(void) {
108
unsigned long err = ERR_get_error();
112
ERR_error_string(err, str);
113
fprintf(stderr, "ssl error: %s\n", str);
118
char *get_saved_pem(char *save, int create) {
119
char *s = NULL, *path, *cdir, *tmp;
124
rfbLog("get_saved_pem: save string is null.\n");
128
if (strstr(save, "SAVE_PROMPT") == save) {
130
s = save + strlen("SAVE_PROMPT");
131
} else if (strstr(save, "SAVE") == save) {
132
s = save + strlen("SAVE");
134
rfbLog("get_saved_pem: invalid save string: %s\n", save);
137
if (strchr(s, '/')) {
138
rfbLog("get_saved_pem: invalid save string: %s\n", s);
142
cdir = get_Cert_dir(NULL, &tmp);
143
if (! cdir || ! tmp) {
144
rfbLog("get_saved_pem: could not find Cert dir.\n");
148
len = strlen(cdir) + strlen("/server.pem") + strlen(s) + 1;
150
path = (char *) malloc(len);
151
sprintf(path, "%s/server%s.pem", cdir, s);
153
if (stat(path, &sbuf) != 0) {
156
new = create_tmp_pem(path, prompt);
157
if (! getenv("X11VNC_SSL_NO_PASSPHRASE") && ! inetd) {
167
FILE *in = fopen(path, "r");
170
rfbLog("Using SSL Certificate:\n");
171
fprintf(stderr, "\n");
172
while (fgets(line, 1024, in) != NULL) {
173
if (strstr(line, "BEGIN CERTIFICATE")) {
177
fprintf(stderr, "%s", line);
179
if (strstr(line, "END CERTIFICATE")) {
182
if (strstr(line, "PRIVATE KEY")) {
186
fprintf(stderr, "\n");
193
static char *get_input(char *tag, char **in) {
194
char line[1024], *str;
196
if (! tag || ! in || ! *in) {
200
fprintf(stderr, "%s:\n [%s] ", tag, *in);
201
if (fgets(line, 1024, stdin) == NULL) {
202
rfbLog("could not read stdin!\n");
203
rfbLogPerror("fgets");
206
if ((str = strrchr(line, '\n')) != NULL) {
210
if (!strcmp(str, "")) {
217
char *find_openssl_bin(void) {
218
char *path, *exe, *p, *gp;
220
int found_openssl = 0;
221
char extra[] = ":/usr/bin:/bin:/usr/sbin:/usr/local/bin"
222
":/usr/local/sbin:/usr/sfw/bin";
226
fprintf(stderr, "could not find openssl(1) program in PATH.\n");
230
path = (char *) malloc(strlen(gp) + strlen(extra) + 1);
234
/* find openssl binary: */
235
exe = (char *) malloc(strlen(path) + strlen("/openssl") + 1);
236
p = strtok(path, ":");
239
sprintf(exe, "%s/openssl", p);
240
if (stat(exe, &sbuf) == 0) {
241
if (! S_ISDIR(sbuf.st_mode)) {
246
p = strtok(NULL, ":");
250
if (! found_openssl) {
251
fprintf(stderr, "could not find openssl(1) program in PATH.\n");
252
fprintf(stderr, "(also checked: %s)\n", extra);
258
/* uses /usr/bin/openssl to create a tmp cert */
260
static char *create_tmp_pem(char *pathin, int prompt) {
263
char cnf[] = "/tmp/x11vnc-cnf.XXXXXX";
264
char pem[] = "/tmp/x11vnc-pem.XXXXXX";
265
char str[8*1024], line[1024], *exe;
266
int cnf_fd, pem_fd, status, show_cert = 1;
268
char *C, *L, *OU, *O, *CN, *EM;
272
"default_bits = 2048\n"
273
"encrypt_key = yes\n"
274
"distinguished_name = req_dn\n"
275
"x509_extensions = cert_type\n"
280
"organizationalUnitName=%s\n"
281
"organizationName=%s\n"
286
"nsCertType = server\n"
290
L = strdup(UT.sysname ? UT.sysname : "unknown-os");
291
snprintf(line, 1024, "%s-%f", UT.nodename ? UT.nodename :
292
"unknown-node", dnow());
296
O = strdup("x11vnc");
298
snprintf(line, 1024, "x11vnc-SELF-SIGNED-CERT-%d", getpid());
300
snprintf(line, 1024, "x11vnc-SELF-SIGNED-TEMPORARY-CERT-%d",
305
EM = strdup("x11vnc@server.nowhere");
308
if (no_external_cmds || !cmd_ok("ssl")) {
309
rfbLog("create_tmp_pem: cannot run external commands.\n");
315
rfbLog("Creating a self-signed PEM certificate...\n");
317
rfbLog("Creating a temporary, self-signed PEM certificate...\n");
321
rfbLog("This will NOT prevent man-in-the-middle attacks UNLESS you\n");
322
rfbLog("get the certificate information to the VNC viewers SSL\n");
323
rfbLog("tunnel configuration or you take the extra steps to sign it\n");
324
rfbLog("with a CA key. However, it will prevent passive network\n");
325
rfbLog("sniffing.\n");
327
rfbLog("The cert inside -----BEGIN CERTIFICATE-----\n");
329
rfbLog(" -----END CERTIFICATE-----\n");
330
rfbLog("printed below may be used on the VNC viewer-side to\n");
331
rfbLog("authenticate this server for this session. See the -ssl\n");
332
rfbLog("help output and the FAQ for how to create a permanent\n");
333
rfbLog("server certificate.\n");
336
exe = find_openssl_bin();
341
/* create template file with our made up stuff: */
343
fprintf(stderr, "\nReply to the following prompts to set"
344
" your Certificate parameters.\n");
345
fprintf(stderr, "(press Enter to accept the default in [...], "
346
"or type in the value you want)\n\n");
347
C = get_input("CountryName", &C);
348
L = get_input("LocalityName", &L);
349
OU = get_input("OrganizationalUnitName", &OU);
350
O = get_input("OrganizationalName", &O);
351
CN = get_input("CommonName", &CN);
352
EM = get_input("EmailAddress", &EM);
354
sprintf(str, tmpl, C, L, OU, O, CN, EM);
356
cnf_fd = mkstemp(cnf);
357
pem_fd = mkstemp(pem);
359
if (cnf_fd < 0 || pem_fd < 0) {
365
write(cnf_fd, str, strlen(str));
378
} else if (pid == 0) {
380
for (i=0; i<256; i++) {
383
execlp(exe, exe, "req", "-new", "-x509", "-nodes",
384
"-days", days, "-config", cnf, "-out", pem,
385
"-keyout", pem, (char *)0);
388
pidw = waitpid(pid, &status, 0);
392
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
399
/* make DH parameters */
403
} else if (pid == 0) {
405
for (i=0; i<256; i++) {
408
/* rather slow at 1024 */
409
execlp(exe, exe, "dhparam", "-out", cnf, "512", (char *)0);
412
pidw = waitpid(pid, &status, 0);
416
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
423
in = fopen(cnf, "r");
427
out = fopen(pem, "a");
432
while (fgets(line, 1024, in) != NULL) {
433
fprintf(out, "%s", line);
442
if (pathin != NULL) {
443
char *q, *pathcrt = strdup(pathin);
447
q = strrchr(pathcrt, '/');
449
q = strstr(q, ".pem");
454
crt = fopen(pathcrt, "w");
458
rfbLog("could not open: %s\n", pathcrt);
459
rfbLogPerror("fopen");
463
out = fopen(pathin, "w");
466
rfbLog("could not open: %s\n", pathin);
467
rfbLogPerror("fopen");
472
in = fopen(pem, "r");
474
rfbLog("could not open: %s\n", pem);
475
rfbLogPerror("fopen");
482
while (fgets(line, 1024, in) != NULL) {
483
if (strstr(line, "BEGIN CERTIFICATE")) {
486
fprintf(out, "%s", line);
488
fprintf(crt, "%s", line);
490
if (strstr(line, "END CERTIFICATE")) {
493
if (strstr(line, "PRIVATE KEY")) {
505
sprintf(cmd, "openssl x509 -text -in '%s' 1>&2", pem);
507
sprintf(cmd, "openssl x509 -text -in '%s'", pem);
509
fprintf(stderr, "\n");
511
fprintf(stderr, "\n");
516
return strdup(pathin);
522
static int pem_passwd_callback(char *buf, int size, int rwflag,
530
fprintf(stderr, "\nA passphrase is needed to unlock an OpenSSL "
531
"private key (PEM file).\n");
532
fprintf(stderr, "Enter passphrase> ");
533
system("stty -echo");
534
if(fgets(line, 1024, stdin) == NULL) {
535
fprintf(stdout, "\n");
540
fprintf(stdout, "\n\n");
541
q = strrchr(line, '\n');
545
line[1024 - 1] = '\0';
546
strncpy(buf, line, size);
547
buf[size - 1] = '\0';
549
if (0) rwflag = 0; /* compiler warning. */
550
if (0) userdata = 0; /* compiler warning. */
555
static int appendfile(FILE *out, char *infile) {
560
rfbLog("appendfile: null infile.\n");
564
rfbLog("appendfile: null out handle.\n");
568
in = fopen(infile, "r");
571
rfbLog("appendfile: %s\n", infile);
572
rfbLogPerror("fopen");
576
while (fgets(line, 1024, in) != NULL) {
577
fprintf(out, "%s", line);
583
static char *get_ssl_verify_file(char *str_in) {
584
char *p, *str, *cdir, *tmp;
585
char *tfile, *tfile2;
591
rfbLog("get_ssl_verify_file: no filename\n");
595
if (stat(str_in, &sbuf) == 0) {
596
/* assume he knows what he is doing. */
600
cdir = get_Cert_dir(NULL, &tmp);
601
if (! cdir || ! tmp) {
602
rfbLog("get_ssl_verify_file: invalid cert-dir.\n");
606
tfile = (char *) malloc(strlen(tmp) + 1024);
607
tfile2 = (char *) malloc(strlen(tmp) + 1024);
609
sprintf(tfile, "%s/sslverify-load-%d.crts", tmp, getpid());
611
file = fopen(tfile, "w");
614
rfbLog("get_ssl_verify_file: %s\n", tfile);
615
rfbLogPerror("fopen");
619
str = strdup(str_in);
620
p = strtok(str, ",");
623
if (!strcmp(p, "CA")) {
624
sprintf(tfile2, "%s/CA/cacert.pem", cdir);
625
if (! appendfile(file, tfile2)) {
629
fprintf(stderr, "sslverify: loaded %s\n", tfile2);
632
} else if (!strcmp(p, "clients")) {
636
sprintf(tfile2, "%s/clients", cdir);
637
dir = opendir(tfile2);
639
rfbLog("get_ssl_verify_file: %s\n", tfile2);
640
rfbLogPerror("opendir");
644
while ( (dp = readdir(dir)) != NULL) {
645
char *n = dp->d_name;
646
char *q = strstr(n, ".crt");
648
if (! q || strlen(q) != strlen(".crt")) {
651
if (strlen(n) > 512) {
655
sprintf(tfile2, "%s/clients/%s", cdir, n);
656
if (! appendfile(file, tfile2)) {
660
fprintf(stderr, "sslverify: loaded %s\n",
667
if (strlen(p) > 512) {
671
sprintf(tfile2, "%s/clients/%s.crt", cdir, p);
672
if (stat(tfile2, &sbuf) != 0) {
673
sprintf(tfile2, "%s/clients/%s", cdir, p);
675
if (! appendfile(file, tfile2)) {
679
fprintf(stderr, "sslverify: loaded %s\n", tfile2);
682
p = strtok(NULL, ",");
688
fprintf(stderr, "sslverify: using %d client certs in %s\n", count,
694
int ssl_client_mode = 0;
696
void openssl_init(int isclient) {
697
int db = 0, tmp_pem = 0, do_dh;
701
static int first = 1;
707
rfbLog("Initializing SSL (%s connect mode).\n", isclient ? "client":"server");
710
if (db) fprintf(stderr, "\nSSL_load_error_strings()\n");
712
SSL_load_error_strings();
714
if (db) fprintf(stderr, "SSL_library_init()\n");
718
if (db) fprintf(stderr, "init_prng()\n");
731
if (ssl_client_mode) {
732
if (db) fprintf(stderr, "SSLv23_client_method()\n");
733
ctx = SSL_CTX_new( SSLv23_client_method() );
735
if (db) fprintf(stderr, "SSLv23_server_method()\n");
736
ctx = SSL_CTX_new( SSLv23_server_method() );
740
rfbLog("openssl_init: SSL_CTX_new failed.\n");
745
rsa_512 = RSA_generate_key(512, RSA_F4, NULL, NULL);
746
if (rsa_512 == NULL) {
747
rfbLog("openssl_init: RSA_generate_key(512) failed.\n");
751
rfbLog("created 512 bit temporary RSA key: %.3fs\n", dnow() - ds);
754
rsa_1024 = RSA_generate_key(1024, RSA_F4, NULL, NULL);
755
if (rsa_1024 == NULL) {
756
rfbLog("openssl_init: RSA_generate_key(1024) failed.\n");
760
rfbLog("created 1024 bit temporary RSA key: %.3fs\n", dnow() - ds);
762
if (db) fprintf(stderr, "SSL_CTX_set_tmp_rsa()\n");
764
if (! SSL_CTX_set_tmp_rsa(ctx, rsa_1024)) {
765
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
770
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
771
mode |= SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
772
SSL_CTX_set_mode(ctx, mode);
774
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
775
SSL_CTX_set_timeout(ctx, 300);
779
openssl_pem = create_tmp_pem(NULL, 0);
781
rfbLog("openssl_init: could not create temporary,"
782
" self-signed PEM.\n");
787
} else if (strstr(openssl_pem, "SAVE") == openssl_pem) {
788
openssl_pem = get_saved_pem(openssl_pem, 1);
790
rfbLog("openssl_init: could not create or open"
791
" saved PEM:\n", openssl_pem);
797
rfbLog("using PEM %s %.3fs\n", openssl_pem, dnow() - ds);
799
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_callback);
806
in = fopen(openssl_pem, "r");
808
rfbLogPerror("fopen");
811
bio = BIO_new_fp(in, BIO_CLOSE|BIO_FP_TEXT);
813
rfbLog("openssl_init: BIO_new_fp() failed.\n");
816
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
818
rfbLog("openssl_init: PEM_read_bio_DHparams() failed.\n");
823
SSL_CTX_set_tmp_dh(ctx, dh);
824
rfbLog("loaded Diffie Hellman %d bits, %.3fs\n",
825
8*DH_size(dh), dnow()-ds);
829
if (! SSL_CTX_use_certificate_chain_file(ctx, openssl_pem)) {
830
rfbLog("openssl_init: SSL_CTX_use_certificate_chain_file() failed.\n");
833
if (! SSL_CTX_use_RSAPrivateKey_file(ctx, openssl_pem,
835
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
838
if (! SSL_CTX_check_private_key(ctx)) {
839
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
843
if (tmp_pem && ! getenv("X11VNC_KEEP_TMP_PEM")) {
844
if (getenv("X11VNC_SHOW_TMP_PEM")) {
845
FILE *in = fopen(openssl_pem, "r");
848
fprintf(stderr, "\n");
849
while (fgets(line, 128, in) != NULL) {
850
fprintf(stderr, "%s", line);
852
fprintf(stderr, "\n");
866
file = get_ssl_verify_file(ssl_verify);
868
if (!file || stat(file, &sbuf) != 0) {
869
rfbLog("openssl_init: -sslverify does not exists %s.\n",
870
file ? file : "null");
871
rfbLogPerror("stat");
874
if (! S_ISDIR(sbuf.st_mode)) {
875
if (! SSL_CTX_load_verify_locations(ctx, file, NULL)) {
876
rfbLog("openssl_init: SSL_CTX_load_verify_"
877
"locations() failed.\n");
881
if (! SSL_CTX_load_verify_locations(ctx, NULL, file)) {
882
rfbLog("openssl_init: SSL_CTX_load_verify_"
883
"locations() failed.\n");
888
lvl = SSL_VERIFY_FAIL_IF_NO_PEER_CERT|SSL_VERIFY_PEER;
889
SSL_CTX_set_verify(ctx, lvl, NULL);
890
if (strstr(file, "tmp/sslverify-load-")) {
895
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
901
void openssl_port(void) {
902
int sock, shutdown = 0;
904
static in_addr_t iface = INADDR_ANY;
908
rfbLog("openssl_port: no screen!\n");
916
if (screen->listenSock > -1 && screen->port > 0) {
920
if (screen->listenInterface) {
921
iface = screen->listenInterface;
925
if (db) fprintf(stderr, "shutting down %d/%d\n",
926
port, screen->listenSock);
927
rfbShutdownSockets(screen);
930
sock = rfbListenOnTCPPort(port, iface);
932
rfbLog("openssl_port: could not reopen port %d\n", port);
935
rfbLog("openssl_port: listen on port/sock %d/%d\n", port, sock);
937
announce(port, 1, NULL);
940
openssl_port_num = port;
946
void https_port(void) {
949
static in_addr_t iface = INADDR_ANY;
952
/* as openssl_port above: open a listening socket for pure https: */
953
if (https_port_num < 0) {
957
rfbLog("https_port: no screen!\n");
960
if (screen->listenInterface) {
961
iface = screen->listenInterface;
964
if (https_port_num == 0) {
965
https_port_num = find_free_port(5801, 5851);
967
if (https_port_num <= 0) {
968
rfbLog("https_port: could not find port %d\n", https_port_num);
971
port = https_port_num;
973
sock = rfbListenOnTCPPort(port, iface);
975
rfbLog("https_port: could not open port %d\n", port);
978
if (db) fprintf(stderr, "https_port: listen on port/sock %d/%d\n",
984
static void lose_ram(void) {
986
* for a forked child that will be around for a long time
987
* without doing exec(). we really should re-exec, but a pain
988
* to redo all SSL ctx.
995
/* utility to keep track of existing helper processes: */
997
void ssl_helper_pid(pid_t pid, int sock) {
999
static pid_t helpers[HPSIZE];
1000
static int sockets[HPSIZE], first = 1;
1001
int i, empty, set, status, db = 0;
1004
for (i=0; i < HPSIZE; i++) {
1013
for (i=0; i < HPSIZE; i++) {
1014
if (helpers[i] == 0) {
1018
if (kill(helpers[i], 0) == 0) {
1020
if (sockets[i] >= 0) {
1023
kill(helpers[i], SIGTERM);
1026
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
1027
if (db) fprintf(stderr, "waitpid(%d)\n", helpers[i]);
1028
waitpid(helpers[i], &status, WNOHANG);
1040
if (db) fprintf(stderr, "ssl_helper_pid(%d, %d)\n", pid, sock);
1042
/* add (or delete for sock == -1) */
1045
for (i=0; i < HPSIZE; i++) {
1046
if (helpers[i] == pid) {
1049
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
1050
if (db) fprintf(stderr, "waitpid(%d) 2\n", helpers[i]);
1051
waitpid(helpers[i], &status, WNOHANG);
1057
} else if (empty == -1 && helpers[i] == 0) {
1061
if (set || sock == -1) {
1065
/* now try to store */
1067
helpers[empty] = pid;
1068
sockets[empty] = sock;
1071
for (i=0; i < HPSIZE; i++) {
1072
if (helpers[i] == 0) {
1075
/* clear out stale pids: */
1076
if (kill(helpers[i], 0) != 0) {
1086
helpers[empty] = pid;
1087
sockets[empty] = sock;
1091
static int is_ssl_readable(int s_in, time_t last_https, char *last_get,
1097
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
1098
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
1102
* we'll do a select() on s_in for reading. this is not an
1103
* absolute proof that SSL_read is ready (XXX use SSL utility).
1108
if (mode == OPENSSL_INETD) {
1110
* https via inetd is icky because x11vnc is restarted
1111
* for each socket (and some clients send requests
1118
* increase the timeout if we know HTTP traffic has occurred
1121
if (time(NULL) < last_https + 30) {
1123
if (last_get && strstr(last_get, "VncViewer")) {
1127
if (getenv("X11VNC_HTTPS_VS_VNC_TIMEOUT")) {
1128
tv.tv_sec = atoi(getenv("X11VNC_HTTPS_VS_VNC_TIMEOUT"));
1130
if (db) fprintf(stderr, "tv_sec: %d - %s\n", (int) tv.tv_sec, last_get);
1136
nfd = select(s_in+1, &rd, NULL, NULL, &tv);
1137
} while (nfd < 0 && errno == EINTR);
1139
if (db) fprintf(stderr, "https nfd: %d\n", nfd);
1141
if (nfd <= 0 || ! FD_ISSET(s_in, &rd)) {
1147
#define ABSIZE 16384
1148
static int watch_for_http_traffic(char *buf_a, int *n_a) {
1149
int is_http, err, n, n2;
1153
* sniff the first couple bytes of the stream and try to see
1154
* if it is http or not. if we read them OK, we must read the
1155
* rest of the available data otherwise we may deadlock.
1156
* what has been read is returned in buf_a and n_a.
1157
* *buf_a is ABSIZE+1 long and zeroed.
1159
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
1160
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
1162
if (! buf_a || ! n_a) {
1166
buf = (char *) calloc((ABSIZE+1), 1);
1169
n = SSL_read(ssl, buf, 2);
1170
err = SSL_get_error(ssl, n);
1172
if (err != SSL_ERROR_NONE || n < 2) {
1174
strncpy(buf_a, buf, n);
1177
if (db) fprintf(stderr, "watch_for_http_traffic ssl err: %d/%d\n", err, n);
1181
/* look for GET, HEAD, POST, CONNECT */
1183
if (!strncmp("GE", buf, 2)) {
1185
} else if (!strncmp("HE", buf, 2)) {
1187
} else if (!strncmp("PO", buf, 2)) {
1189
} else if (!strncmp("CO", buf, 2)) {
1192
if (db) fprintf(stderr, "watch_for_http_traffic read: '%s' %d\n", buf, n);
1195
* better read all we can and fwd it along to avoid blocking
1199
n2 = SSL_read(ssl, buf + n, ABSIZE - n);
1206
if (db) fprintf(stderr, "watch_for_http_traffic readmore: %d\n", n2);
1209
memcpy(buf_a, buf, n);
1212
fprintf(stderr, "watch_for_http_traffic readmore: ");
1213
write(2, buf_a, *n_a);
1214
fprintf(stderr, "\n");
1216
if (db) fprintf(stderr, "watch_for_http_traffic return: %d\n", is_http);
1220
static int csock_timeout_sock = -1;
1222
static void csock_timeout (int sig) {
1223
rfbLog("sig: %d, csock_timeout.\n", sig);
1224
if (csock_timeout_sock >= 0) {
1225
close(csock_timeout_sock);
1226
csock_timeout_sock = -1;
1230
static int wait_conn(int sock) {
1232
struct sockaddr_in addr;
1234
int addrlen = sizeof(addr);
1236
socklen_t addrlen = sizeof(addr);
1239
signal(SIGALRM, csock_timeout);
1240
csock_timeout_sock = sock;
1243
conn = accept(sock, (struct sockaddr *)&addr, &addrlen);
1246
signal(SIGALRM, SIG_DFL);
1250
int proxy_hack(int vncsock, int listen, int s_in, int s_out, char *cookie,
1253
char reply[] = "HTTP/1.1 200 OK\r\n"
1254
"Content-Type: octet-stream\r\n"
1255
"Pragma: no-cache\r\n\r\n";
1256
char reply0[] = "HTTP/1.0 200 OK\r\n"
1257
"Content-Type: octet-stream\r\n"
1258
"Content-Length: 9\r\n"
1259
"Pragma: no-cache\r\n\r\nGO_AHEAD\n";
1261
rfbLog("SSL: accept_openssl: detected https proxied connection"
1264
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
1265
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
1268
SSL_write(ssl, reply0, strlen(reply0));
1275
if (mode == OPENSSL_VNC) {
1276
listen = openssl_sock;
1277
} else if (mode == OPENSSL_HTTPS) {
1278
listen = https_sock;
1284
sock1 = wait_conn(listen);
1286
if (csock_timeout_sock < 0 || sock1 < 0) {
1291
if (db) fprintf(stderr, "got applet input sock1: %d\n", sock1);
1293
if (! ssl_init(sock1, sock1)) {
1294
if (db) fprintf(stderr, "ssl_init FAILED\n");
1298
SSL_write(ssl, reply, strlen(reply));
1304
buf = (char *) calloc((8192+1), 1);
1305
while (ptr < 8192) {
1306
n = SSL_read(ssl, buf + ptr, 8192 - ptr);
1310
if (db) fprintf(stderr, "buf: '%s'\n", buf);
1311
if (strstr(buf, "\r\n\r\n")) {
1318
write(vncsock, cookie, strlen(cookie));
1320
ssl_xfer(vncsock, sock1, sock1, 0);
1325
void accept_openssl(int mode, int presock) {
1326
int sock = -1, listen = -1, cport, csock, vsock;
1328
int status, n, i, db = 0;
1329
struct sockaddr_in addr;
1331
int addrlen = sizeof(addr);
1333
socklen_t addrlen = sizeof(addr);
1335
rfbClientPtr client;
1337
char uniq[] = "_evilrats_";
1338
char cookie[128], rcookie[128], *name = NULL;
1339
static time_t last_https = 0;
1340
static char last_get[128];
1341
static int first = 1;
1343
openssl_last_helper_pid = 0;
1345
/* zero buffers for use below. */
1346
for (i=0; i<128; i++) {
1355
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
1356
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
1359
/* do INETD, VNC, or HTTPS cases (result is client socket or pipe) */
1360
if (mode == OPENSSL_INETD) {
1361
ssl_initialized = 1;
1363
} else if (mode == OPENSSL_VNC) {
1364
sock = accept(openssl_sock, (struct sockaddr *)&addr, &addrlen);
1366
rfbLog("SSL: accept_openssl: accept connection failed\n");
1367
rfbLogPerror("accept");
1373
listen = openssl_sock;
1375
} else if (mode == OPENSSL_REVERSE) {
1378
rfbLog("SSL: accept_openssl: connection failed\n");
1386
} else if (mode == OPENSSL_HTTPS) {
1387
sock = accept(https_sock, (struct sockaddr *)&addr, &addrlen);
1389
rfbLog("SSL: accept_openssl: accept connection failed\n");
1390
rfbLogPerror("accept");
1396
listen = https_sock;
1398
if (db) fprintf(stderr, "SSL: accept_openssl: sock: %d\n", sock);
1400
if (openssl_last_ip) {
1401
free(openssl_last_ip);
1402
openssl_last_ip = NULL;
1404
if (mode == OPENSSL_INETD) {
1405
openssl_last_ip = get_remote_host(fileno(stdin));
1407
openssl_last_ip = get_remote_host(sock);
1410
/* now make a listening socket for child to connect back to us by: */
1412
cport = find_free_port(20000, 0);
1414
rfbLog("SSL: accept_openssl: could not find open port.\n");
1416
if (mode == OPENSSL_INETD || ssl_no_fail) {
1421
if (db) fprintf(stderr, "accept_openssl: cport: %d\n", cport);
1423
csock = rfbListenOnTCPPort(cport, htonl(INADDR_LOOPBACK));
1426
rfbLog("SSL: accept_openssl: could not listen on port %d.\n",
1429
if (mode == OPENSSL_INETD || ssl_no_fail) {
1434
if (db) fprintf(stderr, "accept_openssl: csock: %d\n", csock);
1439
* make a simple cookie to id the child socket, not foolproof
1440
* but hard to guess exactly (just worrying about local lusers
1441
* here, since we use INADDR_LOOPBACK).
1443
sprintf(cookie, "%f/%f", dnow(), x11vnc_start);
1445
if (mode != OPENSSL_INETD) {
1446
name = get_remote_host(sock);
1447
peerport = get_remote_port(sock);
1449
openssl_last_ip = get_remote_host(fileno(stdin));
1450
peerport = get_remote_port(fileno(stdin));
1451
if (openssl_last_ip) {
1452
name = strdup(openssl_last_ip);
1454
name = strdup("unknown");
1458
if (mode == OPENSSL_INETD) {
1459
rfbLog("SSL: (inetd) spawning helper process "
1460
"to handle: %s:%d\n", name, peerport);
1462
rfbLog("SSL: spawning helper process to handle: "
1463
"%s:%d\n", name, peerport);
1476
certret = strdup("/tmp/x11vnc-certret.XXXXXX");
1478
certret_fd = mkstemp(certret);
1480
if (certret_fd < 0) {
1486
/* now fork the child to handle the SSL: */
1490
rfbLog("SSL: accept_openssl: could not fork.\n");
1491
rfbLogPerror("fork");
1494
if (mode == OPENSSL_INETD || ssl_no_fail) {
1499
} else if (pid == 0) {
1500
int s_in, s_out, httpsock = -1;
1502
int i, have_httpd = 0;
1503
int f_in = fileno(stdin);
1504
int f_out = fileno(stdout);
1506
if (db) fprintf(stderr, "helper pid in: %d %d %d %d\n", f_in, f_out, sock, listen);
1508
/* reset all handlers to default (no interrupted() calls) */
1511
/* close all non-essential fd's */
1512
for (i=0; i<256; i++) {
1513
if (mode == OPENSSL_INETD) {
1514
if (i == f_in || i == f_out) {
1528
* sadly, we are a long lived child and so the large
1529
* framebuffer memory areas will soon differ from parent.
1530
* try to free as much as possible.
1534
/* now connect back to parent socket: */
1535
vncsock = rfbConnectToTcpAddr("127.0.0.1", cport);
1537
rfbLog("SSL: ssl_helper[%d]: could not connect"
1538
" back to: %d\n", getpid(), cport);
1541
if (db) fprintf(stderr, "vncsock %d\n", vncsock);
1543
/* try to initialize SSL with the remote client */
1545
if (mode == OPENSSL_INETD) {
1546
s_in = fileno(stdin);
1547
s_out = fileno(stdout);
1549
s_in = s_out = sock;
1552
if (! ssl_init(s_in, s_out)) {
1558
* things get messy below since we are trying to do
1559
* *both* VNC and Java applet httpd through the same
1567
if (screen->httpListenSock >= 0 && screen->httpPort > 0) {
1570
if (mode == OPENSSL_HTTPS && ! have_httpd) {
1571
rfbLog("SSL: accept_openssl[%d]: no httpd socket for "
1572
"-https mode\n", getpid());
1579
int hport = screen->httpPort;
1583
buf = (char *) calloc((ABSIZE+1), 1);
1584
tbuf = (char *) calloc((2*ABSIZE+1), 1);
1586
if (mode == OPENSSL_HTTPS) {
1588
* for this mode we know it is HTTP traffic
1589
* so we skip trying to guess.
1593
goto connect_to_httpd;
1597
* Check if there is stuff to read from remote end
1598
* if so it is likely a GET or HEAD.
1600
if (! is_ssl_readable(s_in, last_https, last_get,
1606
* read first 2 bytes to try to guess. sadly,
1607
* the user is often pondering a "non-verified
1608
* cert" dialog for a long time before the GET
1609
* is ever sent. So often we timeout here.
1612
if (db) fprintf(stderr, "watch_for_http_traffic\n");
1614
is_http = watch_for_http_traffic(buf, &n);
1616
if (is_http < 0 || is_http == 0) {
1618
* error or http not detected, fall back
1619
* to normal VNC socket.
1621
if (db) fprintf(stderr, "is_http err: %d n: %d\n", is_http, n);
1622
write(vncsock, cookie, strlen(cookie));
1624
write(vncsock, buf, n);
1629
if (db) fprintf(stderr, "is_http: %d n: %d\n",
1631
if (db) fprintf(stderr, "buf: '%s'\n", buf);
1633
if (strstr(buf, "/request.https.vnc.connection")) {
1634
char reply[] = "HTTP/1.0 200 OK\r\n"
1635
"Content-Type: octet-stream\r\n"
1636
"Connection: Keep-Alive\r\n"
1637
"Pragma: no-cache\r\n\r\n";
1639
* special case proxy coming thru https
1640
* instead of a direct SSL connection.
1642
rfbLog("Handling VNC request via https GET. [%d]\n", getpid());
1643
rfbLog("-- %s\n", buf);
1645
if (strstr(buf, "/reverse.proxy")) {
1648
SSL_write(ssl, reply, strlen(reply));
1650
buf2 = (char *) calloc((8192+1), 1);
1653
while (ptr < 8192) {
1654
n = SSL_read(ssl, buf2 + ptr, 1);
1658
if (db) fprintf(stderr, "buf2: '%s'\n", buf2);
1660
if (strstr(buf2, "\r\n\r\n")) {
1668
} else if (strstr(buf, "/check.https.proxy.connection")) {
1669
char reply[] = "HTTP/1.0 200 OK\r\n"
1670
"Connection: close\r\n"
1671
"Content-Type: octet-stream\r\n"
1672
"Pragma: no-cache\r\n\r\n";
1674
rfbLog("Handling Check HTTPS request via https GET. [%d]\n", getpid());
1675
rfbLog("-- %s\n", buf);
1677
SSL_write(ssl, reply, strlen(reply));
1681
strcat(tbuf, cookie);
1682
write(vncsock, tbuf, strlen(tbuf));
1690
* Here we go... no turning back. we have to
1691
* send failure to parent and close socket to have
1692
* http processed at all in a timely fashion...
1695
/* send the failure tag: */
1698
if (https_port_redir < 0) {
1699
char *q = strstr(buf, "Host:");
1702
if (q && strstr(q, "\n")) {
1703
q += strlen("Host:") + 1;
1704
while (*q != '\n') {
1706
if (*q == ':' && sscanf(q, ":%d", &p) == 1) {
1707
if (p > 0 && p < 65536) {
1715
sprintf(num, "HP=%d,", fport);
1719
if (strstr(buf, "HTTP/") != NULL) {
1722
* Also send back the GET line for heuristics.
1723
* (last_https, get file).
1726
q = strstr(str, "HTTP/");
1735
* Also send the cookie to pad out the number of
1736
* bytes to more than the parent wants to read.
1737
* Since this is the failure case, it does not
1738
* matter that we send more than strlen(cookie).
1740
strcat(tbuf, cookie);
1741
write(vncsock, tbuf, strlen(tbuf));
1744
if (db) fprintf(stderr, "close vncsock: %d\n", vncsock);
1747
/* now, finally, connect to the libvncserver httpd: */
1748
if (screen->listenInterface == htonl(INADDR_ANY) ||
1749
screen->listenInterface == htonl(INADDR_NONE)) {
1750
iface = "127.0.0.1";
1753
in.s_addr = screen->listenInterface;
1754
iface = inet_ntoa(in);
1756
if (iface == NULL || !strcmp(iface, "")) {
1757
iface = "127.0.0.1";
1759
if (db) fprintf(stderr, "iface: %s\n", iface);
1762
httpsock = rfbConnectToTcpAddr(iface, hport);
1765
/* UGH, after all of that! */
1766
rfbLog("Could not connect to httpd socket!\n");
1769
if (db) fprintf(stderr, "ssl_helper[%d]: httpsock: %d %d\n",
1770
getpid(), httpsock, n);
1773
* send what we read to httpd, and then connect
1774
* the rest of the SSL session to it:
1777
write(httpsock, buf, n);
1779
ssl_xfer(httpsock, s_in, s_out, is_http);
1784
* ok, back from the above https mess, simply send the
1785
* cookie back to the parent (who will attach us to
1786
* libvncserver), and connect the rest of the SSL session
1790
write(vncsock, cookie, strlen(cookie));
1793
ssl_xfer(vncsock, s_in, s_out, 0);
1799
if (mode != OPENSSL_INETD) {
1802
if (db) fprintf(stderr, "helper process is: %d\n", pid);
1804
/* accept connection from our child. */
1805
signal(SIGALRM, csock_timeout);
1806
csock_timeout_sock = csock;
1809
vsock = accept(csock, (struct sockaddr *)&addr, &addrlen);
1812
signal(SIGALRM, SIG_DFL);
1817
rfbLog("SSL: accept_openssl: connection from ssl_helper FAILED.\n");
1818
rfbLogPerror("accept");
1821
waitpid(pid, &status, WNOHANG);
1822
if (mode == OPENSSL_INETD || ssl_no_fail) {
1825
if (certret_fd >= 0) {
1834
if (db) fprintf(stderr, "accept_openssl: vsock: %d\n", vsock);
1836
n = read(vsock, rcookie, strlen(cookie));
1837
if (n < 0 && errno != 0) {
1838
rfbLogPerror("read");
1844
if (certret_fd >= 0 && stat(certret, &sbuf) == 0 && sbuf.st_size > 0) {
1845
certret_str = (char *) malloc(sbuf.st_size+1);
1846
read(certret_fd, certret_str, sbuf.st_size);
1850
if (certret_fd >= 0) {
1855
if (certret_str && strstr(certret_str, "NOCERT") == certret_str) {
1859
if (0 && certret_str) {
1860
fprintf(stderr, "certret_str[%d]:\n%s\n", (int) sbuf.st_size, certret_str);
1864
if (n != (int) strlen(cookie) || strncmp(cookie, rcookie, n)) {
1865
rfbLog("SSL: accept_openssl: cookie from ssl_helper FAILED. %d\n", n);
1866
if (db) fprintf(stderr, "'%s'\n'%s'\n", cookie, rcookie);
1869
if (strstr(rcookie, uniq) == rcookie) {
1871
rfbLog("SSL: BUT WAIT! HTTPS for helper process succeeded. Good.\n");
1872
if (mode != OPENSSL_HTTPS) {
1873
last_https = time(NULL);
1874
for (i=0; i<128; i++) {
1877
strncpy(last_get, rcookie, 100);
1878
if (db) fprintf(stderr, "last_get: '%s'\n", last_get);
1880
if (rcookie && strstr(rcookie, "VncViewer.class")) {
1882
rfbLog("***********************************************************\n");
1883
rfbLog("SSL: WARNING CLIENT ASKED FOR NONEXISTENT 'VncViewer.class'\n");
1884
rfbLog("SSL: USER NEEDS TO **RESTART** HIS WEB BROWSER.\n");
1885
rfbLog("***********************************************************\n");
1888
ssl_helper_pid(pid, -2);
1890
if (https_port_redir) {
1892
int origport = screen->port;
1893
int useport = screen->port;
1894
/* to expand $PORT correctly in index.vnc */
1895
if (https_port_redir < 0) {
1896
char *q = strstr(rcookie, "HP=");
1899
if (sscanf(q, "HP=%d,", &p) == 1) {
1904
useport = https_port_redir;
1906
screen->port = useport;
1907
if (origport != useport) {
1908
rfbLog("SSL: -httpsredir guess port: %d\n", screen->port);
1912
while (dnow() < start + 10.0) {
1915
waitpid(pid, &status, WNOHANG);
1916
if (kill(pid, 0) != 0) {
1922
screen->port = origport;
1923
rfbLog("SSL: guessing child https finished.\n");
1924
if (mode == OPENSSL_INETD) {
1927
} else if (mode == OPENSSL_INETD) {
1929
/* to expand $PORT correctly in index.vnc */
1930
if (screen->port == 0) {
1931
int fd = fileno(stdin);
1932
if (getenv("X11VNC_INETD_PORT")) {
1933
screen->port = atoi(getenv(
1934
"X11VNC_INETD_PORT"));
1936
int tport = get_local_port(fd);
1938
screen->port = tport;
1942
rfbLog("SSL: screen->port %d\n", screen->port);
1944
/* kludge for https fetch via inetd */
1946
while (dnow() < start + 10.0) {
1949
waitpid(pid, &status, WNOHANG);
1950
if (kill(pid, 0) != 0) {
1956
rfbLog("SSL: OPENSSL_INETD guessing "
1957
"child https finished.\n");
1963
waitpid(pid, &status, WNOHANG);
1964
if (mode == OPENSSL_INETD || ssl_no_fail) {
1969
if (db) fprintf(stderr, "accept_openssl: cookie good: %s\n", cookie);
1971
rfbLog("SSL: handshake with helper process succeeded.\n");
1973
openssl_last_helper_pid = pid;
1974
ssl_helper_pid(pid, vsock);
1977
vnc_redirect_sock = vsock;
1978
openssl_last_helper_pid = 0;
1982
client = rfbNewClient(screen, vsock);
1983
openssl_last_helper_pid = 0;
1986
if (db) fprintf(stderr, "accept_openssl: client %p\n", (void *) client);
1987
if (db) fprintf(stderr, "accept_openssl: new_client %p\n", (void *) screen->newClientHook);
1988
if (db) fprintf(stderr, "accept_openssl: new_client %p\n", (void *) new_client);
1989
if (mode == OPENSSL_INETD) {
1990
inetd_client = client;
1991
client->clientGoneHook = client_gone;
1993
if (openssl_last_ip &&
1994
strpbrk(openssl_last_ip, "0123456789") == openssl_last_ip) {
1995
client->host = strdup(openssl_last_ip);
1998
rfbLog("SSL: accept_openssl: rfbNewClient failed.\n");
2002
waitpid(pid, &status, WNOHANG);
2003
if (mode == OPENSSL_INETD || ssl_no_fail) {
2010
static void ssl_timeout (int sig) {
2011
rfbLog("sig: %d, ssl_init timed out.\n", sig);
2015
static int ssl_init(int s_in, int s_out) {
2016
unsigned char *sid = (unsigned char *) "x11vnc SID";
2019
int db = 0, rc, err;
2021
double start = dnow();
2024
if (getenv("SSL_DEBUG")) {
2025
db = atoi(getenv("SSL_DEBUG"));
2027
if (db) fprintf(stderr, "ssl_init: %d/%d\n", s_in, s_out);
2031
fprintf(stderr, "SSL_new failed\n");
2034
if (db > 1) fprintf(stderr, "ssl_init: 1\n");
2036
SSL_set_session_id_context(ssl, sid, strlen((char *)sid));
2038
if (s_in == s_out) {
2039
if (! SSL_set_fd(ssl, ssock)) {
2040
fprintf(stderr, "SSL_set_fd failed\n");
2044
if (! SSL_set_rfd(ssl, s_in)) {
2045
fprintf(stderr, "SSL_set_rfd failed\n");
2048
if (! SSL_set_wfd(ssl, s_out)) {
2049
fprintf(stderr, "SSL_set_wfd failed\n");
2053
if (db > 1) fprintf(stderr, "ssl_init: 2\n");
2055
if (ssl_client_mode) {
2056
SSL_set_connect_state(ssl);
2058
SSL_set_accept_state(ssl);
2061
if (db > 1) fprintf(stderr, "ssl_init: 3\n");
2063
name = get_remote_host(ssock);
2064
peerport = get_remote_port(ssock);
2066
if (db > 1) fprintf(stderr, "ssl_init: 4\n");
2069
if (db) fprintf(stderr, "calling SSL_accept...\n");
2071
signal(SIGALRM, ssl_timeout);
2074
if (ssl_client_mode) {
2075
rc = SSL_connect(ssl);
2077
rc = SSL_accept(ssl);
2079
err = SSL_get_error(ssl, rc);
2082
signal(SIGALRM, SIG_DFL);
2084
if (db) fprintf(stderr, "SSL_accept %d/%d\n", rc, err);
2085
if (err == SSL_ERROR_NONE) {
2087
} else if (err == SSL_ERROR_WANT_READ) {
2089
if (db) fprintf(stderr, "got SSL_ERROR_WANT_READ\n");
2090
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
2091
getpid(), name, peerport);
2094
} else if (err == SSL_ERROR_WANT_WRITE) {
2096
if (db) fprintf(stderr, "got SSL_ERROR_WANT_WRITE\n");
2097
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
2098
getpid(), name, peerport);
2101
} else if (err == SSL_ERROR_SYSCALL) {
2103
if (db) fprintf(stderr, "got SSL_ERROR_SYSCALL\n");
2104
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
2105
getpid(), name, peerport);
2108
} else if (err == SSL_ERROR_ZERO_RETURN) {
2110
if (db) fprintf(stderr, "got SSL_ERROR_ZERO_RETURN\n");
2111
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
2112
getpid(), name, peerport);
2115
} else if (rc < 0) {
2117
rfbLog("SSL: ssl_helper[%d]: SSL_accept() *FATAL: %d\n", getpid(), rc);
2120
} else if (dnow() > start + 3.0) {
2122
rfbLog("SSL: ssl_helper[%d]: timeout looping SSL_accept() "
2123
"fatal.\n", getpid());
2127
BIO *bio = SSL_get_rbio(ssl);
2129
rfbLog("SSL: ssl_helper[%d]: ssl BIO is null. "
2130
"fatal.\n", getpid());
2134
rfbLog("SSL: ssl_helper[%d]: ssl BIO is EOF. "
2135
"fatal.\n", getpid());
2142
rfbLog("SSL: ssl_helper[%d]: SSL_accept() succeeded for: %s:%d\n", getpid(), name, peerport);
2144
if (SSL_get_verify_result(ssl) == X509_V_OK) {
2147
if (certret != NULL) {
2148
cr = fopen(certret, "w");
2151
x = SSL_get_peer_certificate(ssl);
2153
rfbLog("SSL: ssl_helper[%d]: accepted client %s x509 peer cert is null\n", getpid(), name);
2155
fprintf(cr, "NOCERT\n");
2159
rfbLog("SSL: ssl_helper[%d]: accepted client %s x509 cert is:\n", getpid(), name);
2160
X509_print_ex_fp(stderr, x, 0, XN_FLAG_MULTILINE);
2162
X509_print_ex_fp(cr, x, 0, XN_FLAG_MULTILINE);
2172
static void ssl_xfer(int csock, int s_in, int s_out, int is_https) {
2173
int dbxfer = 0, db = 0, check_pending, fdmax, nfd, n, i, err;
2174
char cbuf[ABSIZE], sbuf[ABSIZE];
2175
int cptr, sptr, c_rd, c_wr, s_rd, s_wr;
2178
int ssock, cnt = 0, ndata = 0;
2181
* we want to switch to a longer timeout for long term VNC
2182
* connections (in case the network is not working for periods of
2183
* time), but we also want the timeout shorter at the beginning
2184
* in case the client went away.
2187
int tv_https_early = 60;
2188
int tv_https_later = 20;
2189
int tv_vnc_early = 25;
2190
int tv_vnc_later = 43200; /* was 300, stunnel: 43200 */
2191
int tv_cutover = 70;
2192
int tv_closing = 60;
2196
raw_xfer(csock, s_in, s_out);
2199
if (getenv("SSL_DEBUG")) {
2200
db = atoi(getenv("SSL_DEBUG"));
2203
if (db) fprintf(stderr, "ssl_xfer begin\n");
2207
tv_use = tv_https_early;
2209
tv_use = tv_vnc_early;
2214
* csock: clear text socket with libvncserver. "C"
2215
* ssock: ssl data socket with remote vnc viewer. "S"
2217
* to cover inetd mode, we have s_in and s_out, but in non-inetd
2218
* mode they both ssock.
2220
* cbuf[] is data from csock that we have read but not passed on to ssl
2221
* sbuf[] is data from ssl that we have read but not passed on to csock
2223
for (i=0; i<ABSIZE; i++) {
2234
if (csock > ssock) {
2240
c_rd = 1; /* clear text (libvncserver) socket open for reading */
2241
c_wr = 1; /* clear text (libvncserver) socket open for writing */
2242
s_rd = 1; /* ssl data (remote client) socket open for reading */
2243
s_wr = 1; /* ssl data (remote client) socket open for writing */
2245
cptr = 0; /* offsets into ABSIZE buffers */
2249
int c_to_s, s_to_c, closing;
2251
if ( s_wr && (c_rd || cptr > 0) ) {
2254
* C is readable or some cbuf data remaining
2261
if ( c_wr && (s_rd || sptr > 0) ) {
2264
* S is readable or some sbuf data remaining
2271
if (! c_to_s && ! s_to_c) {
2273
* nothing can be sent either direction.
2274
* break out of the loop to finish all work.
2280
/* set up the fd sets for the two sockets for read & write: */
2284
if (c_rd && cptr < ABSIZE) {
2285
/* we could read more from C since cbuf is not full */
2290
* we could read more from S since sbuf not full,
2291
* OR ssl is waiting for more BIO to be able to
2292
* read and we have some C data still buffered.
2294
if (sptr < ABSIZE || (cptr > 0 && SSL_want_read(ssl))) {
2301
if (c_wr && sptr > 0) {
2302
/* we could write more to C since sbuf is not empty */
2307
* we could write more to S since cbuf not empty,
2308
* OR ssl is waiting for more BIO to be able
2309
* write and we haven't filled up sbuf yet.
2311
if (cptr > 0 || (sptr < ABSIZE && SSL_want_write(ssl))) {
2316
if (tv_cutover && time(NULL) > start + tv_cutover) {
2317
rfbLog("SSL: ssl_xfer[%d]: tv_cutover: %d\n", getpid(),
2321
tv_use = tv_https_later;
2323
tv_use = tv_vnc_later;
2326
if (ssl_timeout_secs > 0) {
2327
tv_use = ssl_timeout_secs;
2330
if ( (s_rd && c_rd) || cptr || sptr) {
2334
tv_use = tv_closing;
2339
/* do the select, repeat if interrupted */
2341
if (ssl_timeout_secs == 0) {
2342
nfd = select(fdmax+1, &rd, &wr, NULL, NULL);
2344
nfd = select(fdmax+1, &rd, &wr, NULL, &tv);
2346
} while (nfd < 0 && errno == EINTR);
2348
if (db > 1) fprintf(stderr, "nfd: %d\n", nfd);
2351
rfbLog("SSL: ssl_xfer[%d]: select error: %d\n", getpid(), nfd);
2353
/* connection finished */
2358
if (!closing && tv_cutover && ndata > 25000) {
2360
/* probably ok, early windows iconify */
2362
rfbLog("SSL: ssl_xfer[%d]: early time"
2363
"out: %d\n", getpid(), ndata);
2367
rfbLog("SSL: ssl_xfer[%d]: connection timedout. %d\n",
2369
/* connection finished */
2373
/* used to see if SSL_pending() should be checked: */
2377
if (c_wr && FD_ISSET(csock, &wr)) {
2379
/* try to write some of our sbuf to C: */
2380
n = write(csock, sbuf, sptr);
2383
if (errno != EINTR) {
2384
/* connection finished */
2388
} else if (n == 0) {
2389
/* connection finished XXX double check */
2392
/* shift over the data in sbuf by n */
2393
memmove(sbuf, sbuf + n, sptr - n);
2394
if (sptr == ABSIZE) {
2399
if (! s_rd && sptr == 0) {
2400
/* finished sending last of sbuf */
2401
shutdown(csock, SHUT_WR);
2409
if ((cptr > 0 && FD_ISSET(s_out, &wr)) ||
2410
(SSL_want_read(ssl) && FD_ISSET(s_in, &rd))) {
2412
/* try to write some of our cbuf to S: */
2414
n = SSL_write(ssl, cbuf, cptr);
2415
err = SSL_get_error(ssl, n);
2417
if (err == SSL_ERROR_NONE) {
2418
/* shift over the data in cbuf by n */
2419
memmove(cbuf, cbuf + n, cptr - n);
2422
if (! c_rd && cptr == 0 && s_wr) {
2423
/* finished sending last cbuf */
2429
} else if (err == SSL_ERROR_WANT_WRITE
2430
|| err == SSL_ERROR_WANT_READ
2431
|| err == SSL_ERROR_WANT_X509_LOOKUP) {
2435
} else if (err == SSL_ERROR_SYSCALL) {
2436
if (n < 0 && errno != EINTR) {
2437
/* connection finished */
2441
} else if (err == SSL_ERROR_ZERO_RETURN) {
2445
} else if (err == SSL_ERROR_SSL) {
2446
/* connection finished */
2452
if (c_rd && FD_ISSET(csock, &rd)) {
2455
/* try to read some data from C into our cbuf */
2457
n = read(csock, cbuf + cptr, ABSIZE - cptr);
2460
if (errno != EINTR) {
2461
/* connection finished */
2465
} else if (n == 0) {
2468
if (cptr == 0 && s_wr) {
2469
/* and no more in cbuf to send */
2482
if ((sptr < ABSIZE && FD_ISSET(s_in, &rd)) ||
2483
(SSL_want_write(ssl) && FD_ISSET(s_out, &wr)) ||
2484
(check_pending && SSL_pending(ssl))) {
2486
/* try to read some data from S into our sbuf */
2488
n = SSL_read(ssl, sbuf + sptr, ABSIZE - sptr);
2489
err = SSL_get_error(ssl, n);
2491
if (err == SSL_ERROR_NONE) {
2497
} else if (err == SSL_ERROR_WANT_WRITE
2498
|| err == SSL_ERROR_WANT_READ
2499
|| err == SSL_ERROR_WANT_X509_LOOKUP) {
2503
} else if (err == SSL_ERROR_SYSCALL) {
2505
if(errno != EINTR) {
2506
/* connection finished */
2515
} else if (err == SSL_ERROR_ZERO_RETURN) {
2518
if (cptr == 0 && s_wr) {
2519
/* and no more in cbuf to send */
2523
if (sptr == 0 && c_wr) {
2524
/* and no more in sbuf to send */
2525
shutdown(csock, SHUT_WR);
2528
} else if (err == SSL_ERROR_SSL) {
2529
/* connection finished */
2537
void check_openssl(void) {
2541
static time_t last_waitall = 0;
2542
static double last_check = 0.0;
2545
if (! use_openssl || openssl_sock < 0) {
2550
if (now < last_check + 0.5) {
2555
if (time(NULL) > last_waitall + 150) {
2556
last_waitall = time(NULL);
2557
ssl_helper_pid(0, -2); /* waitall */
2561
FD_SET(openssl_sock, &fds);
2566
nfds = select(openssl_sock+1, &fds, NULL, NULL, &tv);
2572
rfbLog("SSL: accept_openssl(OPENSSL_VNC)\n");
2573
accept_openssl(OPENSSL_VNC, -1);
2576
void check_https(void) {
2580
static double last_check = 0.0;
2583
if (! use_openssl || https_sock < 0) {
2588
if (now < last_check + 0.5) {
2594
FD_SET(https_sock, &fds);
2599
nfds = select(https_sock+1, &fds, NULL, NULL, &tv);
2604
rfbLog("SSL: accept_openssl(OPENSSL_HTTPS)\n");
2605
accept_openssl(OPENSSL_HTTPS, -1);
2609
static void init_prng(void) {
2613
RAND_file_name(file, MSZ);
2615
rfbLog("RAND_file_name: %s\n", file);
2617
bytes = RAND_load_file(file, -1);
2618
if (db) fprintf(stderr, "bytes read: %d\n", bytes);
2620
bytes += RAND_load_file("/dev/urandom", 64);
2621
if (db) fprintf(stderr, "bytes read: %d\n", bytes);
2625
rfbLog("initialized PRNG with %d random bytes.\n",
2631
bytes += RAND_load_file("/dev/random", 8);
2632
if (db) fprintf(stderr, "bytes read: %d\n", bytes);
2634
rfbLog("initialized PRNG with %d random bytes.\n", bytes);
2637
#endif /* FORK_OK */
2638
#endif /* LIBVNCSERVER_HAVE_LIBSSL */
2640
void raw_xfer(int csock, int s_in, int s_out) {
2642
int sz = 8192, n, m, status, db = 1;
2645
pid_t par = getpid();
2650
/* change buf size some direction. */
2653
/* this is for testing, no SSL just socket redir */
2658
if (db) fprintf(stderr, "raw_xfer start: %d -> %d/%d\n", csock, s_in, s_out);
2661
n = read(csock, buf, sz);
2662
if (n == 0 || (n < 0 && errno != EINTR) ) {
2667
if (db > 1) write(2, buf, n);
2669
m = write(s_out, src, len);
2675
if (m < 0 && (errno == EINTR || errno == EAGAIN)) {
2678
if (db) fprintf(stderr, "raw_xfer bad write: %d -> %d | %d/%d errno=%d\n", csock, s_out, m, n, errno);
2685
waitpid(pid, &status, WNOHANG);
2686
if (db) fprintf(stderr, "raw_xfer done: %d -> %d\n", csock, s_out);
2689
if (db) fprintf(stderr, "raw_xfer start: %d <- %d\n", csock, s_in);
2692
n = read(s_in, buf, sz);
2693
if (n == 0 || (n < 0 && errno != EINTR) ) {
2698
if (db > 1) write(2, buf, n);
2700
m = write(csock, src, len);
2706
if (m < 0 && (errno == EINTR || errno == EAGAIN)) {
2709
if (db) fprintf(stderr, "raw_xfer bad write: %d <- %d | %d/%d errno=%d\n", csock, s_in, m, n, errno);
2716
waitpid(par, &status, WNOHANG);
2717
if (db) fprintf(stderr, "raw_xfer done: %d <- %d\n", csock, s_in);
2722
#endif /* FORK_OK */