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