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