It seems like gcc does canonicalisation of file names. More
[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.2 2001/09/24 07:54:09 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.2 2001/09/24 07:54:09 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 static int
571 verify_dont_fail_cb(X509_STORE_CTX *c)
572 {
573     int i;
574     
575     i = X509_verify_cert(c); /* sets c->error */
576 #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
577                                            * certificates -- they could
578                                            * survive session reuse, but
579                                            * OpenSSL < 0.9.5-dev does not
580                                            * preserve their verify_result */
581     if (i == 0)
582         return 1;
583     else
584 #endif
585         return i;
586 }
587
588 static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it just once */
589
590 void
591 tls_set_dhe1024(int i, void *apparg)
592 {
593     DSA *dsaparams;
594     DH *dhparams;
595     const char *seed[] = { ";-)  :-(  :-)  :-(  ",
596                            ";-)  :-(  :-)  :-(  ",
597                            "Random String no. 12",
598                            ";-)  :-(  :-)  :-(  ",
599                            "hackers have even mo", /* from jargon file */
600     };
601     unsigned char seedbuf[20];
602     
603     tls_init(apparg);
604     if (i >= 0) {
605         i %= sizeof seed / sizeof seed[0];
606         assert(strlen(seed[i]) == 20);
607         memcpy(seedbuf, seed[i], 20);
608         dsaparams = DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL);
609     } else {
610         /* random parameters (may take a while) */
611         dsaparams = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL);
612     }
613     
614     if (dsaparams == NULL) {
615         tls_openssl_errors("", "", NULL, apparg);
616         return;
617     }
618     dhparams = DSA_dup_DH(dsaparams);
619     DSA_free(dsaparams);
620     if (dhparams == NULL) {
621         tls_openssl_errors("", "", NULL, apparg);
622         return;
623     }
624     if (tls_dhe1024 != NULL)
625         DH_free(tls_dhe1024);
626     tls_dhe1024 = dhparams;
627 }
628
629 struct tls_create_ctx_args
630 tls_create_ctx_defaultargs(void)
631 {
632         struct tls_create_ctx_args ret;
633
634         ret.client_p = 0;
635         ret.certificate_file = NULL;
636         ret.key_file = NULL;
637         ret.ca_file = NULL;
638         ret.verify_depth = -1;
639         ret.fail_unless_verified = 0;
640         ret.export_p = 0;
641
642         return ret;
643 }
644
645 SSL_CTX *
646 tls_create_ctx(struct tls_create_ctx_args a, void *apparg)
647 {
648     int r;
649     static long context_num = 0;
650     SSL_CTX *ret;
651     const char *err_pref_1 = "", *err_pref_2 = "";
652     
653     if (tls_init(apparg) == -1)
654         return NULL;
655
656     ret = SSL_CTX_new((a.client_p? SSLv23_client_method:SSLv23_server_method)());
657
658     if (ret == NULL)
659         goto err;
660
661     SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback);
662     SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE);
663     
664     if ((a.certificate_file != NULL) || (a.key_file != NULL)) {
665         if (a.key_file == NULL) {
666             tls_errprintf(1, apparg, "Need a key file.\n");
667             goto err_return;
668         }
669         if (a.certificate_file == NULL) {
670             tls_errprintf(1, apparg, "Need a certificate chain file.\n");
671             goto err_return;
672         }
673         
674         if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM))
675             goto err;
676         if (!tls_rand_seeded_p) {
677             /* particularly paranoid people may not like this --
678              * so provide your own random seeding before calling this */
679             if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1)
680                 goto err_return;
681         }
682         if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file))
683             goto err;
684         if (!SSL_CTX_check_private_key(ret)) {
685             tls_errprintf(1, apparg, "Private key \"%s\" does not match certificate \"%s\".\n", a.key_file, a.certificate_file);
686             goto err_peek;
687         }
688     }
689     
690     if ((a.ca_file != NULL) || (a.verify_depth > 0)) {
691         context_num++;
692         r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num, (unsigned int)sizeof context_num);
693         if (!r)
694             goto err;
695         
696         SSL_CTX_set_verify(ret, SSL_VERIFY_PEER | (a.fail_unless_verified ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 0);
697         if (!a.fail_unless_verified)
698             SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL);
699             
700         if (a.verify_depth > 0)
701             SSL_CTX_set_verify_depth(ret, a.verify_depth);
702         
703         if (a.ca_file != NULL) {
704             r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL /* no CA-directory */); /* does not report failure if file does not exist ... */
705             if (!r) {
706                 err_pref_1 = " while processing certificate file ";
707                 err_pref_2 = a.ca_file;
708                 goto err;
709             }
710             
711             if (!a.client_p) {
712                 /* SSL_load_client_CA_file is a misnomer, it just creates a list of CNs. */
713                 SSL_CTX_set_client_CA_list(ret, SSL_load_client_CA_file(a.ca_file));
714                 /* SSL_CTX_set_client_CA_list does not have a return value;
715                  * it does not really need one, but make sure
716                  * (we really test if SSL_load_client_CA_file worked) */
717                 if (SSL_CTX_get_client_CA_list(ret) == NULL) {
718                     tls_errprintf(1, apparg, "Could not set client CA list from \"%s\".\n", a.ca_file);
719                     goto err_peek;
720                 }
721             }
722         }
723     }
724     
725     if (!a.client_p) {
726         if (tls_dhe1024 == NULL) {
727             int i;
728
729             RAND_bytes((unsigned char *) &i, sizeof i);
730             /* make sure that i is non-negative -- pick one of the provided
731              * seeds */
732             if (i < 0)
733                 i = -i;
734             if (i < 0)
735                 i = 0;
736             tls_set_dhe1024(i, apparg);
737             if (tls_dhe1024 == NULL)
738                 goto err_return;
739         }
740         
741         if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
742             goto err;
743
744         /* avoid small subgroup attacks: */
745         SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
746     }
747         
748 #ifndef NO_RSA
749     if (!a.client_p && a.export_p) {
750         RSA *tmpkey;
751
752         tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
753         if (tmpkey == NULL)
754             goto err;
755         if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
756             RSA_free(tmpkey);
757             goto err;
758         }
759         RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
760     }
761 #endif
762         
763     return ret;
764     
765  err_peek:
766     if (!ERR_peek_error())
767         goto err_return;
768  err:
769     tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
770  err_return:
771     if (ret != NULL)
772         SSL_CTX_free(ret);
773     return NULL;
774 }
775
776
777 /*****************************************************************************/
778
779 static int
780 tls_socket_nonblocking(int fd)
781 {
782     int v, r;
783
784     v = fcntl(fd, F_GETFL, 0);
785     if (v == -1) {
786         if (errno == EINVAL)
787             return 0; /* already shut down -- ignore */
788         return -1;
789     }
790     r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
791     if (r == -1) {
792         if (errno == EINVAL)
793             return 0; /* already shut down -- ignore */
794         return -1;
795     }
796     return 0;
797 }
798
799 static int
800 max(int a, int b)
801 {
802     return a > b ? a : b;
803 }
804
805 static void
806 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 */)
807 {
808     int maxfd, n;
809     fd_set reads, writes;
810     struct timeval timeout;
811     struct timeval *timeout_p;
812     
813     assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1 && write_select_2 >= -1);
814     assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE -1 && write_select_1 < FD_SETSIZE -1 && write_select_2 < FD_SETSIZE -1);
815
816     maxfd = max(max(read_select_1, read_select_2), max(write_select_1, write_select_2));
817     assert(maxfd >= 0);
818
819     FD_ZERO(&reads);
820     FD_ZERO(&writes);
821     
822     for(n = 0; n < 4; ++n) {
823         int i = n % 2;
824         int w = n >= 2;
825         /* loop over all (i, w) in {0,1}x{0,1} */
826         int fd;
827         
828         if (i == 0 && w == 0)
829             fd = read_select_1;
830         else if (i == 1 && w == 0)
831             fd = read_select_2;
832         else if (i == 0 && w == 1)
833             fd = write_select_1;
834         else {
835             assert(i == 1 && w == 1);
836             fd = write_select_2;
837         }
838         
839         if (fd >= 0) {
840             if (w == 0)
841                 FD_SET(fd, &reads);
842             else /* w == 1 */
843                 FD_SET(fd, &writes);
844         }
845     }
846
847     if (seconds >= 0) {
848         timeout.tv_sec = seconds;
849         timeout.tv_usec = 0;
850         timeout_p = &timeout;
851     } else 
852         timeout_p = NULL;
853
854     DEBUG_MSG2("select no.", ++tls_select_count);
855     select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
856     DEBUG_MSG("cont.");
857 }
858
859 /*****************************************************************************/
860
861 #define TUNNELBUFSIZE (16*1024)
862 struct tunnelbuf {
863     char buf[TUNNELBUFSIZE];
864     size_t len;
865     size_t offset;
866 };
867
868 static int tls_connect_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
869
870 static int tls_accept_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
871
872 static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
873
874 static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
875
876 static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
877
878 static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
879
880 static void write_info(SSL *ssl, int *info_fd)
881 {
882     if (*info_fd != -1) {
883         long v;
884         int v_ok;
885         struct tls_x509_name_string peer;
886         char infobuf[TLS_INFO_SIZE];
887         int r;
888
889         DEBUG_MSG("write_info");
890         v = SSL_get_verify_result(ssl);
891         v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
892         {
893             X509 *peercert;
894
895             peercert = SSL_get_peer_certificate(ssl);
896             tls_get_x509_subject_name_oneline(peercert, &peer);
897             if (peercert != NULL)
898                 X509_free(peercert);
899         }
900         if (peer.str[0] == '\0')
901             v_ok = '0'; /* no cert at all */
902         else
903             if (strchr(peer.str, '\n')) {
904                 /* should not happen, but make sure */
905                 *strchr(peer.str, '\n') = '\0';
906             }
907         r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok, X509_verify_cert_error_string(v), peer.str);
908         DEBUG_MSG2("snprintf", r);
909         if (r == -1 || r >= sizeof infobuf)
910             r = sizeof infobuf - 1;
911         write(*info_fd, infobuf, r);
912         close (*info_fd);
913         *info_fd = -1;
914     }
915 }
916
917
918 /* tls_proxy expects that all fds are closed after return */
919 static void
920 tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
921 {
922     struct tunnelbuf clear_to_tls, tls_to_clear;
923     SSL *ssl;
924     BIO *rbio, *wbio;
925     int closed, in_handshake;
926     const char *err_pref_1 = "", *err_pref_2 = "";
927     const char *err_def = NULL;
928
929     assert(clear_fd != -1);
930     assert(tls_fd != -1);
931     assert(clear_fd < FD_SETSIZE);
932     assert(tls_fd < FD_SETSIZE);
933     /* info_fd may be -1 */
934     assert(ctx != NULL);
935
936     tls_rand_seed_uniquely();
937
938     tls_socket_nonblocking(clear_fd);
939     DEBUG_MSG2("clear_fd", clear_fd);
940     tls_socket_nonblocking(tls_fd);
941     DEBUG_MSG2("tls_fd", tls_fd);
942
943     ssl = SSL_new(ctx);
944     if (ssl == NULL)
945         goto err;
946     DEBUG_MSG("SSL_new");
947     if (!SSL_set_fd(ssl, tls_fd))
948         goto err;
949     rbio = SSL_get_rbio(ssl);
950     wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
951     assert(rbio != NULL);
952     assert(wbio != NULL);
953     if (client_p)
954         SSL_set_connect_state(ssl);
955     else
956         SSL_set_accept_state(ssl);
957     
958     closed = 0;
959     in_handshake = 1;
960     tls_to_clear.len = 0;
961     tls_to_clear.offset = 0;
962     clear_to_tls.len = 0;
963     clear_to_tls.offset = 0;
964
965     err_def = "I/O error";
966     
967     /* loop finishes as soon as we detect that one side closed;
968      * when all (program and OS) buffers have enough space,
969      * the data from the last succesful read in each direction is transferred
970      * before close */
971     do {
972         int clear_read_select = 0, clear_write_select = 0,
973             tls_read_select = 0, tls_write_select = 0,
974             progress = 0;
975         int r;
976         unsigned long num_read = BIO_number_read(rbio),
977             num_written = BIO_number_written(wbio);
978
979         DEBUG_MSG2("loop iteration", ++tls_loop_count);
980
981         if (in_handshake) {
982             DEBUG_MSG("in_handshake");
983             if (client_p)
984                 r = tls_connect_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
985             else
986                 r = tls_accept_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
987             if (r != 0) {
988                 write_info(ssl, &info_fd);
989                 goto err;
990             }
991             if (closed)
992                 goto err_return;
993             if (!SSL_in_init(ssl)) {
994                 in_handshake = 0;
995                 write_info(ssl, &info_fd);
996             }
997         }
998         
999         if (clear_to_tls.len != 0 && !in_handshake) {
1000             assert(!closed);
1001             
1002             r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1003             if (r != 0)
1004                 goto err;
1005             if (closed) {
1006                 assert(progress);
1007                 tls_to_clear.offset = 0;
1008                 tls_to_clear.len = 0;
1009             }
1010         }
1011         
1012         if (tls_to_clear.len != 0) {
1013             assert(!closed);
1014
1015             r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select, &closed, &progress);
1016             if (r != 0)
1017                 goto err_return;
1018             if (closed) {
1019                 assert(progress);
1020                 clear_to_tls.offset = 0;
1021                 clear_to_tls.len = 0;
1022             }
1023         }
1024         
1025         if (!closed) {
1026             if (clear_to_tls.offset + clear_to_tls.len < sizeof clear_to_tls.buf) {
1027                 r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select, &closed, &progress);
1028                 if (r != 0)
1029                     goto err_return;
1030                 if (closed) {
1031                     r = SSL_shutdown(ssl);
1032                     DEBUG_MSG2("SSL_shutdown", r);
1033                 }
1034             }
1035         }
1036         
1037         if (!closed && !in_handshake) {
1038             if (tls_to_clear.offset + tls_to_clear.len < sizeof tls_to_clear.buf) {
1039                 r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1040                 if (r != 0)
1041                     goto err;
1042                 if (closed) {
1043                     r = SSL_shutdown(ssl);
1044                     DEBUG_MSG2("SSL_shutdown", r);
1045                 }
1046             }
1047         }
1048
1049         if (!progress) {
1050             DEBUG_MSG("!progress?");
1051             if (num_read != BIO_number_read(rbio) || num_written != BIO_number_written(wbio))
1052                 progress = 1;
1053
1054             if (!progress) {
1055                 DEBUG_MSG("!progress");
1056                 assert(clear_read_select || tls_read_select || clear_write_select || tls_write_select);
1057                 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);
1058             }
1059         }
1060     } while (!closed);
1061     return;
1062
1063  err:
1064     tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
1065  err_return:
1066     return;
1067 }
1068
1069
1070 static int
1071 tls_get_error(SSL *ssl, int r, int *write_select, int *read_select, int *closed, int *progress)
1072 {
1073     int err = SSL_get_error(ssl, r);
1074
1075     if (err == SSL_ERROR_NONE) {
1076         assert(r > 0);
1077         *progress = 1;
1078         return 0;
1079     }
1080
1081     assert(r <= 0);
1082
1083     switch (err) {
1084     case SSL_ERROR_ZERO_RETURN:
1085         assert(r == 0);
1086         *closed = 1;
1087         *progress = 1;
1088         return 0;
1089
1090     case SSL_ERROR_WANT_WRITE:
1091         *write_select = 1;
1092         return 0;
1093         
1094     case SSL_ERROR_WANT_READ:
1095         *read_select = 1;
1096         return 0;
1097     }
1098
1099     return -1;
1100 }
1101
1102 static int
1103 tls_connect_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1104 {
1105     int n, r;
1106
1107     DEBUG_MSG("tls_connect_attempt");
1108     n = SSL_connect(ssl);
1109     DEBUG_MSG2("SSL_connect",n);
1110     r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1111     if (r == -1)
1112         *err_pref = " during SSL_connect";
1113     return r;
1114 }
1115
1116 static int
1117 tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1118 {
1119     int n, r;
1120
1121     DEBUG_MSG("tls_accept_attempt");
1122     n = SSL_accept(ssl);
1123     DEBUG_MSG2("SSL_accept",n);
1124     r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1125     if (r == -1)
1126         *err_pref = " during SSL_accept";
1127     return r;
1128 }
1129
1130 static int
1131 tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1132 {
1133     int n, r;
1134
1135     DEBUG_MSG("tls_write_attempt");
1136     n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
1137     DEBUG_MSG2("SSL_write",n);
1138     r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1139     if (n > 0) {
1140         buf->len -= n;
1141         assert(buf->len >= 0);
1142         if (buf->len == 0)
1143             buf->offset = 0;
1144         else
1145             buf->offset += n;
1146     }
1147     if (r == -1)
1148         *err_pref = " during SSL_write";
1149     return r;
1150 }
1151
1152 static int
1153 tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1154 {
1155     int n, r;
1156     size_t total;
1157
1158     DEBUG_MSG("tls_read_attempt");
1159     total = buf->offset + buf->len;
1160     assert(total < sizeof buf->buf);
1161     n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
1162     DEBUG_MSG2("SSL_read",n);
1163     r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1164     if (n > 0) {
1165         buf->len += n;
1166         assert(buf->offset + buf->len <= sizeof buf->buf);
1167     }
1168     if (r == -1)
1169         *err_pref = " during SSL_read";
1170     return r;
1171 }
1172
1173 static int
1174 get_error(int r, int *select, int *closed, int *progress)
1175 {
1176     if (r >= 0) {
1177         *progress = 1;
1178         if (r == 0)
1179             *closed = 1;
1180         return 0;
1181     } else {
1182         assert(r == -1);
1183         if (errno == EAGAIN || errno == EWOULDBLOCK) {
1184             *select = 1;
1185             return 0;
1186         } else if (errno == EPIPE) {
1187             *progress = 1;
1188             *closed = 1;
1189             return 0;
1190         } else
1191             return -1;
1192     }
1193 }
1194
1195 static int write_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1196 {
1197     int n, r;
1198
1199     DEBUG_MSG("write_attempt");
1200     n = write(fd, buf->buf + buf->offset, buf->len);
1201     DEBUG_MSG2("write",n);
1202     r = get_error(n, select, closed, progress);
1203     if (n > 0) {
1204         buf->len -= n;
1205         assert(buf->len >= 0);
1206         if (buf->len == 0)
1207             buf->offset = 0;
1208         else
1209             buf->offset += n;
1210     }
1211     if (r == -1)
1212         tls_errprintf(1, tls_child_apparg, "write error: %s\n", strerror(errno));
1213     return r;
1214 }
1215     
1216 static int
1217 read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1218 {
1219     int n, r;
1220     size_t total;
1221
1222     DEBUG_MSG("read_attempt");
1223     total = buf->offset + buf->len;
1224     assert(total < sizeof buf->buf);
1225     n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
1226     DEBUG_MSG2("read",n);
1227     r = get_error(n, select, closed, progress);
1228     if (n > 0) {
1229         buf->len += n;
1230         assert(buf->offset + buf->len <= sizeof buf->buf);
1231     }
1232     if (r == -1)
1233         tls_errprintf(1, tls_child_apparg, "read error: %s\n", strerror(errno));
1234     return r;
1235 }