1 /* -*- Mode: C; c-file-style: "bsd" -*- */
3 * easy-tls.c -- generic TLS proxy.
4 * $Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $
7 (c) Copyright 1999 Bodo Moeller. All rights reserved.
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)
15 - the following license:
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that each of the following
22 * 1. Redistributions qualify as "freeware" or "Open Source Software" under
23 * one of the following terms:
25 * (a) Redistributions are made at no charge beyond the reasonable cost of
26 * materials and delivery.
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.
35 * 2. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
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
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.)
48 * 5. Redistributions of any form whatsoever must retain the following
50 * "This product includes software developed by Bodo Moeller."
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.
66 * Attribution for OpenSSL library:
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/)
75 static char const rcsid
[] =
76 "$Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $";
85 #include <sys/select.h>
86 #include <sys/socket.h>
89 #include <sys/types.h>
90 #include <sys/utsname.h>
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>
102 # include <openssl/rsa.h>
104 #include <openssl/ssl.h>
105 #include <openssl/x509.h>
106 #include <openssl/x509_vfy.h>
108 #if OPENSSL_VERSION_NUMBER < 0x00904000L /* 0.9.4-dev */
109 # error "This program needs OpenSSL 0.9.4 or later."
112 #include "easy-tls.h" /* include after <openssl/ssl.h> if both are
115 #if TLS_INFO_SIZE > PIPE_BUF
117 # error "PIPE_BUF < 512" /* non-POSIX */
119 # error "TLS_INFO_SIZE > PIPE_BUF"
122 /*****************************************************************************/
129 * Applications can define:
130 * TLS_APP_PROCESS_INIT -- void ...(int fd, int client_p, void *apparg)
131 * TLS_CUMULATE_ERRORS
133 * TLS_APP_ERRFLUSH -- void ...(int child_p, char *, size_t, void *apparg)
136 #ifndef TLS_APP_PROCESS_INIT
137 # define TLS_APP_PROCESS_INIT(fd, client_p, apparg) ((void) 0)
140 #ifndef TLS_ERROR_BUFSIZ
141 # define TLS_ERROR_BUFSIZ (10*160)
143 #if TLS_ERROR_BUFSIZ < 2 /* {'\n',0} */
144 # error "TLS_ERROR_BUFSIZE is too small."
147 #ifndef TLS_APP_ERRFLUSH
148 # define TLS_APP_ERRFLUSH tls_app_errflush
150 tls_app_errflush(int child_p
, char *errbuf
, size_t num
, void *apparg
)
152 fputs(errbuf
, stderr
);
156 /*****************************************************************************/
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;
164 # define DEBUG_MSG(x) (void)0
165 # define DEBUG_MSG2(x,y) (void)0
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
,
171 static int tls_socket_nonblocking(int fd
);
173 static int tls_child_p
= 0;
174 static void *tls_child_apparg
;
176 struct tls_start_proxy_args
tls_start_proxy_defaultargs(void)
178 struct tls_start_proxy_args ret
;
190 * Slice in TLS proxy process at fd.
192 * 0 ok (*pid is set to child's PID if pid != NULL),
195 * (return value encodes place of error)
198 int tls_start_proxy(struct tls_start_proxy_args a
, void *apparg
)
200 int fds
[2] = { -1, -1 };
201 int infofds
[2] = { -1, -1 };
205 DEBUG_MSG2("tls_start_proxy fd", a
.fd
);
206 DEBUG_MSG2("tls_start_proxy client_p", a
.client_p
);
208 if (a
.fd
== -1 || a
.client_p
== -1 || a
.ctx
== NULL
)
214 if (a
.infofd
!= NULL
) {
218 r
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fds
);
221 if (a
.fd
>= FD_SETSIZE
|| fds
[0] >= FD_SETSIZE
) {
225 if (a
.infofd
!= NULL
) {
241 tls_child_apparg
= apparg
;
243 if (infofds
[0] != -1)
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
);
252 if (infofds
[1] != -1) {
256 /* install fds[1] in place of fd: */
259 getfd
= fcntl(a
.fd
, F_GETFD
);
260 getfl
= fcntl(a
.fd
, F_GETFL
);
261 r
= dup2(fds
[1], a
.fd
);
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];
281 if (infofds
[0] != -1)
283 if (infofds
[1] != -1)
288 /*****************************************************************************/
290 static char errbuf
[TLS_ERROR_BUFSIZ
];
291 static size_t errbuf_i
= 0;
293 static void tls_errflush(void *apparg
)
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';
306 * TLS_APP_ERRFLUSH may modify the string as needed, e.g. substitute
307 * other characters for \n for convenience
309 TLS_APP_ERRFLUSH(tls_child_p
, errbuf
, errbuf_i
, apparg
);
314 static void tls_errprintf(int flush
, void *apparg
, const char *fmt
, ...)
319 if (errbuf_i
< sizeof errbuf
- 1) {
323 n
= (sizeof errbuf
) - errbuf_i
;
324 r
= vsnprintf(errbuf
+ errbuf_i
, n
, fmt
, args
);
330 errbuf_i
= sizeof errbuf
- 1;
331 errbuf
[errbuf_i
] = '\0';
333 assert(errbuf_i
< sizeof errbuf
);
334 assert(errbuf
[errbuf_i
] == 0);
336 #ifndef TLS_CUMULATE_ERRORS
337 tls_errflush(apparg
);
340 tls_errflush(apparg
);
345 * app_prefix.. are for additional information provided by caller. If OpenSSL
346 * error queue is empty, print default_text ("???" if NULL).
348 static char *tls_openssl_errors(const char *app_prefix_1
,
349 const char *app_prefix_2
,
350 const char *default_text
, void *apparg
)
352 static char reasons
[255];
360 int printed_something
= 0;
364 assert(app_prefix_1
!= NULL
);
365 assert(app_prefix_2
!= NULL
);
367 if (default_text
== NULL
)
368 default_text
= "?" "?" "?";
370 while ((err
= ERR_get_error_line_data(&file
, &line
, &data
, &flags
)) != 0) {
371 if (reasons_i
< sizeof reasons
) {
375 n
= (sizeof reasons
) - reasons_i
;
376 r
= snprintf(reasons
+ reasons_i
, n
, "%s%s",
377 (reasons_i
> 0 ? ", " : ""),
378 ERR_reason_error_string(err
));
384 reasons_i
= sizeof reasons
;
386 assert(reasons_i
<= sizeof reasons
);
389 errstring
= ERR_error_string(err
, NULL
);
390 assert(errstring
!= NULL
);
391 tls_errprintf(0, apparg
, "OpenSSL error%s%s: %s:%s:%d:%s\n",
392 app_prefix_1
, app_prefix_2
, errstring
, file
, line
,
393 (flags
& ERR_TXT_STRING
) ? data
: "");
394 printed_something
= 1;
397 if (!printed_something
) {
398 assert(reasons_i
== 0);
399 snprintf(reasons
, sizeof reasons
, "%s", default_text
);
400 tls_errprintf(0, apparg
, "OpenSSL error%s%s: %s\n", app_prefix_1
,
401 app_prefix_2
, default_text
);
403 #ifdef TLS_CUMULATE_ERRORS
404 tls_errflush(apparg
);
406 assert(errbuf_i
== 0);
411 /*****************************************************************************/
413 static int tls_init_done
= 0;
415 static int tls_init(void *apparg
)
420 SSL_load_error_strings();
421 if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) {
422 tls_errprintf(1, apparg
, "SSL_library_init failed.\n");
430 /*****************************************************************************/
432 static void tls_rand_seed_uniquely(void)
441 data
.time
= time(NULL
);
442 data
.stack
= (void *)&data
;
444 RAND_seed((const void *)&data
, sizeof data
);
447 void tls_rand_seed(void)
450 struct utsname uname
;
459 data
.uname_1
= uname(&data
.uname
);
460 data
.uname_2
= errno
; /* Let's hope that uname fails randomly :-) */
463 data
.euid
= geteuid();
465 data
.egid
= getegid();
467 RAND_seed((const void *)&data
, sizeof data
);
468 tls_rand_seed_uniquely();
471 static int tls_rand_seeded_p
= 0;
473 #define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */
474 int tls_rand_seed_from_file(const char *filename
, size_t n
, void *apparg
)
477 * Seed OpenSSL's random number generator from file. Try to read n bytes
478 * if n > 0, whole file if n == 0.
483 if (tls_init(apparg
) == -1)
487 r
= RAND_load_file(filename
,
488 (n
> 0 && n
< LONG_MAX
) ? (long)n
: LONG_MAX
);
490 * r is the number of bytes filled into the random number generator,
491 * which are taken from "stat(filename, ...)" in addition to the file
494 assert(1 < my_MIN_SEED_BYTES
);
496 * We need to detect at least those cases when the file does not exist at
497 * all. With current versions of OpenSSL, this should do it:
500 n
= my_MIN_SEED_BYTES
;
502 tls_errprintf(1, apparg
,
503 "rand_seed_from_file: could not read %d bytes from %s.\n",
507 tls_rand_seeded_p
= 1;
512 void tls_rand_seed_from_memory(const void *buf
, size_t n
)
518 int chunk
= rest
< INT_MAX
? (int)rest
: INT_MAX
;
519 RAND_seed((const char *)buf
+ i
, chunk
);
522 tls_rand_seeded_p
= 1;
525 /*****************************************************************************/
527 struct tls_x509_name_string
{
532 tls_get_x509_subject_name_oneline(X509
*cert
,
533 struct tls_x509_name_string
*namestring
)
538 namestring
->str
[0] = '\0';
542 name
= X509_get_subject_name(cert
); /* does not increment any reference
545 assert(sizeof namestring
->str
>= 4); /* "?" or "...", plus 0 */
548 namestring
->str
[0] = '?';
549 namestring
->str
[1] = 0;
553 X509_NAME_oneline(name
, namestring
->str
, sizeof namestring
->str
);
554 len
= strlen(namestring
->str
);
555 assert(namestring
->str
[len
] == 0);
556 assert(len
< sizeof namestring
->str
);
558 if (len
+ 1 == sizeof namestring
->str
) {
560 * (Probably something was cut off.) Does not really work --
561 * X509_NAME_oneline truncates after name components, we cannot
562 * tell from the result whether anything is missing.
565 assert(namestring
->str
[len
] == 0);
566 namestring
->str
[--len
] = '.';
567 namestring
->str
[--len
] = '.';
568 namestring
->str
[--len
] = '.';
573 /*****************************************************************************/
575 /* to hinder OpenSSL from asking for passphrases */
576 static int no_passphrase_callback(char *buf
, int num
, int w
, void *arg
)
581 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
582 static int verify_dont_fail_cb(X509_STORE_CTX
*c
, void *unused_arg
)
584 static int verify_dont_fail_cb(X509_STORE_CTX
*c
)
589 i
= X509_verify_cert(c
); /* sets c->error */
590 #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
591 * certificates -- they could
592 * survive session reuse, but
593 * OpenSSL < 0.9.5-dev does not
594 * preserve their verify_result */
602 static DH
*tls_dhe1024
= NULL
; /* generating these takes a while, so do it
605 void tls_set_dhe1024(int i
, void *apparg
)
609 const char *seed
[] = { ";-) :-( :-) :-( ",
611 "Random String no. 12",
613 "hackers have even mo", /* from jargon file */
615 unsigned char seedbuf
[20];
619 i
%= sizeof seed
/ sizeof seed
[0];
620 assert(strlen(seed
[i
]) == 20);
621 memcpy(seedbuf
, seed
[i
], 20);
623 DSA_generate_parameters(1024, seedbuf
, 20, NULL
, NULL
, 0, NULL
);
625 /* random parameters (may take a while) */
627 DSA_generate_parameters(1024, NULL
, 0, NULL
, NULL
, 0, NULL
);
630 if (dsaparams
== NULL
) {
631 tls_openssl_errors("", "", NULL
, apparg
);
634 dhparams
= DSA_dup_DH(dsaparams
);
636 if (dhparams
== NULL
) {
637 tls_openssl_errors("", "", NULL
, apparg
);
640 if (tls_dhe1024
!= NULL
)
641 DH_free(tls_dhe1024
);
642 tls_dhe1024
= dhparams
;
645 struct tls_create_ctx_args
tls_create_ctx_defaultargs(void)
647 struct tls_create_ctx_args ret
;
650 ret
.certificate_file
= NULL
;
653 ret
.verify_depth
= -1;
654 ret
.fail_unless_verified
= 0;
660 SSL_CTX
*tls_create_ctx(struct tls_create_ctx_args a
, void *apparg
)
663 static long context_num
= 0;
665 const char *err_pref_1
= "", *err_pref_2
= "";
667 if (tls_init(apparg
) == -1)
671 SSL_CTX_new((a
.client_p
? SSLv23_client_method
:
672 SSLv23_server_method
) ());
677 SSL_CTX_set_default_passwd_cb(ret
, no_passphrase_callback
);
678 SSL_CTX_set_mode(ret
, SSL_MODE_ENABLE_PARTIAL_WRITE
);
680 if ((a
.certificate_file
!= NULL
) || (a
.key_file
!= NULL
)) {
681 if (a
.key_file
== NULL
) {
682 tls_errprintf(1, apparg
, "Need a key file.\n");
685 if (a
.certificate_file
== NULL
) {
686 tls_errprintf(1, apparg
, "Need a certificate chain file.\n");
690 if (!SSL_CTX_use_PrivateKey_file(ret
, a
.key_file
, SSL_FILETYPE_PEM
))
692 if (!tls_rand_seeded_p
) {
694 * particularly paranoid people may not like this -- so provide
695 * your own random seeding before calling this
697 if (tls_rand_seed_from_file(a
.key_file
, 0, apparg
) == -1)
700 if (!SSL_CTX_use_certificate_chain_file(ret
, a
.certificate_file
))
702 if (!SSL_CTX_check_private_key(ret
)) {
703 tls_errprintf(1, apparg
,
704 "Private key \"%s\" does not match certificate \"%s\".\n",
705 a
.key_file
, a
.certificate_file
);
710 if ((a
.ca_file
!= NULL
) || (a
.verify_depth
> 0)) {
712 r
= SSL_CTX_set_session_id_context(ret
, (const void *)&context_num
,
713 (unsigned int)sizeof context_num
);
717 SSL_CTX_set_verify(ret
,
718 SSL_VERIFY_PEER
| (a
.fail_unless_verified
?
719 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
721 if (!a
.fail_unless_verified
)
722 SSL_CTX_set_cert_verify_callback(ret
, verify_dont_fail_cb
, NULL
);
724 if (a
.verify_depth
> 0)
725 SSL_CTX_set_verify_depth(ret
, a
.verify_depth
);
727 if (a
.ca_file
!= NULL
) {
728 /* does not report failure if file does not exist ... */
729 /* NULL argument means no CA-directory */
730 r
= SSL_CTX_load_verify_locations(ret
, a
.ca_file
, NULL
);
732 err_pref_1
= " while processing certificate file ";
733 err_pref_2
= a
.ca_file
;
739 * SSL_load_client_CA_file is a misnomer, it just creates a
742 SSL_CTX_set_client_CA_list(ret
,
743 SSL_load_client_CA_file
746 * SSL_CTX_set_client_CA_list does not have a return value;
747 * it does not really need one, but make sure (we really test
748 * if SSL_load_client_CA_file worked)
750 if (SSL_CTX_get_client_CA_list(ret
) == NULL
) {
751 tls_errprintf(1, apparg
,
752 "Could not set client CA list from \"%s\".\n",
761 if (tls_dhe1024
== NULL
) {
764 RAND_bytes((unsigned char *)&i
, sizeof i
);
766 * make sure that i is non-negative -- pick one of the provided
773 tls_set_dhe1024(i
, apparg
);
774 if (tls_dhe1024
== NULL
)
778 if (!SSL_CTX_set_tmp_dh(ret
, tls_dhe1024
))
781 /* avoid small subgroup attacks: */
782 SSL_CTX_set_options(ret
, SSL_OP_SINGLE_DH_USE
);
785 if (!a
.client_p
&& a
.export_p
) {
788 tmpkey
= RSA_generate_key(512, RSA_F4
, 0, NULL
);
791 if (!SSL_CTX_set_tmp_rsa(ret
, tmpkey
)) {
795 RSA_free(tmpkey
); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
802 if (!ERR_peek_error())
805 tls_openssl_errors(err_pref_1
, err_pref_2
, NULL
, apparg
);
812 /*****************************************************************************/
814 static int tls_socket_nonblocking(int fd
)
818 v
= fcntl(fd
, F_GETFL
, 0);
821 return 0; /* already shut down -- ignore */
824 r
= fcntl(fd
, F_SETFL
, v
| O_NONBLOCK
);
827 return 0; /* already shut down -- ignore */
833 static int max(int a
, int b
)
835 return a
> b
? a
: b
;
838 /* timeout, -1 means no timeout */
840 tls_sockets_select(int read_select_1
, int read_select_2
, int write_select_1
,
841 int write_select_2
, int seconds
)
844 fd_set reads
, writes
;
845 struct timeval timeout
;
846 struct timeval
*timeout_p
;
848 assert(read_select_1
>= -1 && read_select_2
>= -1 && write_select_1
>= -1
849 && write_select_2
>= -1);
850 assert(read_select_1
< FD_SETSIZE
&& read_select_2
< FD_SETSIZE
- 1
851 && write_select_1
< FD_SETSIZE
- 1
852 && write_select_2
< FD_SETSIZE
- 1);
855 max(max(read_select_1
, read_select_2
),
856 max(write_select_1
, write_select_2
));
862 for (n
= 0; n
< 4; ++n
) {
865 /* loop over all (i, w) in {0,1}x{0,1} */
868 if (i
== 0 && w
== 0)
870 else if (i
== 1 && w
== 0)
872 else if (i
== 0 && w
== 1)
875 assert(i
== 1 && w
== 1);
888 timeout
.tv_sec
= seconds
;
890 timeout_p
= &timeout
;
894 DEBUG_MSG2("select no.", ++tls_select_count
);
895 select(maxfd
+ 1, &reads
, &writes
, (fd_set
*) NULL
, timeout_p
);
899 /*****************************************************************************/
901 #define TUNNELBUFSIZE (16*1024)
903 char buf
[TUNNELBUFSIZE
];
908 static int tls_connect_attempt(SSL
*, int *write_select
, int *read_select
,
909 int *closed
, int *progress
,
910 const char **err_pref
);
912 static int tls_accept_attempt(SSL
*, int *write_select
, int *read_select
,
913 int *closed
, int *progress
,
914 const char **err_pref
);
916 static int tls_write_attempt(SSL
*, struct tunnelbuf
*, int *write_select
,
917 int *read_select
, int *closed
, int *progress
,
918 const char **err_pref
);
920 static int tls_read_attempt(SSL
*, struct tunnelbuf
*, int *write_select
,
921 int *read_select
, int *closed
, int *progress
,
922 const char **err_pref
);
924 static int write_attempt(int fd
, struct tunnelbuf
*, int *select
, int *closed
,
927 static int read_attempt(int fd
, struct tunnelbuf
*, int *select
, int *closed
,
930 static void write_info(SSL
*ssl
, int *info_fd
)
932 if (*info_fd
!= -1) {
935 struct tls_x509_name_string peer
;
936 char infobuf
[TLS_INFO_SIZE
];
939 DEBUG_MSG("write_info");
940 v
= SSL_get_verify_result(ssl
);
941 v_ok
= (v
== X509_V_OK
) ? 'A' : 'E'; /* Auth./Error */
945 peercert
= SSL_get_peer_certificate(ssl
);
946 tls_get_x509_subject_name_oneline(peercert
, &peer
);
947 if (peercert
!= NULL
)
950 if (peer
.str
[0] == '\0')
951 v_ok
= '0'; /* no cert at all */
952 else if (strchr(peer
.str
, '\n')) {
953 /* should not happen, but make sure */
954 *strchr(peer
.str
, '\n') = '\0';
956 r
= snprintf(infobuf
, sizeof infobuf
, "%c:%s\n%s\n", v_ok
,
957 X509_verify_cert_error_string(v
), peer
.str
);
958 DEBUG_MSG2("snprintf", r
);
959 if (r
== -1 || r
>= sizeof infobuf
)
960 r
= sizeof infobuf
- 1;
961 write(*info_fd
, infobuf
, r
);
967 /* tls_proxy expects that all fds are closed after return */
969 tls_proxy(int clear_fd
, int tls_fd
, int info_fd
, SSL_CTX
*ctx
, int client_p
)
971 struct tunnelbuf clear_to_tls
, tls_to_clear
;
974 int closed
, in_handshake
;
975 const char *err_pref_1
= "", *err_pref_2
= "";
976 const char *err_def
= NULL
;
978 assert(clear_fd
!= -1);
979 assert(tls_fd
!= -1);
980 assert(clear_fd
< FD_SETSIZE
);
981 assert(tls_fd
< FD_SETSIZE
);
982 /* info_fd may be -1 */
985 tls_rand_seed_uniquely();
987 tls_socket_nonblocking(clear_fd
);
988 DEBUG_MSG2("clear_fd", clear_fd
);
989 tls_socket_nonblocking(tls_fd
);
990 DEBUG_MSG2("tls_fd", tls_fd
);
995 DEBUG_MSG("SSL_new");
996 if (!SSL_set_fd(ssl
, tls_fd
))
998 rbio
= SSL_get_rbio(ssl
);
999 wbio
= SSL_get_wbio(ssl
); /* should be the same, but who cares */
1000 assert(rbio
!= NULL
);
1001 assert(wbio
!= NULL
);
1003 SSL_set_connect_state(ssl
);
1005 SSL_set_accept_state(ssl
);
1009 tls_to_clear
.len
= 0;
1010 tls_to_clear
.offset
= 0;
1011 clear_to_tls
.len
= 0;
1012 clear_to_tls
.offset
= 0;
1014 err_def
= "I/O error";
1017 * loop finishes as soon as we detect that one side closed; when all
1018 * (program and OS) buffers have enough space, the data from the last
1019 * succesful read in each direction is transferred before close
1022 int clear_read_select
= 0, clear_write_select
= 0,
1023 tls_read_select
= 0, tls_write_select
= 0, progress
= 0;
1025 unsigned long num_read
= BIO_number_read(rbio
),
1026 num_written
= BIO_number_written(wbio
);
1028 DEBUG_MSG2("loop iteration", ++tls_loop_count
);
1031 DEBUG_MSG("in_handshake");
1033 r
= tls_connect_attempt(ssl
, &tls_write_select
,
1034 &tls_read_select
, &closed
, &progress
,
1037 r
= tls_accept_attempt(ssl
, &tls_write_select
,
1038 &tls_read_select
, &closed
, &progress
,
1041 write_info(ssl
, &info_fd
);
1046 if (!SSL_in_init(ssl
)) {
1048 write_info(ssl
, &info_fd
);
1052 if (clear_to_tls
.len
!= 0 && !in_handshake
) {
1055 r
= tls_write_attempt(ssl
, &clear_to_tls
, &tls_write_select
,
1056 &tls_read_select
, &closed
, &progress
,
1062 tls_to_clear
.offset
= 0;
1063 tls_to_clear
.len
= 0;
1067 if (tls_to_clear
.len
!= 0) {
1070 r
= write_attempt(clear_fd
, &tls_to_clear
, &clear_write_select
,
1071 &closed
, &progress
);
1076 clear_to_tls
.offset
= 0;
1077 clear_to_tls
.len
= 0;
1082 if (clear_to_tls
.offset
+ clear_to_tls
.len
<
1083 sizeof clear_to_tls
.buf
) {
1084 r
= read_attempt(clear_fd
, &clear_to_tls
, &clear_read_select
,
1085 &closed
, &progress
);
1089 r
= SSL_shutdown(ssl
);
1090 DEBUG_MSG2("SSL_shutdown", r
);
1095 if (!closed
&& !in_handshake
) {
1096 if (tls_to_clear
.offset
+ tls_to_clear
.len
<
1097 sizeof tls_to_clear
.buf
) {
1098 r
= tls_read_attempt(ssl
, &tls_to_clear
, &tls_write_select
,
1099 &tls_read_select
, &closed
, &progress
,
1104 r
= SSL_shutdown(ssl
);
1105 DEBUG_MSG2("SSL_shutdown", r
);
1111 DEBUG_MSG("!progress?");
1112 if (num_read
!= BIO_number_read(rbio
)
1113 || num_written
!= BIO_number_written(wbio
))
1117 DEBUG_MSG("!progress");
1118 assert(clear_read_select
|| tls_read_select
1119 || clear_write_select
|| tls_write_select
);
1120 tls_sockets_select(clear_read_select
? clear_fd
: -1,
1121 tls_read_select
? tls_fd
: -1,
1122 clear_write_select
? clear_fd
: -1,
1123 tls_write_select
? tls_fd
: -1, -1);
1130 tls_openssl_errors(err_pref_1
, err_pref_2
, err_def
, tls_child_apparg
);
1136 tls_get_error(SSL
*ssl
, int r
, int *write_select
, int *read_select
,
1137 int *closed
, int *progress
)
1139 int err
= SSL_get_error(ssl
, r
);
1141 if (err
== SSL_ERROR_NONE
) {
1150 case SSL_ERROR_ZERO_RETURN
:
1156 case SSL_ERROR_WANT_WRITE
:
1160 case SSL_ERROR_WANT_READ
:
1169 tls_connect_attempt(SSL
*ssl
, int *write_select
, int *read_select
,
1170 int *closed
, int *progress
, const char **err_pref
)
1174 DEBUG_MSG("tls_connect_attempt");
1175 n
= SSL_connect(ssl
);
1176 DEBUG_MSG2("SSL_connect", n
);
1177 r
= tls_get_error(ssl
, n
, write_select
, read_select
, closed
, progress
);
1179 *err_pref
= " during SSL_connect";
1184 tls_accept_attempt(SSL
*ssl
, int *write_select
, int *read_select
, int *closed
,
1185 int *progress
, const char **err_pref
)
1189 DEBUG_MSG("tls_accept_attempt");
1190 n
= SSL_accept(ssl
);
1191 DEBUG_MSG2("SSL_accept", n
);
1192 r
= tls_get_error(ssl
, n
, write_select
, read_select
, closed
, progress
);
1194 *err_pref
= " during SSL_accept";
1199 tls_write_attempt(SSL
*ssl
, struct tunnelbuf
*buf
, int *write_select
,
1200 int *read_select
, int *closed
, int *progress
,
1201 const char **err_pref
)
1205 DEBUG_MSG("tls_write_attempt");
1206 n
= SSL_write(ssl
, buf
->buf
+ buf
->offset
, buf
->len
);
1207 DEBUG_MSG2("SSL_write", n
);
1208 r
= tls_get_error(ssl
, n
, write_select
, read_select
, closed
, progress
);
1211 assert(buf
->len
>= 0);
1218 *err_pref
= " during SSL_write";
1223 tls_read_attempt(SSL
*ssl
, struct tunnelbuf
*buf
, int *write_select
,
1224 int *read_select
, int *closed
, int *progress
,
1225 const char **err_pref
)
1230 DEBUG_MSG("tls_read_attempt");
1231 total
= buf
->offset
+ buf
->len
;
1232 assert(total
< sizeof buf
->buf
);
1233 n
= SSL_read(ssl
, buf
->buf
+ total
, (sizeof buf
->buf
) - total
);
1234 DEBUG_MSG2("SSL_read", n
);
1235 r
= tls_get_error(ssl
, n
, write_select
, read_select
, closed
, progress
);
1238 assert(buf
->offset
+ buf
->len
<= sizeof buf
->buf
);
1241 *err_pref
= " during SSL_read";
1245 static int get_error(int r
, int *select
, int *closed
, int *progress
)
1254 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
) {
1257 } else if (errno
== EPIPE
) {
1266 static int write_attempt(int fd
, struct tunnelbuf
*buf
, int *select
,
1267 int *closed
, int *progress
)
1271 DEBUG_MSG("write_attempt");
1272 n
= write(fd
, buf
->buf
+ buf
->offset
, buf
->len
);
1273 DEBUG_MSG2("write", n
);
1274 r
= get_error(n
, select
, closed
, progress
);
1277 assert(buf
->len
>= 0);
1284 tls_errprintf(1, tls_child_apparg
, "write error: %s\n",
1290 read_attempt(int fd
, struct tunnelbuf
*buf
, int *select
, int *closed
,
1296 DEBUG_MSG("read_attempt");
1297 total
= buf
->offset
+ buf
->len
;
1298 assert(total
< sizeof buf
->buf
);
1299 n
= read(fd
, buf
->buf
+ total
, (sizeof buf
->buf
) - total
);
1300 DEBUG_MSG2("read", n
);
1301 r
= get_error(n
, select
, closed
, progress
);
1304 assert(buf
->offset
+ buf
->len
<= sizeof buf
->buf
);
1307 tls_errprintf(1, tls_child_apparg
, "read error: %s\n",