]> git.ipfire.org Git - thirdparty/openssl.git/blob - demos/easy_tls/easy-tls.c
mark all block comments that need format preserving so that
[thirdparty/openssl.git] / demos / easy_tls / easy-tls.c
1 /* -*- Mode: C; c-file-style: "bsd" -*- */
2 /*
3 * easy-tls.c -- generic TLS proxy.
4 * $Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $
5 */
6 /*-
7 (c) Copyright 1999 Bodo Moeller. All rights reserved.
8
9 This is free software; you can redistributed and/or modify it
10 unter the terms of either
11 - the GNU General Public License as published by the
12 Free Software Foundation, version 1, or (at your option)
13 any later version,
14 or
15 - the following license:
16 */
17 /*-
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that each of the following
20 * conditions is met:
21 *
22 * 1. Redistributions qualify as "freeware" or "Open Source Software" under
23 * one of the following terms:
24 *
25 * (a) Redistributions are made at no charge beyond the reasonable cost of
26 * materials and delivery.
27 *
28 * (b) Redistributions are accompanied by a copy of the Source Code
29 * or by an irrevocable offer to provide a copy of the Source Code
30 * for up to three years at the cost of materials and delivery.
31 * Such redistributions must allow further use, modification, and
32 * redistribution of the Source Code under substantially the same
33 * terms as this license.
34 *
35 * 2. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 *
38 * 3. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in
40 * the documentation and/or other materials provided with the
41 * distribution.
42 *
43 * 4. All advertising materials mentioning features or use of this
44 * software must display the following acknowledgment:
45 * "This product includes software developed by Bodo Moeller."
46 * (If available, substitute umlauted o for oe.)
47 *
48 * 5. Redistributions of any form whatsoever must retain the following
49 * acknowledgment:
50 * "This product includes software developed by Bodo Moeller."
51 *
52 * THIS SOFTWARE IS PROVIDED BY BODO MOELLER ``AS IS'' AND ANY
53 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
55 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BODO MOELLER OR
56 * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
58 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
59 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
61 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
62 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
63 * OF THE POSSIBILITY OF SUCH DAMAGE.
64 */
65 /*
66 * Attribution for OpenSSL library:
67 *
68 * This product includes cryptographic software written by Eric Young
69 * (eay@cryptsoft.com). This product includes software written by Tim
70 * Hudson (tjh@cryptsoft.com).
71 * This product includes software developed by the OpenSSL Project
72 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)
73 */
74
75 static char const rcsid[] =
76 "$Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $";
77
78 #include <assert.h>
79 #include <errno.h>
80 #include <fcntl.h>
81 #include <limits.h>
82 #include <stdarg.h>
83 #include <stdio.h>
84 #include <string.h>
85 #include <sys/select.h>
86 #include <sys/socket.h>
87 #include <sys/stat.h>
88 #include <sys/time.h>
89 #include <sys/types.h>
90 #include <sys/utsname.h>
91 #include <unistd.h>
92
93 #include <openssl/crypto.h>
94 #include <openssl/dh.h>
95 #include <openssl/dsa.h>
96 #include <openssl/err.h>
97 #include <openssl/evp.h>
98 #include <openssl/opensslv.h>
99 #include <openssl/pem.h>
100 #include <openssl/rand.h>
101 #ifndef NO_RSA
102 #include <openssl/rsa.h>
103 #endif
104 #include <openssl/ssl.h>
105 #include <openssl/x509.h>
106 #include <openssl/x509_vfy.h>
107
108 #if OPENSSL_VERSION_NUMBER < 0x00904000L /* 0.9.4-dev */
109 # error "This program needs OpenSSL 0.9.4 or later."
110 #endif
111
112 #include "easy-tls.h" /* include after <openssl/ssl.h> if both are needed */
113
114 #if TLS_INFO_SIZE > PIPE_BUF
115 # if PIPE_BUF < 512
116 # error "PIPE_BUF < 512" /* non-POSIX */
117 # endif
118 # error "TLS_INFO_SIZE > PIPE_BUF"
119 #endif
120
121 /*****************************************************************************/
122
123 #ifdef TLS_APP
124 # include TLS_APP
125 #endif
126
127 /* Applications can define:
128 * TLS_APP_PROCESS_INIT -- void ...(int fd, int client_p, void *apparg)
129 * TLS_CUMULATE_ERRORS
130 * TLS_ERROR_BUFSIZ
131 * TLS_APP_ERRFLUSH -- void ...(int child_p, char *, size_t, void *apparg)
132 */
133
134 #ifndef TLS_APP_PROCESS_INIT
135 # define TLS_APP_PROCESS_INIT(fd, client_p, apparg) ((void) 0)
136 #endif
137
138 #ifndef TLS_ERROR_BUFSIZ
139 # define TLS_ERROR_BUFSIZ (10*160)
140 #endif
141 #if TLS_ERROR_BUFSIZ < 2 /* {'\n',0} */
142 # error "TLS_ERROR_BUFSIZE is too small."
143 #endif
144
145 #ifndef TLS_APP_ERRFLUSH
146 # define TLS_APP_ERRFLUSH tls_app_errflush
147 static void
148 tls_app_errflush(int child_p, char *errbuf, size_t num, void *apparg)
149 {
150 fputs(errbuf, stderr);
151 }
152 #endif
153
154 /*****************************************************************************/
155
156 #ifdef DEBUG_TLS
157 # define DEBUG_MSG(x) fprintf(stderr," %s\n",x)
158 # define DEBUG_MSG2(x,y) fprintf(stderr, " %s: %d\n",x,y)
159 static int tls_loop_count = 0;
160 static int tls_select_count = 0;
161 #else
162 # define DEBUG_MSG(x) (void)0
163 # define DEBUG_MSG2(x,y) (void)0
164 #endif
165
166 static void tls_rand_seed_uniquely(void);
167 static void tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p);
168 static int tls_socket_nonblocking(int fd);
169
170 static int tls_child_p = 0;
171 static void *tls_child_apparg;
172
173
174 struct tls_start_proxy_args
175 tls_start_proxy_defaultargs(void)
176 {
177 struct tls_start_proxy_args ret;
178
179 ret.fd = -1;
180 ret.client_p = -1;
181 ret.ctx = NULL;
182 ret.pid = NULL;
183 ret.infofd = NULL;
184
185 return ret;
186 }
187
188 /*-
189 * Slice in TLS proxy process at fd.
190 * Return value:
191 * 0 ok (*pid is set to child's PID if pid != NULL),
192 * < 0 look at errno
193 * > 0 other error
194 * (return value encodes place of error)
195 *
196 */
197 int
198 tls_start_proxy(struct tls_start_proxy_args a, void *apparg)
199 {
200 int fds[2] = {-1, -1};
201 int infofds[2] = {-1, -1};
202 int r, getfd, getfl;
203 int ret;
204
205 DEBUG_MSG2("tls_start_proxy fd", a.fd);
206 DEBUG_MSG2("tls_start_proxy client_p", a.client_p);
207
208 if (a.fd == -1 || a.client_p == -1 || a.ctx == NULL)
209 return 1;
210
211 if (a.pid != NULL) {
212 *a.pid = 0;
213 }
214 if (a.infofd != NULL) {
215 *a.infofd = -1;
216 }
217
218 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
219 if (r == -1)
220 return -1;
221 if (a.fd >= FD_SETSIZE || fds[0] >= FD_SETSIZE) {
222 ret = 2;
223 goto err;
224 }
225 if (a.infofd != NULL) {
226 r = pipe(infofds);
227 if (r == -1) {
228 ret = -3;
229 goto err;
230 }
231 }
232
233 r = fork();
234 if (r == -1) {
235 ret = -4;
236 goto err;
237 }
238 if (r == 0) {
239 DEBUG_MSG("fork");
240 tls_child_p = 1;
241 tls_child_apparg = apparg;
242 close(fds[1]);
243 if (infofds[0] != -1)
244 close(infofds[0]);
245 TLS_APP_PROCESS_INIT(a.fd, a.client_p, apparg);
246 DEBUG_MSG("TLS_APP_PROCESS_INIT");
247 tls_proxy(fds[0], a.fd, infofds[1], a.ctx, a.client_p);
248 exit(0);
249 }
250 if (a.pid != NULL)
251 *a.pid = r;
252 if (infofds[1] != -1) {
253 close(infofds[1]);
254 infofds[1] = -1;
255 }
256 /* install fds[1] in place of fd: */
257 close(fds[0]);
258 fds[0] = -1;
259 getfd = fcntl(a.fd, F_GETFD);
260 getfl = fcntl(a.fd, F_GETFL);
261 r = dup2(fds[1], a.fd);
262 close(fds[1]);
263 fds[1] = -1;
264 if (r == -1) {
265 ret = -5;
266 goto err;
267 }
268 if (getfd != 1)
269 fcntl(a.fd, F_SETFD, getfd);
270 if (getfl & O_NONBLOCK)
271 (void)tls_socket_nonblocking(a.fd);
272 if (a.infofd != NULL)
273 *a.infofd = infofds[0];
274 return 0;
275
276 err:
277 if (fds[0] != -1)
278 close(fds[0]);
279 if (fds[1] != -1)
280 close(fds[1]);
281 if (infofds[0] != -1)
282 close(infofds[0]);
283 if (infofds[1] != -1)
284 close(infofds[1]);
285 return ret;
286 }
287
288 /*****************************************************************************/
289
290 static char errbuf[TLS_ERROR_BUFSIZ];
291 static size_t errbuf_i = 0;
292
293 static void
294 tls_errflush(void *apparg)
295 {
296 if (errbuf_i == 0)
297 return;
298
299 assert(errbuf_i < sizeof errbuf);
300 assert(errbuf[errbuf_i] == 0);
301 if (errbuf_i == sizeof errbuf - 1) {
302 /* make sure we have a newline, even if string has been truncated */
303 errbuf[errbuf_i - 1] = '\n';
304 }
305
306 /* TLS_APP_ERRFLUSH may modify the string as needed,
307 * e.g. substitute other characters for \n for convenience */
308 TLS_APP_ERRFLUSH(tls_child_p, errbuf, errbuf_i, apparg);
309
310 errbuf_i = 0;
311 }
312
313 static void
314 tls_errprintf(int flush, void *apparg, const char *fmt, ...)
315 {
316 va_list args;
317 int r;
318
319 if (errbuf_i < sizeof errbuf - 1) {
320 size_t n;
321
322 va_start(args, fmt);
323 n = (sizeof errbuf) - errbuf_i;
324 r = vsnprintf(errbuf + errbuf_i, n, fmt, args);
325 if (r >= n)
326 r = n - 1;
327 if (r >= 0) {
328 errbuf_i += r;
329 } else {
330 errbuf_i = sizeof errbuf - 1;
331 errbuf[errbuf_i] = '\0';
332 }
333 assert(errbuf_i < sizeof errbuf);
334 assert(errbuf[errbuf_i] == 0);
335 }
336 #ifndef TLS_CUMULATE_ERRORS
337 tls_errflush(apparg);
338 #else
339 if (flush)
340 tls_errflush(apparg);
341 #endif
342 }
343
344 /* app_prefix.. are for additional information provided by caller.
345 * If OpenSSL error queue is empty, print default_text ("???" if NULL).
346 */
347 static char *
348 tls_openssl_errors(const char *app_prefix_1, const char *app_prefix_2, const char *default_text, void *apparg)
349 {
350 static char reasons[255];
351 size_t reasons_i;
352 unsigned long err;
353 const char *file;
354 int line;
355 const char *data;
356 int flags;
357 char *errstring;
358 int printed_something = 0;
359
360 reasons_i = 0;
361
362 assert(app_prefix_1 != NULL);
363 assert(app_prefix_2 != NULL);
364
365 if (default_text == NULL)
366 default_text = "?""?""?";
367
368 while ((err = ERR_get_error_line_data(&file,&line,&data,&flags)) != 0) {
369 if (reasons_i < sizeof reasons) {
370 size_t n;
371 int r;
372
373 n = (sizeof reasons) - reasons_i;
374 r = snprintf(reasons + reasons_i, n, "%s%s", (reasons_i > 0 ? ", " : ""), ERR_reason_error_string(err));
375 if (r >= n)
376 r = n - 1;
377 if (r >= 0) {
378 reasons_i += r;
379 } else {
380 reasons_i = sizeof reasons;
381 }
382 assert(reasons_i <= sizeof reasons);
383 }
384
385 errstring = ERR_error_string(err, NULL);
386 assert(errstring != NULL);
387 tls_errprintf(0, apparg, "OpenSSL error%s%s: %s:%s:%d:%s\n", app_prefix_1, app_prefix_2, errstring, file, line, (flags & ERR_TXT_STRING) ? data : "");
388 printed_something = 1;
389 }
390
391 if (!printed_something) {
392 assert(reasons_i == 0);
393 snprintf(reasons, sizeof reasons, "%s", default_text);
394 tls_errprintf(0, apparg, "OpenSSL error%s%s: %s\n", app_prefix_1, app_prefix_2, default_text);
395 }
396
397 #ifdef TLS_CUMULATE_ERRORS
398 tls_errflush(apparg);
399 #endif
400 assert(errbuf_i == 0);
401
402 return reasons;
403 }
404
405 /*****************************************************************************/
406
407 static int tls_init_done = 0;
408
409 static int
410 tls_init(void *apparg)
411 {
412 if (tls_init_done)
413 return 0;
414
415 SSL_load_error_strings();
416 if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) {
417 tls_errprintf(1, apparg, "SSL_library_init failed.\n");
418 return -1;
419 }
420 tls_init_done = 1;
421 tls_rand_seed();
422 return 0;
423 }
424
425 /*****************************************************************************/
426
427 static void
428 tls_rand_seed_uniquely(void)
429 {
430 struct {
431 pid_t pid;
432 time_t time;
433 void *stack;
434 } data;
435
436 data.pid = getpid();
437 data.time = time(NULL);
438 data.stack = (void *)&data;
439
440 RAND_seed((const void *)&data, sizeof data);
441 }
442
443 void
444 tls_rand_seed(void)
445 {
446 struct {
447 struct utsname uname;
448 int uname_1;
449 int uname_2;
450 uid_t uid;
451 uid_t euid;
452 gid_t gid;
453 gid_t egid;
454 } data;
455
456 data.uname_1 = uname(&data.uname);
457 data.uname_2 = errno; /* Let's hope that uname fails randomly :-) */
458
459 data.uid = getuid();
460 data.euid = geteuid();
461 data.gid = getgid();
462 data.egid = getegid();
463
464 RAND_seed((const void *)&data, sizeof data);
465 tls_rand_seed_uniquely();
466 }
467
468 static int tls_rand_seeded_p = 0;
469
470 #define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */
471 int
472 tls_rand_seed_from_file(const char *filename, size_t n, void *apparg)
473 {
474 /* Seed OpenSSL's random number generator from file.
475 Try to read n bytes if n > 0, whole file if n == 0. */
476
477 int r;
478
479 if (tls_init(apparg) == -1)
480 return -1;
481 tls_rand_seed();
482
483 r = RAND_load_file(filename, (n > 0 && n < LONG_MAX) ? (long)n : LONG_MAX);
484 /* r is the number of bytes filled into the random number generator,
485 * which are taken from "stat(filename, ...)" in addition to the
486 * file contents.
487 */
488 assert(1 < my_MIN_SEED_BYTES);
489 /* We need to detect at least those cases when the file does not exist
490 * at all. With current versions of OpenSSL, this should do it: */
491 if (n == 0)
492 n = my_MIN_SEED_BYTES;
493 if (r < n) {
494 tls_errprintf(1, apparg, "rand_seed_from_file: could not read %d bytes from %s.\n", n, filename);
495 return -1;
496 } else {
497 tls_rand_seeded_p = 1;
498 return 0;
499 }
500 }
501
502 void
503 tls_rand_seed_from_memory(const void *buf, size_t n)
504 {
505 size_t i = 0;
506
507 while (i < n) {
508 size_t rest = n - i;
509 int chunk = rest < INT_MAX ? (int)rest : INT_MAX;
510 RAND_seed((const char *)buf + i, chunk);
511 i += chunk;
512 }
513 tls_rand_seeded_p = 1;
514 }
515
516
517 /*****************************************************************************/
518
519 struct tls_x509_name_string {
520 char str[100];
521 };
522
523 static void
524 tls_get_x509_subject_name_oneline(X509 *cert, struct tls_x509_name_string *namestring)
525 {
526 X509_NAME *name;
527
528 if (cert == NULL) {
529 namestring->str[0] = '\0';
530 return;
531 }
532
533 name = X509_get_subject_name(cert); /* does not increment any reference counter */
534
535 assert(sizeof namestring->str >= 4); /* "?" or "...", plus 0 */
536
537 if (name == NULL) {
538 namestring->str[0] = '?';
539 namestring->str[1] = 0;
540 } else {
541 size_t len;
542
543 X509_NAME_oneline(name, namestring->str, sizeof namestring->str);
544 len = strlen(namestring->str);
545 assert(namestring->str[len] == 0);
546 assert(len < sizeof namestring->str);
547
548 if (len+1 == sizeof namestring->str) {
549 /* (Probably something was cut off.)
550 * Does not really work -- X509_NAME_oneline truncates after
551 * name components, we cannot tell from the result whether
552 * anything is missing. */
553
554 assert(namestring->str[len] == 0);
555 namestring->str[--len] = '.';
556 namestring->str[--len] = '.';
557 namestring->str[--len] = '.';
558 }
559 }
560 }
561
562 /*****************************************************************************/
563
564 /* to hinder OpenSSL from asking for passphrases */
565 static int
566 no_passphrase_callback(char *buf, int num, int w, void *arg)
567 {
568 return -1;
569 }
570
571 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
572 static int
573 verify_dont_fail_cb(X509_STORE_CTX *c, void *unused_arg)
574 #else
575 static int
576 verify_dont_fail_cb(X509_STORE_CTX *c)
577 #endif
578 {
579 int i;
580
581 i = X509_verify_cert(c); /* sets c->error */
582 #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
583 * certificates -- they could
584 * survive session reuse, but
585 * OpenSSL < 0.9.5-dev does not
586 * preserve their verify_result */
587 if (i == 0)
588 return 1;
589 else
590 #endif
591 return i;
592 }
593
594 static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it just once */
595
596 void
597 tls_set_dhe1024(int i, void *apparg)
598 {
599 DSA *dsaparams;
600 DH *dhparams;
601 const char *seed[] = { ";-) :-( :-) :-( ",
602 ";-) :-( :-) :-( ",
603 "Random String no. 12",
604 ";-) :-( :-) :-( ",
605 "hackers have even mo", /* from jargon file */
606 };
607 unsigned char seedbuf[20];
608
609 tls_init(apparg);
610 if (i >= 0) {
611 i %= sizeof seed / sizeof seed[0];
612 assert(strlen(seed[i]) == 20);
613 memcpy(seedbuf, seed[i], 20);
614 dsaparams = DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL);
615 } else {
616 /* random parameters (may take a while) */
617 dsaparams = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL);
618 }
619
620 if (dsaparams == NULL) {
621 tls_openssl_errors("", "", NULL, apparg);
622 return;
623 }
624 dhparams = DSA_dup_DH(dsaparams);
625 DSA_free(dsaparams);
626 if (dhparams == NULL) {
627 tls_openssl_errors("", "", NULL, apparg);
628 return;
629 }
630 if (tls_dhe1024 != NULL)
631 DH_free(tls_dhe1024);
632 tls_dhe1024 = dhparams;
633 }
634
635 struct tls_create_ctx_args
636 tls_create_ctx_defaultargs(void)
637 {
638 struct tls_create_ctx_args ret;
639
640 ret.client_p = 0;
641 ret.certificate_file = NULL;
642 ret.key_file = NULL;
643 ret.ca_file = NULL;
644 ret.verify_depth = -1;
645 ret.fail_unless_verified = 0;
646 ret.export_p = 0;
647
648 return ret;
649 }
650
651 SSL_CTX *
652 tls_create_ctx(struct tls_create_ctx_args a, void *apparg)
653 {
654 int r;
655 static long context_num = 0;
656 SSL_CTX *ret;
657 const char *err_pref_1 = "", *err_pref_2 = "";
658
659 if (tls_init(apparg) == -1)
660 return NULL;
661
662 ret = SSL_CTX_new((a.client_p? SSLv23_client_method:SSLv23_server_method)());
663
664 if (ret == NULL)
665 goto err;
666
667 SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback);
668 SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE);
669
670 if ((a.certificate_file != NULL) || (a.key_file != NULL)) {
671 if (a.key_file == NULL) {
672 tls_errprintf(1, apparg, "Need a key file.\n");
673 goto err_return;
674 }
675 if (a.certificate_file == NULL) {
676 tls_errprintf(1, apparg, "Need a certificate chain file.\n");
677 goto err_return;
678 }
679
680 if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM))
681 goto err;
682 if (!tls_rand_seeded_p) {
683 /* particularly paranoid people may not like this --
684 * so provide your own random seeding before calling this */
685 if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1)
686 goto err_return;
687 }
688 if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file))
689 goto err;
690 if (!SSL_CTX_check_private_key(ret)) {
691 tls_errprintf(1, apparg, "Private key \"%s\" does not match certificate \"%s\".\n", a.key_file, a.certificate_file);
692 goto err_peek;
693 }
694 }
695
696 if ((a.ca_file != NULL) || (a.verify_depth > 0)) {
697 context_num++;
698 r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num, (unsigned int)sizeof context_num);
699 if (!r)
700 goto err;
701
702 SSL_CTX_set_verify(ret, SSL_VERIFY_PEER | (a.fail_unless_verified ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 0);
703 if (!a.fail_unless_verified)
704 SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL);
705
706 if (a.verify_depth > 0)
707 SSL_CTX_set_verify_depth(ret, a.verify_depth);
708
709 if (a.ca_file != NULL) {
710 r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL /* no CA-directory */); /* does not report failure if file does not exist ... */
711 if (!r) {
712 err_pref_1 = " while processing certificate file ";
713 err_pref_2 = a.ca_file;
714 goto err;
715 }
716
717 if (!a.client_p) {
718 /* SSL_load_client_CA_file is a misnomer, it just creates a list of CNs. */
719 SSL_CTX_set_client_CA_list(ret, SSL_load_client_CA_file(a.ca_file));
720 /* SSL_CTX_set_client_CA_list does not have a return value;
721 * it does not really need one, but make sure
722 * (we really test if SSL_load_client_CA_file worked) */
723 if (SSL_CTX_get_client_CA_list(ret) == NULL) {
724 tls_errprintf(1, apparg, "Could not set client CA list from \"%s\".\n", a.ca_file);
725 goto err_peek;
726 }
727 }
728 }
729 }
730
731 if (!a.client_p) {
732 if (tls_dhe1024 == NULL) {
733 int i;
734
735 RAND_bytes((unsigned char *) &i, sizeof i);
736 /* make sure that i is non-negative -- pick one of the provided
737 * seeds */
738 if (i < 0)
739 i = -i;
740 if (i < 0)
741 i = 0;
742 tls_set_dhe1024(i, apparg);
743 if (tls_dhe1024 == NULL)
744 goto err_return;
745 }
746
747 if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
748 goto err;
749
750 /* avoid small subgroup attacks: */
751 SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
752 }
753
754 #ifndef NO_RSA
755 if (!a.client_p && a.export_p) {
756 RSA *tmpkey;
757
758 tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
759 if (tmpkey == NULL)
760 goto err;
761 if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
762 RSA_free(tmpkey);
763 goto err;
764 }
765 RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
766 }
767 #endif
768
769 return ret;
770
771 err_peek:
772 if (!ERR_peek_error())
773 goto err_return;
774 err:
775 tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
776 err_return:
777 if (ret != NULL)
778 SSL_CTX_free(ret);
779 return NULL;
780 }
781
782
783 /*****************************************************************************/
784
785 static int
786 tls_socket_nonblocking(int fd)
787 {
788 int v, r;
789
790 v = fcntl(fd, F_GETFL, 0);
791 if (v == -1) {
792 if (errno == EINVAL)
793 return 0; /* already shut down -- ignore */
794 return -1;
795 }
796 r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
797 if (r == -1) {
798 if (errno == EINVAL)
799 return 0; /* already shut down -- ignore */
800 return -1;
801 }
802 return 0;
803 }
804
805 static int
806 max(int a, int b)
807 {
808 return a > b ? a : b;
809 }
810
811 static void
812 tls_sockets_select(int read_select_1, int read_select_2, int write_select_1, int write_select_2, int seconds /* timeout, -1 means no timeout */)
813 {
814 int maxfd, n;
815 fd_set reads, writes;
816 struct timeval timeout;
817 struct timeval *timeout_p;
818
819 assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1 && write_select_2 >= -1);
820 assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE -1 && write_select_1 < FD_SETSIZE -1 && write_select_2 < FD_SETSIZE -1);
821
822 maxfd = max(max(read_select_1, read_select_2), max(write_select_1, write_select_2));
823 assert(maxfd >= 0);
824
825 FD_ZERO(&reads);
826 FD_ZERO(&writes);
827
828 for(n = 0; n < 4; ++n) {
829 int i = n % 2;
830 int w = n >= 2;
831 /* loop over all (i, w) in {0,1}x{0,1} */
832 int fd;
833
834 if (i == 0 && w == 0)
835 fd = read_select_1;
836 else if (i == 1 && w == 0)
837 fd = read_select_2;
838 else if (i == 0 && w == 1)
839 fd = write_select_1;
840 else {
841 assert(i == 1 && w == 1);
842 fd = write_select_2;
843 }
844
845 if (fd >= 0) {
846 if (w == 0)
847 FD_SET(fd, &reads);
848 else /* w == 1 */
849 FD_SET(fd, &writes);
850 }
851 }
852
853 if (seconds >= 0) {
854 timeout.tv_sec = seconds;
855 timeout.tv_usec = 0;
856 timeout_p = &timeout;
857 } else
858 timeout_p = NULL;
859
860 DEBUG_MSG2("select no.", ++tls_select_count);
861 select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
862 DEBUG_MSG("cont.");
863 }
864
865 /*****************************************************************************/
866
867 #define TUNNELBUFSIZE (16*1024)
868 struct tunnelbuf {
869 char buf[TUNNELBUFSIZE];
870 size_t len;
871 size_t offset;
872 };
873
874 static int tls_connect_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
875
876 static int tls_accept_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
877
878 static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
879
880 static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
881
882 static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
883
884 static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
885
886 static void write_info(SSL *ssl, int *info_fd)
887 {
888 if (*info_fd != -1) {
889 long v;
890 int v_ok;
891 struct tls_x509_name_string peer;
892 char infobuf[TLS_INFO_SIZE];
893 int r;
894
895 DEBUG_MSG("write_info");
896 v = SSL_get_verify_result(ssl);
897 v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
898 {
899 X509 *peercert;
900
901 peercert = SSL_get_peer_certificate(ssl);
902 tls_get_x509_subject_name_oneline(peercert, &peer);
903 if (peercert != NULL)
904 X509_free(peercert);
905 }
906 if (peer.str[0] == '\0')
907 v_ok = '0'; /* no cert at all */
908 else
909 if (strchr(peer.str, '\n')) {
910 /* should not happen, but make sure */
911 *strchr(peer.str, '\n') = '\0';
912 }
913 r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok, X509_verify_cert_error_string(v), peer.str);
914 DEBUG_MSG2("snprintf", r);
915 if (r == -1 || r >= sizeof infobuf)
916 r = sizeof infobuf - 1;
917 write(*info_fd, infobuf, r);
918 close (*info_fd);
919 *info_fd = -1;
920 }
921 }
922
923
924 /* tls_proxy expects that all fds are closed after return */
925 static void
926 tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
927 {
928 struct tunnelbuf clear_to_tls, tls_to_clear;
929 SSL *ssl;
930 BIO *rbio, *wbio;
931 int closed, in_handshake;
932 const char *err_pref_1 = "", *err_pref_2 = "";
933 const char *err_def = NULL;
934
935 assert(clear_fd != -1);
936 assert(tls_fd != -1);
937 assert(clear_fd < FD_SETSIZE);
938 assert(tls_fd < FD_SETSIZE);
939 /* info_fd may be -1 */
940 assert(ctx != NULL);
941
942 tls_rand_seed_uniquely();
943
944 tls_socket_nonblocking(clear_fd);
945 DEBUG_MSG2("clear_fd", clear_fd);
946 tls_socket_nonblocking(tls_fd);
947 DEBUG_MSG2("tls_fd", tls_fd);
948
949 ssl = SSL_new(ctx);
950 if (ssl == NULL)
951 goto err;
952 DEBUG_MSG("SSL_new");
953 if (!SSL_set_fd(ssl, tls_fd))
954 goto err;
955 rbio = SSL_get_rbio(ssl);
956 wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
957 assert(rbio != NULL);
958 assert(wbio != NULL);
959 if (client_p)
960 SSL_set_connect_state(ssl);
961 else
962 SSL_set_accept_state(ssl);
963
964 closed = 0;
965 in_handshake = 1;
966 tls_to_clear.len = 0;
967 tls_to_clear.offset = 0;
968 clear_to_tls.len = 0;
969 clear_to_tls.offset = 0;
970
971 err_def = "I/O error";
972
973 /* loop finishes as soon as we detect that one side closed;
974 * when all (program and OS) buffers have enough space,
975 * the data from the last succesful read in each direction is transferred
976 * before close */
977 do {
978 int clear_read_select = 0, clear_write_select = 0,
979 tls_read_select = 0, tls_write_select = 0,
980 progress = 0;
981 int r;
982 unsigned long num_read = BIO_number_read(rbio),
983 num_written = BIO_number_written(wbio);
984
985 DEBUG_MSG2("loop iteration", ++tls_loop_count);
986
987 if (in_handshake) {
988 DEBUG_MSG("in_handshake");
989 if (client_p)
990 r = tls_connect_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
991 else
992 r = tls_accept_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
993 if (r != 0) {
994 write_info(ssl, &info_fd);
995 goto err;
996 }
997 if (closed)
998 goto err_return;
999 if (!SSL_in_init(ssl)) {
1000 in_handshake = 0;
1001 write_info(ssl, &info_fd);
1002 }
1003 }
1004
1005 if (clear_to_tls.len != 0 && !in_handshake) {
1006 assert(!closed);
1007
1008 r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1009 if (r != 0)
1010 goto err;
1011 if (closed) {
1012 assert(progress);
1013 tls_to_clear.offset = 0;
1014 tls_to_clear.len = 0;
1015 }
1016 }
1017
1018 if (tls_to_clear.len != 0) {
1019 assert(!closed);
1020
1021 r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select, &closed, &progress);
1022 if (r != 0)
1023 goto err_return;
1024 if (closed) {
1025 assert(progress);
1026 clear_to_tls.offset = 0;
1027 clear_to_tls.len = 0;
1028 }
1029 }
1030
1031 if (!closed) {
1032 if (clear_to_tls.offset + clear_to_tls.len < sizeof clear_to_tls.buf) {
1033 r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select, &closed, &progress);
1034 if (r != 0)
1035 goto err_return;
1036 if (closed) {
1037 r = SSL_shutdown(ssl);
1038 DEBUG_MSG2("SSL_shutdown", r);
1039 }
1040 }
1041 }
1042
1043 if (!closed && !in_handshake) {
1044 if (tls_to_clear.offset + tls_to_clear.len < sizeof tls_to_clear.buf) {
1045 r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1046 if (r != 0)
1047 goto err;
1048 if (closed) {
1049 r = SSL_shutdown(ssl);
1050 DEBUG_MSG2("SSL_shutdown", r);
1051 }
1052 }
1053 }
1054
1055 if (!progress) {
1056 DEBUG_MSG("!progress?");
1057 if (num_read != BIO_number_read(rbio) || num_written != BIO_number_written(wbio))
1058 progress = 1;
1059
1060 if (!progress) {
1061 DEBUG_MSG("!progress");
1062 assert(clear_read_select || tls_read_select || clear_write_select || tls_write_select);
1063 tls_sockets_select(clear_read_select ? clear_fd : -1, tls_read_select ? tls_fd : -1, clear_write_select ? clear_fd : -1, tls_write_select ? tls_fd : -1, -1);
1064 }
1065 }
1066 } while (!closed);
1067 return;
1068
1069 err:
1070 tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
1071 err_return:
1072 return;
1073 }
1074
1075
1076 static int
1077 tls_get_error(SSL *ssl, int r, int *write_select, int *read_select, int *closed, int *progress)
1078 {
1079 int err = SSL_get_error(ssl, r);
1080
1081 if (err == SSL_ERROR_NONE) {
1082 assert(r > 0);
1083 *progress = 1;
1084 return 0;
1085 }
1086
1087 assert(r <= 0);
1088
1089 switch (err) {
1090 case SSL_ERROR_ZERO_RETURN:
1091 assert(r == 0);
1092 *closed = 1;
1093 *progress = 1;
1094 return 0;
1095
1096 case SSL_ERROR_WANT_WRITE:
1097 *write_select = 1;
1098 return 0;
1099
1100 case SSL_ERROR_WANT_READ:
1101 *read_select = 1;
1102 return 0;
1103 }
1104
1105 return -1;
1106 }
1107
1108 static int
1109 tls_connect_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1110 {
1111 int n, r;
1112
1113 DEBUG_MSG("tls_connect_attempt");
1114 n = SSL_connect(ssl);
1115 DEBUG_MSG2("SSL_connect",n);
1116 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1117 if (r == -1)
1118 *err_pref = " during SSL_connect";
1119 return r;
1120 }
1121
1122 static int
1123 tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1124 {
1125 int n, r;
1126
1127 DEBUG_MSG("tls_accept_attempt");
1128 n = SSL_accept(ssl);
1129 DEBUG_MSG2("SSL_accept",n);
1130 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1131 if (r == -1)
1132 *err_pref = " during SSL_accept";
1133 return r;
1134 }
1135
1136 static int
1137 tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1138 {
1139 int n, r;
1140
1141 DEBUG_MSG("tls_write_attempt");
1142 n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
1143 DEBUG_MSG2("SSL_write",n);
1144 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1145 if (n > 0) {
1146 buf->len -= n;
1147 assert(buf->len >= 0);
1148 if (buf->len == 0)
1149 buf->offset = 0;
1150 else
1151 buf->offset += n;
1152 }
1153 if (r == -1)
1154 *err_pref = " during SSL_write";
1155 return r;
1156 }
1157
1158 static int
1159 tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1160 {
1161 int n, r;
1162 size_t total;
1163
1164 DEBUG_MSG("tls_read_attempt");
1165 total = buf->offset + buf->len;
1166 assert(total < sizeof buf->buf);
1167 n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
1168 DEBUG_MSG2("SSL_read",n);
1169 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1170 if (n > 0) {
1171 buf->len += n;
1172 assert(buf->offset + buf->len <= sizeof buf->buf);
1173 }
1174 if (r == -1)
1175 *err_pref = " during SSL_read";
1176 return r;
1177 }
1178
1179 static int
1180 get_error(int r, int *select, int *closed, int *progress)
1181 {
1182 if (r >= 0) {
1183 *progress = 1;
1184 if (r == 0)
1185 *closed = 1;
1186 return 0;
1187 } else {
1188 assert(r == -1);
1189 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1190 *select = 1;
1191 return 0;
1192 } else if (errno == EPIPE) {
1193 *progress = 1;
1194 *closed = 1;
1195 return 0;
1196 } else
1197 return -1;
1198 }
1199 }
1200
1201 static int write_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1202 {
1203 int n, r;
1204
1205 DEBUG_MSG("write_attempt");
1206 n = write(fd, buf->buf + buf->offset, buf->len);
1207 DEBUG_MSG2("write",n);
1208 r = get_error(n, select, closed, progress);
1209 if (n > 0) {
1210 buf->len -= n;
1211 assert(buf->len >= 0);
1212 if (buf->len == 0)
1213 buf->offset = 0;
1214 else
1215 buf->offset += n;
1216 }
1217 if (r == -1)
1218 tls_errprintf(1, tls_child_apparg, "write error: %s\n", strerror(errno));
1219 return r;
1220 }
1221
1222 static int
1223 read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1224 {
1225 int n, r;
1226 size_t total;
1227
1228 DEBUG_MSG("read_attempt");
1229 total = buf->offset + buf->len;
1230 assert(total < sizeof buf->buf);
1231 n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
1232 DEBUG_MSG2("read",n);
1233 r = get_error(n, select, closed, progress);
1234 if (n > 0) {
1235 buf->len += n;
1236 assert(buf->offset + buf->len <= sizeof buf->buf);
1237 }
1238 if (r == -1)
1239 tls_errprintf(1, tls_child_apparg, "read error: %s\n", strerror(errno));
1240 return r;
1241 }