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