1 /* source: xio-openssl.c */
2 /* Copyright Gerhard Rieger and contributors (see file CHANGES) */
3 /* Published under the GNU General Public License V.2, see file COPYING */
4 
5 /* this file contains the implementation of the openssl addresses */
6 
7 #include "xiosysincludes.h"
8 #if WITH_OPENSSL	/* make this address configure dependend */
9 #include <openssl/conf.h>
10 #include <openssl/x509v3.h>
11 
12 #include "xioopen.h"
13 
14 #include "xio-fd.h"
15 #include "xio-socket.h"	/* _xioopen_connect() */
16 #include "xio-listen.h"
17 #include "xio-udp.h"
18 #include "xio-ipapp.h"
19 #include "xio-ip6.h"
20 
21 #include "xio-openssl.h"
22 
23 /* the openssl library requires a file descriptor for external communications.
24    so our best effort is to provide any possible kind of un*x file descriptor
25    (not only tcp, but also pipes, stdin, files...)
26    for tcp we want to provide support for socks and proxy.
27    read and write functions must use the openssl crypt versions.
28    but currently only plain tcp4 is implemented.
29 */
30 
31 /* Linux: "man 3 ssl" */
32 
33 /* generate a simple openssl server for testing:
34    1) generate a private key
35    openssl genrsa -out server.key 1024
36    2) generate a self signed cert
37    openssl req -new -key server.key -x509 -days 3653 -out server.crt
38       enter fields...
39    3) generate the pem file
40    cat server.key server.crt >server.pem
41    openssl s_server  (listens on 4433/tcp)
42  */
43 
44 /* static declaration of ssl's open function */
45 static int xioopen_openssl_connect(int argc, const char *argv[], struct opt *opts,
46 				   int xioflags, xiofile_t *fd, unsigned groups,
47 			   int dummy1, int dummy2, int dummy3);
48 
49 /* static declaration of ssl's open function */
50 static int xioopen_openssl_listen(int argc, const char *argv[], struct opt *opts,
51 				  int xioflags, xiofile_t *fd, unsigned groups,
52 			   int dummy1, int dummy2, int dummy3);
53 static int openssl_SSL_ERROR_SSL(int level, const char *funcname);
54 static int openssl_handle_peer_certificate(struct single *xfd,
55 					   const char *peername,
56 					   bool opt_ver,
57 					   int level);
58 static int xioSSL_set_fd(struct single *xfd, int level);
59 static int xioSSL_connect(struct single *xfd, const char *opt_commonname, bool opt_ver, int level);
60 static int openssl_delete_cert_info(void);
61 
62 
63 /* description record for ssl connect */
64 const struct addrdesc xioaddr_openssl = {
65    "openssl",	/* keyword for selecting this address type in xioopen calls
66 		   (canonical or main name) */
67    3,		/* data flow directions this address supports on API layer:
68 		   1..read, 2..write, 3..both */
69    xioopen_openssl_connect,	/* a function pointer used to "open" these addresses.*/
70    GROUP_FD|GROUP_SOCKET|GROUP_SOCK_IP4|GROUP_SOCK_IP6|GROUP_IP_TCP|GROUP_CHILD|GROUP_OPENSSL|GROUP_RETRY,	/* bitwise OR of address groups this address belongs to.
71 		   You might have to specify a new group in xioopts.h */
72    0,		/* an integer passed to xioopen_openssl; makes it possible to
73 		   use the xioopen_openssl_connect function for slightly different
74 		   address types. */
75    0,		/* like previous argument */
76    0		/* like previous arguments, but pointer type.
77 		   No trailing comma or semicolon! */
78    HELP(":<host>:<port>")	/* a text displayed from xio help function.
79 			   No trailing comma or semicolon!
80 			   only generates this text if WITH_HELP is != 0 */
81 } ;
82 
83 #if WITH_LISTEN
84 /* description record for ssl listen */
85 const struct addrdesc xioaddr_openssl_listen = {
86    "openssl-listen",	/* keyword for selecting this address type in xioopen calls
87 		   (canonical or main name) */
88    3,		/* data flow directions this address supports on API layer:
89 		   1..read, 2..write, 3..both */
90    xioopen_openssl_listen,	/* a function pointer used to "open" these addresses.*/
91    GROUP_FD|GROUP_SOCKET|GROUP_SOCK_IP4|GROUP_SOCK_IP6|GROUP_IP_TCP|GROUP_LISTEN|GROUP_CHILD|GROUP_RANGE|GROUP_OPENSSL|GROUP_RETRY,	/* bitwise OR of address groups this address belongs to.
92 		   You might have to specify a new group in xioopts.h */
93    0,		/* an integer passed to xioopen_openssl_listen; makes it possible to
94 		   use the xioopen_openssl_listen function for slightly different
95 		   address types. */
96    0,		/* like previous argument */
97    0		/* like previous arguments, but pointer type.
98 		   No trailing comma or semicolon! */
99    HELP(":<port>")	/* a text displayed from xio help function.
100 			   No trailing comma or semicolon!
101 			   only generates this text if WITH_HELP is != 0 */
102 } ;
103 #endif /* WITH_LISTEN */
104 
105 const struct addrdesc xioaddr_openssl_dtls_client = { "openssl-dtls-client", 3, xioopen_openssl_connect, GROUP_FD|GROUP_SOCKET|GROUP_SOCK_IP4|GROUP_SOCK_IP6|GROUP_IP_UDP|GROUP_CHILD|GROUP_OPENSSL|GROUP_RETRY, 1, 0, 0  HELP(":<host>:<port>") } ;
106 #if WITH_LISTEN
107 const struct addrdesc xioaddr_openssl_dtls_server = { "openssl-dtls-server", 3, xioopen_openssl_listen, GROUP_FD|GROUP_SOCKET|GROUP_SOCK_IP4|GROUP_SOCK_IP6|GROUP_IP_UDP|GROUP_LISTEN|GROUP_CHILD|GROUP_RANGE|GROUP_OPENSSL|GROUP_RETRY, 1, 0, 0  HELP(":<port>") } ;
108 #endif
109 
110 /* both client and server */
111 const struct optdesc opt_openssl_cipherlist = { "openssl-cipherlist", "ciphers", OPT_OPENSSL_CIPHERLIST, GROUP_OPENSSL, PH_SPEC, TYPE_STRING, OFUNC_SPEC };
112 #if WITH_OPENSSL_METHOD
113 const struct optdesc opt_openssl_method     = { "openssl-method",     "method",  OPT_OPENSSL_METHOD,     GROUP_OPENSSL, PH_SPEC, TYPE_STRING, OFUNC_SPEC };
114 #endif
115 #if HAVE_SSL_CTX_set_min_proto_version || defined(SSL_CTX_set_min_proto_version)
116 const struct optdesc opt_openssl_min_proto_version = { "openssl-min-proto-version", "min-version", OPT_OPENSSL_MIN_PROTO_VERSION, GROUP_OPENSSL, PH_INIT, TYPE_STRING, OFUNC_OFFSET, XIO_OFFSETOF(para.openssl.min_proto_version) };
117 #endif
118 #if HAVE_SSL_CTX_set_max_proto_version || defined(SSL_CTX_set_max_proto_version)
119 const struct optdesc opt_openssl_max_proto_version = { "openssl-max-proto-version", "max-version", OPT_OPENSSL_MAX_PROTO_VERSION, GROUP_OPENSSL, PH_INIT, TYPE_STRING, OFUNC_OFFSET, XIO_OFFSETOF(para.openssl.max_proto_version) };
120 #endif
121 const struct optdesc opt_openssl_verify     = { "openssl-verify",     "verify",  OPT_OPENSSL_VERIFY,     GROUP_OPENSSL, PH_SPEC, TYPE_BOOL,   OFUNC_SPEC };
122 const struct optdesc opt_openssl_certificate = { "openssl-certificate", "cert",  OPT_OPENSSL_CERTIFICATE, GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
123 const struct optdesc opt_openssl_key         = { "openssl-key",         "key",   OPT_OPENSSL_KEY,         GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
124 const struct optdesc opt_openssl_dhparam     = { "openssl-dhparam",     "dh",    OPT_OPENSSL_DHPARAM,     GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
125 const struct optdesc opt_openssl_cafile      = { "openssl-cafile",     "cafile", OPT_OPENSSL_CAFILE,      GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
126 const struct optdesc opt_openssl_capath      = { "openssl-capath",     "capath", OPT_OPENSSL_CAPATH,      GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
127 const struct optdesc opt_openssl_egd         = { "openssl-egd",        "egd",    OPT_OPENSSL_EGD,         GROUP_OPENSSL, PH_SPEC, TYPE_FILENAME, OFUNC_SPEC };
128 const struct optdesc opt_openssl_pseudo      = { "openssl-pseudo",     "pseudo", OPT_OPENSSL_PSEUDO,      GROUP_OPENSSL, PH_SPEC, TYPE_BOOL,     OFUNC_SPEC };
129 #if OPENSSL_VERSION_NUMBER >= 0x00908000L && !defined(OPENSSL_NO_COMP)
130 const struct optdesc opt_openssl_compress    = { "openssl-compress",   "compress", OPT_OPENSSL_COMPRESS,  GROUP_OPENSSL, PH_SPEC, TYPE_STRING,   OFUNC_SPEC };
131 #endif
132 #if WITH_FIPS
133 const struct optdesc opt_openssl_fips        = { "openssl-fips",       "fips",   OPT_OPENSSL_FIPS,        GROUP_OPENSSL, PH_SPEC, TYPE_BOOL,     OFUNC_SPEC };
134 #endif
135 const struct optdesc opt_openssl_commonname  = { "openssl-commonname", "cn",     OPT_OPENSSL_COMMONNAME,  GROUP_OPENSSL, PH_SPEC, TYPE_STRING,   OFUNC_SPEC };
136 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
137 const struct optdesc opt_openssl_no_sni      = { "openssl-no-sni",    "nosni",   OPT_OPENSSL_NO_SNI,      GROUP_OPENSSL, PH_SPEC, TYPE_BOOL,     OFUNC_SPEC };
138 const struct optdesc opt_openssl_snihost     = { "openssl-snihost",   "snihost", OPT_OPENSSL_SNIHOST,     GROUP_OPENSSL, PH_SPEC, TYPE_STRING,   OFUNC_SPEC };
139 #endif
140 
141 
142 /* If FIPS is compiled in, we need to track if the user asked for FIPS mode.
143  * On forks, the FIPS mode must be reset by a disable, then enable since
144  * FIPS tracks the process ID that initializes things.
145  * If FIPS is not compiled in, no tracking variable is needed
146  * and we make the reset code compile out.  This keeps the
147  * rest of the code below free of FIPS related #ifs
148  */
149 #if WITH_FIPS
150 static bool xio_openssl_fips = false;
xio_reset_fips_mode(void)151 int xio_reset_fips_mode(void) {
152    if (xio_openssl_fips) {
153       if(!sycFIPS_mode_set(0) || !sycFIPS_mode_set(1)) {
154 	 ERR_load_crypto_strings();
155 	 ERR_print_errors(BIO_new_fp(stderr,BIO_NOCLOSE));
156 	 Error("Failed to reset OpenSSL FIPS mode");
157 	 xio_openssl_fips = false;
158          return -1;
159       }
160    }
161    return 0;
162 }
163 #else
164 #define xio_reset_fips_mode() 0
165 #endif
166 
openssl_conn_loginfo(SSL * ssl)167 static void openssl_conn_loginfo(SSL *ssl) {
168    const char *string;
169 
170    string = SSL_get_cipher_version(ssl);
171    Notice1("SSL proto version used: %s", string);
172    xiosetenv("OPENSSL_PROTO_VERSION", string, 1, NULL);
173 
174    string = SSL_get_cipher(ssl);
175    Notice1("SSL connection using %s", string);
176    xiosetenv("OPENSSL_CIPHER", string, 1, NULL);
177 
178 #if OPENSSL_VERSION_NUMBER >= 0x00908000L && !defined(OPENSSL_NO_COMP)
179    {
180       const COMP_METHOD *comp, *expansion;
181 
182       comp = sycSSL_get_current_compression(ssl);
183       expansion = sycSSL_get_current_expansion(ssl);
184 
185       Notice1("SSL connection compression \"%s\"",
186               comp?sycSSL_COMP_get_name(comp):"none");
187       Notice1("SSL connection expansion \"%s\"",
188               expansion?sycSSL_COMP_get_name(expansion):"none");
189    }
190 #endif
191 }
192 
193 /* the open function for OpenSSL client */
194 static int
xioopen_openssl_connect(int argc,const char * argv[],struct opt * opts,int xioflags,xiofile_t * xxfd,unsigned groups,int protogrp,int dummy2,int dummy3)195    xioopen_openssl_connect(int argc,
196 		   const char *argv[],	/* the arguments in the address string */
197 		   struct opt *opts,
198 		   int xioflags,	/* is the open meant for reading (0),
199 				   writing (1), or both (2) ? */
200 		   xiofile_t *xxfd,	/* a xio file descriptor structure,
201 				   already allocated */
202 		   unsigned groups,	/* the matching address groups... */
203 		   int protogrp,	/* first transparent integer value from
204 				   addr_openssl */
205 		   int dummy2,	/* second transparent integer value from
206 				   addr_openssl */
207 		   int dummy3)	/* transparent pointer value from
208 					   addr_openssl */
209 {
210    struct single *xfd = &xxfd->stream;
211    struct opt *opts0 = NULL;
212    const char *hostname, *portname;
213    int pf = PF_UNSPEC;
214    bool use_dtls = (protogrp != 0);
215    int socktype = SOCK_STREAM;
216    int ipproto = IPPROTO_TCP;
217    bool dofork = false;
218    union sockaddr_union us_sa,  *us = &us_sa;
219    union sockaddr_union them_sa, *them = &them_sa;
220    socklen_t uslen = sizeof(us_sa);
221    socklen_t themlen = sizeof(them_sa);
222    bool needbind = false;
223    bool lowport = false;
224    int level;
225    SSL_CTX* ctx;
226    bool opt_ver = true;	/* verify peer certificate */
227    char *opt_cert = NULL;	/* file name of client certificate */
228    const char *opt_commonname = NULL;	/* for checking peer certificate */
229    bool        opt_no_sni;
230    const char *opt_snihost = NULL;	/* for SNI host */
231    int result;
232 
233    if (!(xioflags & XIO_MAYCONVERT)) {
234       Error("address with data processing not allowed here");
235       return STAT_NORETRY;
236    }
237    xfd->flags |= XIO_DOESCONVERT;
238 
239    if (argc != 3) {
240       Error1("%s: 2 parameters required", argv[0]);
241       return STAT_NORETRY;
242    }
243    hostname = argv[1];
244    portname = argv[2];
245    if (hostname[0] == '\0') {
246       /* we catch this explicitely because empty commonname (peername) disables
247 	 commonName check of peer certificate */
248       Error1("%s: empty host name", argv[0]);
249       return STAT_NORETRY;
250    }
251 
252    xfd->howtoend = END_SHUTDOWN;
253    if (applyopts_single(xfd, opts, PH_INIT) < 0)  return -1;
254    applyopts(-1, opts, PH_INIT);
255 
256    retropt_bool(opts, OPT_FORK, &dofork);
257 
258    retropt_string(opts, OPT_OPENSSL_CERTIFICATE, &opt_cert);
259    retropt_string(opts, OPT_OPENSSL_COMMONNAME, (char **)&opt_commonname);
260 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
261    retropt_bool(opts, OPT_OPENSSL_NO_SNI, &opt_no_sni);
262    retropt_string(opts, OPT_OPENSSL_SNIHOST, (char **)&opt_snihost);
263 #endif
264 
265    if (opt_commonname == NULL) {
266       opt_commonname = strdup(hostname);
267       if (opt_commonname == NULL) {
268 	 Error1("strdup("F_Zu"): out of memory", strlen(hostname)+1);
269       }
270    }
271 
272 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
273    if (opt_snihost == NULL) {
274       opt_snihost = strdup(opt_commonname);
275       if (opt_snihost == NULL) {
276 	 Error1("strdup("F_Zu"): out of memory", strlen(opt_commonname)+1);
277       }
278    }
279 #endif
280 
281    result =
282       _xioopen_openssl_prepare(opts, xfd, false, &opt_ver, opt_cert, &ctx, (bool *)&use_dtls);
283    if (result != STAT_OK)  return STAT_NORETRY;
284 
285    if (use_dtls) {
286       socktype = SOCK_DGRAM;
287       ipproto = IPPROTO_UDP;
288    }
289    retropt_int(opts, OPT_SO_TYPE,      &socktype);
290    retropt_int(opts, OPT_SO_PROTOTYPE, &ipproto);
291 
292    result =
293       _xioopen_ipapp_prepare(opts, &opts0, hostname, portname, &pf, ipproto,
294 			     xfd->para.socket.ip.res_opts[1],
295 			     xfd->para.socket.ip.res_opts[0],
296 			     them, &themlen, us, &uslen,
297 			     &needbind, &lowport, socktype);
298    if (result != STAT_OK)  return STAT_NORETRY;
299 
300    if (xioopts.logopt == 'm') {
301       Info("starting connect loop, switching to syslog");
302       diag_set('y', xioopts.syslogfac);  xioopts.logopt = 'y';
303    } else {
304       Info("starting connect loop");
305    }
306 
307    do {	/* loop over failed connect and SSL handshake attempts */
308 
309 #if WITH_RETRY
310       if (xfd->forever || xfd->retry) {
311 	 level = E_INFO;
312       } else
313 #endif /* WITH_RETRY */
314 	 level = E_ERROR;
315 
316       /* this cannot fork because we retrieved fork option above */
317       result =
318 	 _xioopen_connect(xfd,
319 			  needbind?us:NULL, uslen,
320 			  (struct sockaddr *)them, themlen,
321 			  opts, pf, socktype, ipproto, lowport, level);
322       switch (result) {
323       case STAT_OK: break;
324 #if WITH_RETRY
325       case STAT_RETRYLATER:
326       case STAT_RETRYNOW:
327 	 if (xfd->forever || xfd->retry) {
328 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
329 	    if (result == STAT_RETRYLATER) {
330 	       Nanosleep(&xfd->intervall, NULL);
331 	    }
332 	    --xfd->retry;
333 	    continue;
334 	 }
335 	 return STAT_NORETRY;
336 #endif /* WITH_RETRY */
337       default:
338 	 return result;
339       }
340 
341       /*! isn't this too early? */
342       if ((result = _xio_openlate(xfd, opts)) < 0) {
343 	 return result;
344       }
345 
346       result = _xioopen_openssl_connect(xfd, opt_ver, opt_commonname,
347 			opt_no_sni, opt_snihost, ctx, level);
348       switch (result) {
349       case STAT_OK: break;
350 #if WITH_RETRY
351       case STAT_RETRYLATER:
352       case STAT_RETRYNOW:
353 	 if (xfd->forever || xfd->retry) {
354 	    Close(xfd->fd);
355 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
356 	    if (result == STAT_RETRYLATER) {
357 	       Nanosleep(&xfd->intervall, NULL);
358 	    }
359 	    --xfd->retry;
360 	    continue;
361 	 }
362 #endif /* WITH_RETRY */
363       default: return STAT_NORETRY;
364       }
365 
366       if (dofork) {
367 	 xiosetchilddied();	/* set SIGCHLD handler */
368       }
369 
370 #if WITH_RETRY
371       if (dofork) {
372 	 pid_t pid;
373 	 int level = E_ERROR;
374 	 if (xfd->forever || xfd->retry) {
375 	    level = E_WARN;
376 	 }
377 	 while ((pid = xio_fork(false, level)) < 0) {
378 	    if (xfd->forever || --xfd->retry) {
379 	       Nanosleep(&xfd->intervall, NULL); continue;
380 	    }
381 	    return STAT_RETRYLATER;
382 	 }
383 
384 	 if (pid == 0) {	/* child process */
385 	    xfd->forever = false;  xfd->retry = 0;
386 	    break;
387 	 }
388 
389 	 /* parent process */
390 	 Close(xfd->fd);
391 	 sycSSL_free(xfd->para.openssl.ssl);
392 	 xfd->para.openssl.ssl = NULL;
393 	 /* with and without retry */
394 	 Nanosleep(&xfd->intervall, NULL);
395 	 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
396 	 continue;	/* with next socket() bind() connect() */
397       }
398 #endif /* WITH_RETRY */
399       break;
400    } while (true);	/* drop out on success */
401 
402    openssl_conn_loginfo(xfd->para.openssl.ssl);
403 
404    free((void *)opt_commonname);
405    free((void *)opt_snihost);
406 
407    /* fill in the fd structure */
408    return STAT_OK;
409 }
410 
411 
412 /* this function is typically called within the OpenSSL client fork/retry loop.
413    xfd must be of type DATA_OPENSSL, and its fd must be set with a valid file
414    descriptor. this function then performs all SSL related step to make a valid
415    SSL connection from an FD and a CTX. */
_xioopen_openssl_connect(struct single * xfd,bool opt_ver,const char * opt_commonname,bool no_sni,const char * snihost,SSL_CTX * ctx,int level)416 int _xioopen_openssl_connect(struct single *xfd,
417 			     bool opt_ver,
418 			     const char *opt_commonname,
419 			     bool no_sni,
420 			     const char *snihost,
421 			     SSL_CTX *ctx,
422 			     int level) {
423    SSL *ssl;
424    unsigned long err;
425    int result;
426 
427    /* create a SSL object */
428    if ((ssl = sycSSL_new(ctx)) == NULL) {
429       if (ERR_peek_error() == 0)  Msg(level, "SSL_new() failed");
430       while (err = ERR_get_error()) {
431 	 Msg1(level, "SSL_new(): %s", ERR_error_string(err, NULL));
432       }
433       /*Error("SSL_new()");*/
434       return STAT_RETRYLATER;
435    }
436    xfd->para.openssl.ssl = ssl;
437 
438    result = xioSSL_set_fd(xfd, level);
439    if (result != STAT_OK) {
440       sycSSL_free(xfd->para.openssl.ssl);
441       xfd->para.openssl.ssl = NULL;
442       return result;
443    }
444 
445 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
446    if (!no_sni) {
447       if (!SSL_set_tlsext_host_name(ssl, snihost)) {
448 	 Error1("Failed to set SNI host \"%s\"", snihost);
449 	 sycSSL_free(xfd->para.openssl.ssl);
450 	 xfd->para.openssl.ssl = NULL;
451 	 return STAT_NORETRY;
452       }
453    }
454 #endif
455 
456    result = xioSSL_connect(xfd, opt_commonname, opt_ver, level);
457    if (result != STAT_OK) {
458       sycSSL_free(xfd->para.openssl.ssl);
459       xfd->para.openssl.ssl = NULL;
460       return result;
461    }
462 
463    result = openssl_handle_peer_certificate(xfd, opt_commonname,
464 					    opt_ver, level);
465    if (result != STAT_OK) {
466       sycSSL_free(xfd->para.openssl.ssl);
467       xfd->para.openssl.ssl = NULL;
468       return result;
469    }
470 
471    return STAT_OK;
472 }
473 
474 
475 #if WITH_LISTEN
476 
477 static int
xioopen_openssl_listen(int argc,const char * argv[],struct opt * opts,int xioflags,xiofile_t * xxfd,unsigned groups,int protogrp,int dummy2,int dummy3)478    xioopen_openssl_listen(int argc,
479 		   const char *argv[],	/* the arguments in the address string */
480 		   struct opt *opts,
481 		   int xioflags,	/* is the open meant for reading (0),
482 				   writing (1), or both (2) ? */
483 		   xiofile_t *xxfd,	/* a xio file descriptor structure,
484 				   already allocated */
485 		   unsigned groups,	/* the matching address groups... */
486 		   int protogrp,	/* first transparent integer value from
487 				   addr_openssl */
488 		   int dummy2,	/* second transparent integer value from
489 				   addr_openssl */
490 		   int dummy3)	/* transparent pointer value from
491 					   addr_openssl */
492 {
493    struct single *xfd = &xxfd->stream;
494    const char *portname;
495    struct opt *opts0 = NULL;
496    union sockaddr_union us_sa, *us = &us_sa;
497    socklen_t uslen = sizeof(us_sa);
498    int pf;
499    bool use_dtls = (protogrp != 0);
500    int socktype = SOCK_STREAM;
501    int ipproto = IPPROTO_TCP;
502    /*! lowport? */
503    int level;
504    SSL_CTX* ctx;
505    bool opt_ver = true;	/* verify peer certificate - changed with 1.6.0 */
506    char *opt_cert = NULL;	/* file name of server certificate */
507    const char *opt_commonname = NULL;	/* for checking peer certificate */
508    int result;
509 
510    if (!(xioflags & XIO_MAYCONVERT)) {
511       Error("address with data processing not allowed here");
512       return STAT_NORETRY;
513    }
514    xfd->flags |= XIO_DOESCONVERT;
515 
516    if (argc != 2) {
517       Error1("%s: 1 parameter required", argv[0]);
518       return STAT_NORETRY;
519    }
520 
521 #if WITH_IP4 && WITH_IP6
522    pf = xioopts.default_ip=='6'?PF_INET6:PF_INET;
523 #elif WITH_IP6
524    pf = PF_INET6;
525 #else
526    pf = PF_INET;
527 #endif
528 
529    portname = argv[1];
530 
531    xfd->howtoend = END_SHUTDOWN;
532    if (applyopts_single(xfd, opts, PH_INIT) < 0)  return -1;
533    applyopts(-1, opts, PH_INIT);
534 
535    retropt_string(opts, OPT_OPENSSL_CERTIFICATE, &opt_cert);
536    if (opt_cert == NULL) {
537       Warn("no certificate given; consider option \"cert\"");
538    }
539 
540    retropt_string(opts, OPT_OPENSSL_COMMONNAME, (char **)&opt_commonname);
541 
542    applyopts(-1, opts, PH_EARLY);
543 
544    result =
545       _xioopen_openssl_prepare(opts, xfd, true, &opt_ver, opt_cert, &ctx, &use_dtls);
546    if (result != STAT_OK)  return STAT_NORETRY;
547 
548    if (use_dtls) {
549       socktype = SOCK_DGRAM;
550       ipproto = IPPROTO_UDP;
551    }
552    retropt_int(opts, OPT_SO_TYPE,      &socktype);
553    retropt_int(opts, OPT_SO_PROTOTYPE, &ipproto);
554 
555    if (_xioopen_ipapp_listen_prepare(opts, &opts0, portname, &pf, ipproto,
556 				     xfd->para.socket.ip.res_opts[1],
557 				     xfd->para.socket.ip.res_opts[0],
558 				     us, &uslen, socktype)
559        != STAT_OK) {
560       return STAT_NORETRY;
561    }
562 
563    xfd->dtype = XIODATA_OPENSSL;
564 
565    while (true) {	/* loop over failed attempts */
566 
567 #if WITH_RETRY
568       if (xfd->forever || xfd->retry) {
569 	 level = E_INFO;
570       } else
571 #endif /* WITH_RETRY */
572 	 level = E_ERROR;
573 
574       /* this can fork() for us; it only returns on error or on
575 	 successful establishment of connection */
576       if (ipproto == IPPROTO_TCP) {
577 	 result = _xioopen_listen(xfd, xioflags,
578 			       (struct sockaddr *)us, uslen,
579 			       opts, pf, socktype, ipproto,
580 #if WITH_RETRY
581 			       (xfd->retry||xfd->forever)?E_INFO:E_ERROR
582 #else
583 			       E_ERROR
584 #endif /* WITH_RETRY */
585 			       );
586 #if WITH_UDP
587       } else {
588 	 result = _xioopen_ipdgram_listen(xfd, xioflags,
589 		us, uslen, opts, pf, socktype, ipproto);
590 #endif /* WITH_UDP */
591       }
592 	 /*! not sure if we should try again on retry/forever */
593       switch (result) {
594       case STAT_OK: break;
595 #if WITH_RETRY
596       case STAT_RETRYLATER:
597       case STAT_RETRYNOW:
598 	 if (xfd->forever || xfd->retry) {
599 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
600 	    if (result == STAT_RETRYLATER) {
601 	       Nanosleep(&xfd->intervall, NULL);
602 	    }
603 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
604 	    --xfd->retry;
605 	    continue;
606 	 }
607 	 return STAT_NORETRY;
608 #endif /* WITH_RETRY */
609       default:
610 	 return result;
611       }
612 
613       result = _xioopen_openssl_listen(xfd, opt_ver, opt_commonname, ctx, level);
614       switch (result) {
615       case STAT_OK: break;
616 #if WITH_RETRY
617       case STAT_RETRYLATER:
618       case STAT_RETRYNOW:
619 	 if (xfd->forever || xfd->retry) {
620 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
621 	    if (result == STAT_RETRYLATER) {
622 	       Nanosleep(&xfd->intervall, NULL);
623 	    }
624 	    dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
625 	    --xfd->retry;
626 	    continue;
627 	 }
628 	 return STAT_NORETRY;
629 #endif /* WITH_RETRY */
630       default:
631 	 return result;
632       }
633 
634       openssl_conn_loginfo(xfd->para.openssl.ssl);
635       break;
636 
637    }	/* drop out on success */
638 
639    /* fill in the fd structure */
640 
641    return STAT_OK;
642 }
643 
644 
_xioopen_openssl_listen(struct single * xfd,bool opt_ver,const char * opt_commonname,SSL_CTX * ctx,int level)645 int _xioopen_openssl_listen(struct single *xfd,
646 			     bool opt_ver,
647 			    const char *opt_commonname,
648 			     SSL_CTX *ctx,
649 			     int level) {
650    char error_string[120];
651    unsigned long err;
652    int errint, ret;
653 
654    /* create an SSL object */
655    if ((xfd->para.openssl.ssl = sycSSL_new(ctx)) == NULL) {
656       if (ERR_peek_error() == 0)  Msg(level, "SSL_new() failed");
657       while (err = ERR_get_error()) {
658 	 Msg1(level, "SSL_new(): %s", ERR_error_string(err, NULL));
659       }
660       /*Error("SSL_new()");*/
661       return STAT_NORETRY;
662    }
663 
664    /* assign the network connection to the SSL object */
665    if (sycSSL_set_fd(xfd->para.openssl.ssl, xfd->fd) <= 0) {
666       if (ERR_peek_error() == 0) Msg(level, "SSL_set_fd() failed");
667       while (err = ERR_get_error()) {
668 	 Msg2(level, "SSL_set_fd(, %d): %s",
669 	      xfd->fd, ERR_error_string(err, NULL));
670       }
671    }
672 
673 #if WITH_DEBUG
674    {
675       int i = 0;
676       const char *ciphers = NULL;
677       Debug("available ciphers:");
678       do {
679 	 ciphers = SSL_get_cipher_list(xfd->para.openssl.ssl, i);
680 	 if (ciphers == NULL)  break;
681 	 Debug2("CIPHERS pri=%d: %s", i, ciphers);
682 	 ++i;
683       } while (1);
684    }
685 #endif /* WITH_DEBUG */
686 
687    /* connect via SSL by performing handshake */
688    if ((ret = sycSSL_accept(xfd->para.openssl.ssl)) <= 0) {
689       /*if (ERR_peek_error() == 0) Msg(level, "SSL_accept() failed");*/
690       errint = SSL_get_error(xfd->para.openssl.ssl, ret);
691       switch (errint) {
692       case SSL_ERROR_NONE:
693 	 Msg(level, "ok"); break;
694       case SSL_ERROR_ZERO_RETURN:
695 	 Msg(level, "connection closed (wrong version number?)"); break;
696       case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE:
697       case SSL_ERROR_WANT_CONNECT:
698       case SSL_ERROR_WANT_X509_LOOKUP:
699 	 Msg(level, "nonblocking operation did not complete"); break;	/*!*/
700       case SSL_ERROR_SYSCALL:
701 	 if (ERR_peek_error() == 0) {
702 	    if (ret == 0) {
703 	       Msg(level, "SSL_accept(): socket closed by peer");
704 	    } else if (ret == -1) {
705 	       Msg1(level, "SSL_accept(): %s", strerror(errno));
706 	    }
707 	 } else {
708 	    Msg(level, "I/O error");	/*!*/
709 	    while (err = ERR_get_error()) {
710 	       ERR_error_string_n(err, error_string, sizeof(error_string));
711 	       Msg4(level, "SSL_accept(): %s / %s / %s / %s", error_string,
712 		    ERR_lib_error_string(err), ERR_func_error_string(err),
713 		    ERR_reason_error_string(err));
714 	    }
715 	    /* Msg1(level, "SSL_accept(): %s", ERR_error_string(e, buf));*/
716 	 }
717 	 break;
718       case SSL_ERROR_SSL:
719 	 /*ERR_print_errors_fp(stderr);*/
720 	 openssl_SSL_ERROR_SSL(level, "SSL_accept");
721 	 break;
722       default:
723 	 Msg(level, "unknown error");
724       }
725 
726       return STAT_RETRYLATER;
727    }
728 
729    if (openssl_handle_peer_certificate(xfd, opt_commonname, opt_ver, E_ERROR/*!*/) < 0) {
730       return STAT_NORETRY;
731    }
732 
733    return STAT_OK;
734 }
735 
736 #endif /* WITH_LISTEN */
737 
738 
739 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
740 /* In OpenSSL 0.9.7 compression methods could be added using
741  * SSL_COMP_add_compression_method(3), but the implemntation is not compatible
742  * with the standard (RFC3749).
743  */
openssl_setup_compression(SSL_CTX * ctx,char * method)744 static int openssl_setup_compression(SSL_CTX *ctx, char *method)
745 {
746    STACK_OF(SSL_COMP)* comp_methods;
747 
748    assert(method);
749 
750    /* Getting the stack of compression methods has the intended side-effect of
751     * initializing the SSL library's compression part.
752     */
753    comp_methods = SSL_COMP_get_compression_methods();
754    if (!comp_methods) {
755       Info("OpenSSL built without compression support");
756       return STAT_OK;
757    }
758 
759    if (strcasecmp(method, "auto") == 0) {
760       Info("Using default OpenSSL compression");
761       return STAT_OK;
762    }
763 
764    if (strcasecmp(method, "none") == 0) {
765       /* Disable compression */
766 #ifdef SSL_OP_NO_COMPRESSION
767       Info("Disabling OpenSSL compression");
768       SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
769 #else
770       /* SSL_OP_NO_COMPRESSION was only introduced in OpenSSL 0.9.9 (released
771        * as 1.0.0). Removing all compression methods is a work-around for
772        * earlier versions of OpenSSL, but it affects all SSL connections.
773        */
774       Info("Disabling OpenSSL compression globally");
775       sk_SSL_COMP_zero(comp_methods);
776 #endif
777       return STAT_OK;
778    }
779 
780    /* zlib compression in OpenSSL before version 0.9.8e-beta1 uses the libc's
781     * default malloc/free instead of the ones passed to OpenSSL. Should socat
782     * ever use custom malloc/free functions for OpenSSL, this must be taken
783     * into consideration. See OpenSSL bug #1468.
784     */
785 
786    Error1("openssl-compress=\"%s\": unknown compression method", method);
787    return STAT_NORETRY;
788 }
789 #endif
790 
791 
792 #if HAVE_CTX_SSL_set_min_proto_version || defined(SSL_CTX_set_min_proto_version) || \
793    HAVE_SSL_CTX_set_max_proto_version || defined(SSL_CTX_set_max_proto_version)
794 #define XIO_OPENSSL_VERSIONGROUP_TLS 1
795 #define XIO_OPENSSL_VERSIONGROUP_DTLS 2
796 
797 static struct wordent _xio_openssl_versions[] = {
798 #ifdef DTLS1_VERSION
799    { "DTLS1",		(void *)DTLS1_VERSION },
800    { "DTLS1.0",		(void *)DTLS1_VERSION },
801 #endif
802 #ifdef DTLS1_2_VERSION
803    { "DTLS1.2",		(void *)DTLS1_2_VERSION },
804 #endif
805 #ifdef DTLS1_VERSION
806    { "DTLSv1",		(void *)DTLS1_VERSION },
807    { "DTLSv1.0",	(void *)DTLS1_VERSION },
808 #endif
809 #ifdef DTLS1_2_VERSION
810    { "DTLSv1.2",	(void *)DTLS1_2_VERSION },
811 #endif
812 #ifdef SSL2_VERSION
813    { "SSL2",		(void *)SSL2_VERSION },
814 #endif
815 #ifdef SSL3_VERSION
816    { "SSL3",		(void *)SSL3_VERSION },
817 #endif
818 #ifdef SSL2_VERSION
819    { "SSLv2",		(void *)SSL2_VERSION },
820 #endif
821 #ifdef SSL3_VERSION
822    { "SSLv3",		(void *)SSL3_VERSION },
823 #endif
824 #ifdef TLS1_VERSION
825    { "TLS1",		(void *)TLS1_VERSION },
826    { "TLS1.0",		(void *)TLS1_VERSION },
827 #endif
828 #ifdef TLS1_1_VERSION
829    { "TLS1.1",		(void *)TLS1_1_VERSION },
830 #endif
831 #ifdef TLS1_2_VERSION
832    { "TLS1.2",		(void *)TLS1_2_VERSION },
833 #endif
834 #ifdef TLS1_3_VERSION
835    { "TLS1.3",		(void *)TLS1_3_VERSION },
836 #endif
837 #ifdef TLS1_VERSION
838    { "TLSv1",		(void *)TLS1_VERSION },
839    { "TLSv1.0",		(void *)TLS1_VERSION },
840 #endif
841 #ifdef TLS1_1_VERSION
842    { "TLSv1.1",		(void *)TLS1_1_VERSION },
843 #endif
844 #ifdef TLS1_2_VERSION
845    { "TLSv1.2",		(void *)TLS1_2_VERSION },
846 #endif
847 #ifdef TLS1_3_VERSION
848    { "TLSv1.3",		(void *)TLS1_3_VERSION },
849 #endif
850 } ;
851 
_xio_openssl_parse_version(const char * verstring,int vergroups)852 static int _xio_openssl_parse_version(const char *verstring, int vergroups) {
853    int sslver;
854    const struct wordent *we;
855    we = keyw(_xio_openssl_versions, verstring,
856 	     sizeof(_xio_openssl_versions)/sizeof(struct wordent));
857    if (we == 0) {
858       Error1("Unknown SSL/TLS version \"%s\"", verstring);
859       return -1;
860    }
861    sslver = (size_t)we->desc;
862    switch (sslver) {
863 #ifdef SSL2_VERSION
864    case SSL2_VERSION:
865 #endif
866 #ifdef SSL3_VERSION
867    case SSL3_VERSION:
868 #endif
869 #ifdef TLS1_VERSION
870    case TLS1_VERSION:
871 #endif
872 #ifdef TLS1_1_VERSION
873    case TLS1_1_VERSION:
874 #endif
875 #ifdef TLS1_2_VERSION
876    case TLS1_2_VERSION:
877 #endif
878 #ifdef TLS1_3_VERSION
879    case TLS1_3_VERSION:
880 #endif
881       if (!(vergroups & XIO_OPENSSL_VERSIONGROUP_TLS)) {
882 	 Error1("Wrong type of TLS/DTLS version \"%s\"", verstring);
883 	 return -1;
884       }
885 #ifdef DTLS1_VERSION
886    case DTLS1_VERSION:
887 #endif
888 #ifdef DTLS1_2_VERSION
889    case DTLS1_2_VERSION:
890 #endif
891       if (!(vergroups & XIO_OPENSSL_VERSIONGROUP_DTLS)) {
892 	 Error1("Wrong type of TLS/DTLS version \"%s\"", verstring);
893 	 return -1;
894       }
895       break;
896    }
897    return sslver;
898 }
899 #endif /* defined(SSL_CTX_set_min_proto_version) || defined(SSL_CTX_set_max_proto_version) */
900 
901 
902 int
_xioopen_openssl_prepare(struct opt * opts,struct single * xfd,bool server,bool * opt_ver,const char * opt_cert,SSL_CTX ** ctxp,bool * use_dtls)903    _xioopen_openssl_prepare(struct opt *opts,
904 			    struct single *xfd,/* a xio file descriptor
905 						  structure, already allocated
906 					       */
907 			    bool server,	/* SSL client: false */
908 			    bool *opt_ver,
909 			    const char *opt_cert,
910 			    SSL_CTX **ctxp,
911 			    bool *use_dtls)	/* checked,overwritten with true if DTLS-method */
912 {
913    SSL_CTX *ctx;
914    bool opt_fips = false;
915    const SSL_METHOD *method = NULL;
916    char *me_str = NULL;	/* method string */
917    char *ci_str = "HIGH:-NULL:-PSK:-aNULL";	/* cipher string */
918    char *opt_key  = NULL;	/* file name of client private key */
919    char *opt_dhparam = NULL;	/* file name of DH params */
920    char *opt_cafile = NULL;	/* certificate authority file */
921    char *opt_capath = NULL;	/* certificate authority directory */
922    char *opt_egd = NULL;	/* entropy gathering daemon socket path */
923 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
924    char *opt_compress = NULL;	/* compression method */
925 #endif
926    bool opt_pseudo = false;	/* use pseudo entropy if nothing else */
927    unsigned long err;
928    int result;
929 
930    //*ipproto = IPPROTO_TCP;
931 
932    xfd->dtype = XIODATA_OPENSSL;
933 
934    retropt_bool(opts, OPT_OPENSSL_FIPS, &opt_fips);
935    retropt_string(opts, OPT_OPENSSL_METHOD, &me_str);
936    retropt_string(opts, OPT_OPENSSL_CIPHERLIST, &ci_str);
937    retropt_bool(opts, OPT_OPENSSL_VERIFY, opt_ver);
938    retropt_string(opts, OPT_OPENSSL_CAFILE, &opt_cafile);
939    retropt_string(opts, OPT_OPENSSL_CAPATH, &opt_capath);
940    retropt_string(opts, OPT_OPENSSL_KEY, &opt_key);
941    retropt_string(opts, OPT_OPENSSL_DHPARAM, &opt_dhparam);
942    retropt_string(opts, OPT_OPENSSL_EGD, &opt_egd);
943    retropt_bool(opts,OPT_OPENSSL_PSEUDO, &opt_pseudo);
944 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
945    retropt_string(opts, OPT_OPENSSL_COMPRESS, &opt_compress);
946 #endif
947 #if WITH_FIPS
948    if (opt_fips) {
949       if (!sycFIPS_mode_set(1)) {
950 	 ERR_load_crypto_strings();
951 	 ERR_print_errors(BIO_new_fp(stderr,BIO_NOCLOSE));
952 	 Error("Failed to set FIPS mode");
953       } else {
954 	 xio_openssl_fips = true;
955       }
956    }
957 #endif
958 
959    openssl_delete_cert_info();
960 
961    /* OpenSSL preparation */
962 #if HAVE_OPENSSL_init_ssl
963    {
964       OPENSSL_INIT_SETTINGS *settings;
965       settings = OPENSSL_INIT_new();
966       sycOPENSSL_init_ssl(0, settings);
967    }
968 #else
969    sycSSL_library_init();
970    OpenSSL_add_all_algorithms();
971    OpenSSL_add_all_ciphers();
972    OpenSSL_add_all_digests();
973    sycSSL_load_error_strings();
974 #endif
975 
976    /*! actions_to_seed_PRNG();*/
977 
978    if (!server) {
979       if (me_str != NULL) {
980 	 if (false) {
981 	    ;	/* for canonical reasons */
982 #if HAVE_SSLv2_client_method
983 	 } else if (!strcasecmp(me_str, "SSL2")) {
984 	    method = sycSSLv2_client_method();
985 #endif
986 #if HAVE_SSLv3_client_method
987 	 } else if (!strcasecmp(me_str, "SSL3")) {
988 	    method = sycSSLv3_client_method();
989 #endif
990 #if HAVE_SSLv23_client_method
991 	 } else if (!strcasecmp(me_str, "SSL23")) {
992 	    method = sycSSLv23_client_method();
993 #endif
994 #if HAVE_TLSv1_client_method
995 	 } else if (!strcasecmp(me_str, "TLS1") || !strcasecmp(me_str, "TLS1.0")) {
996 	    method = sycTLSv1_client_method();
997 #endif
998 #if HAVE_TLSv1_1_client_method
999 	 } else if (!strcasecmp(me_str, "TLS1.1")) {
1000 	    method = sycTLSv1_1_client_method();
1001 #endif
1002 #if HAVE_TLSv1_2_client_method
1003 	 } else if (!strcasecmp(me_str, "TLS1.2")) {
1004 	    method = sycTLSv1_2_client_method();
1005 #endif
1006 #if HAVE_DTLSv1_client_method
1007 	 } else if (!strcasecmp(me_str, "DTLS1") || !strcasecmp(me_str, "DTLS1.0")) {
1008 	    method = sycDTLSv1_client_method();
1009 	    *use_dtls = true;
1010 #endif
1011 #if HAVE_DTLSv1_2_client_method
1012 	 } else if (!strcasecmp(me_str, "DTLS1.2")) {
1013 	    method = sycDTLSv1_2_client_method();
1014 	 *use_dtls = true;
1015 #endif
1016 	 } else {
1017 	    Error1("openssl-method=\"%s\": method unknown or not provided by library", me_str);
1018 	 }
1019       } else if (!*use_dtls) {
1020 #if   HAVE_TLS_client_method
1021 	 method = sycTLS_client_method();
1022 #elif HAVE_SSLv23_client_method
1023 	 method = sycSSLv23_client_method();
1024 #elif HAVE_TLSv1_2_client_method
1025 	 method = sycTLSv1_2_client_method();
1026 #elif HAVE_TLSv1_1_client_method
1027 	 method = sycTLSv1_1_client_method();
1028 #elif HAVE_TLSv1_client_method
1029 	 method = sycTLSv1_client_method();
1030 #elif HAVE_SSLv3_client_method
1031 	 method = sycSSLv3_client_method();
1032 #elif HAVE_SSLv2_client_method
1033 	 method = sycSSLv2_client_method();
1034 #else
1035 #        error "OpenSSL does not seem to provide SSL/TLS client methods"
1036 #endif
1037       } else {
1038 #if   HAVE_DTLS_client_method
1039 	 method = sycDTLS_client_method();
1040 #elif HAVE_DTLSv1_2_client_method
1041 	 method = sycDTLSv1_2_client_method();
1042 #elif HAVE_DTLSv1_client_method
1043 	 method = sycDTLSv1_client_method();
1044 #else
1045 #        error "OpenSSL does not seem to provide DTLS client methods"
1046 #endif
1047 	 *use_dtls = true;
1048       }
1049    } else /* server */ {
1050       if (me_str != 0) {
1051 	 if (false) {
1052 	    ;	/* for canonical reasons */
1053 #if HAVE_SSLv2_server_method
1054 	 } else if (!strcasecmp(me_str, "SSL2")) {
1055 	    method = sycSSLv2_server_method();
1056 #endif
1057 #if HAVE_SSLv3_server_method
1058 	 } else if (!strcasecmp(me_str, "SSL3")) {
1059 	    method = sycSSLv3_server_method();
1060 #endif
1061 #if HAVE_SSLv23_server_method
1062 	 } else if (!strcasecmp(me_str, "SSL23")) {
1063 	    method = sycSSLv23_server_method();
1064 #endif
1065 #if HAVE_TLSv1_server_method
1066 	 } else if (!strcasecmp(me_str, "TLS1") || !strcasecmp(me_str, "TLS1.0")) {
1067 	    method = sycTLSv1_server_method();
1068 #endif
1069 #if HAVE_TLSv1_1_server_method
1070 	 } else if (!strcasecmp(me_str, "TLS1.1")) {
1071 	    method = sycTLSv1_1_server_method();
1072 #endif
1073 #if HAVE_TLSv1_2_server_method
1074 	 } else if (!strcasecmp(me_str, "TLS1.2")) {
1075 	    method = sycTLSv1_2_server_method();
1076 #endif
1077 #if HAVE_DTLSv1_server_method
1078 	 } else if (!strcasecmp(me_str, "DTLS1") || !strcasecmp(me_str, "DTLS1.0")) {
1079 	    method = sycDTLSv1_server_method();
1080 	    *use_dtls = true;
1081 #endif
1082 #if HAVE_DTLSv1_2_server_method
1083 	 } else if (!strcasecmp(me_str, "DTLS1.2")) {
1084 	    method = sycDTLSv1_2_server_method();
1085 	 *use_dtls = true;
1086 #endif
1087 	 } else {
1088 	    Error1("openssl-method=\"%s\": method unknown or not provided by library", me_str);
1089 	 }
1090       } else if (!*use_dtls) {
1091 #if   HAVE_TLS_server_method
1092 	 method = sycTLS_server_method();
1093 #elif HAVE_SSLv23_server_method
1094 	 method = sycSSLv23_server_method();
1095 #elif HAVE_TLSv1_2_server_method
1096 	 method = sycTLSv1_2_server_method();
1097 #elif HAVE_TLSv1_1_server_method
1098 	 method = sycTLSv1_1_server_method();
1099 #elif HAVE_TLSv1_server_method
1100 	 method = sycTLSv1_server_method();
1101 #elif HAVE_SSLv3_server_method
1102 	 method = sycSSLv3_server_method();
1103 #elif HAVE_SSLv2_server_method
1104 	 method = sycSSLv2_server_method();
1105 #else
1106 #        error "OpenSSL does not seem to provide SSL/TLS server methods"
1107 #endif
1108       } else {
1109 #if   HAVE_DTLS_server_method
1110 	 method = sycDTLS_server_method();
1111 #elif HAVE_DTLSv1_2_server_method
1112 	 method = sycDTLSv1_2_server_method();
1113 #elif HAVE_DTLSv1_server_method
1114 	 method = sycDTLSv1_server_method();
1115 #else
1116 #        error "OpenSSL does not seem to provide DTLS server methods"
1117 #endif
1118 	 *use_dtls = true;
1119       }
1120    }
1121 
1122    if (opt_egd) {
1123 #if !defined(OPENSSL_NO_EGD) && HAVE_RAND_egd
1124       sycRAND_egd(opt_egd);
1125 #else
1126       Debug("RAND_egd() is not available by OpenSSL");
1127 #endif
1128    }
1129 
1130    if (opt_pseudo) {
1131       long int randdata;
1132       /* initialize libc random from actual microseconds */
1133       struct timeval tv;
1134       struct timezone tz;
1135       tz.tz_minuteswest = 0;
1136       tz.tz_dsttime = 0;
1137       if ((result = Gettimeofday(&tv, &tz)) < 0) {
1138 	 Warn2("gettimeofday(%p, {0,0}): %s", &tv, strerror(errno));
1139       }
1140       srandom(tv.tv_sec*1000000+tv.tv_usec);
1141 
1142       while (!RAND_status()) {
1143 	 randdata = random();
1144 	 Debug2("RAND_seed(0x{%lx}, "F_Zu")",
1145 		randdata, sizeof(randdata));
1146 	 RAND_seed(&randdata, sizeof(randdata));
1147       }
1148    }
1149 
1150    if ((ctx = sycSSL_CTX_new(method)) == NULL) {
1151       if (ERR_peek_error() == 0) Error("SSL_CTX_new()");
1152       while (err = ERR_get_error()) {
1153 	 Error1("SSL_CTX_new(): %s", ERR_error_string(err, NULL));
1154       }
1155 
1156       /*ERR_clear_error;*/
1157       return STAT_RETRYLATER;
1158    }
1159    xfd->para.openssl.ctx = ctx;
1160    *ctxp = ctx;
1161 
1162 #if HAVE_SSL_CTX_set_min_proto_version || defined(SSL_CTX_set_min_proto_version)
1163    if (xfd->para.openssl.min_proto_version != NULL) {
1164       int sslver, rc;
1165       sslver = _xio_openssl_parse_version(xfd->para.openssl.min_proto_version,
1166 					  XIO_OPENSSL_VERSIONGROUP_TLS|XIO_OPENSSL_VERSIONGROUP_DTLS);
1167       if (sslver < 0)
1168 	 return STAT_NORETRY;
1169       if ((rc = SSL_CTX_set_min_proto_version(ctx, sslver)) <= 0) {
1170 	 Debug1("version: %ld", SSL_CTX_get_min_proto_version(ctx));
1171 	 Error3("_xioopen_openssl_prepare(): SSL_CTX_set_min_proto_version(\"%s\"->%d): failed (%d)",
1172 		xfd->para.openssl.min_proto_version, sslver, rc);
1173 	 return STAT_NORETRY;
1174       }
1175 	 Debug1("version: %ld", SSL_CTX_get_min_proto_version(ctx));
1176    }
1177 #endif /* HAVE_SSL_set_min_proto_version || defined(SSL_set_min_proto_version) */
1178 #if HAVE_SSL_CTX_set_max_proto_version || defined(SSL_CTX_set_max_proto_version)
1179    if (xfd->para.openssl.max_proto_version != NULL) {
1180       int sslver;
1181       sslver = _xio_openssl_parse_version(xfd->para.openssl.max_proto_version,
1182 					  XIO_OPENSSL_VERSIONGROUP_TLS|XIO_OPENSSL_VERSIONGROUP_DTLS);
1183       if (sslver < 0)
1184 	 return STAT_NORETRY;
1185       if (SSL_CTX_set_max_proto_version(ctx, sslver) <= 0) {
1186 	 Error2("_xioopen_openssl_prepare(): SSL_CTX_set_max_proto_version(\"%s\"->%d): failed",
1187 		xfd->para.openssl.max_proto_version, sslver);
1188 	 return STAT_NORETRY;
1189       }
1190    }
1191 #endif /* HAVE_SSL_set_max_proto_version || defined(SSL_set_max_proto_version) */
1192 
1193    {
1194       static unsigned char dh2048_p[] = {
1195 	 0x00,0xdc,0x21,0x64,0x56,0xbd,0x9c,0xb2,0xac,0xbe,0xc9,0x98,0xef,0x95,0x3e,
1196 	 0x26,0xfa,0xb5,0x57,0xbc,0xd9,0xe6,0x75,0xc0,0x43,0xa2,0x1c,0x7a,0x85,0xdf,
1197 	 0x34,0xab,0x57,0xa8,0xf6,0xbc,0xf6,0x84,0x7d,0x05,0x69,0x04,0x83,0x4c,0xd5,
1198 	 0x56,0xd3,0x85,0x09,0x0a,0x08,0xff,0xb5,0x37,0xa1,0xa3,0x8a,0x37,0x04,0x46,
1199 	 0xd2,0x93,0x31,0x96,0xf4,0xe4,0x0d,0x9f,0xbd,0x3e,0x7f,0x9e,0x4d,0xaf,0x08,
1200 	 0xe2,0xe8,0x03,0x94,0x73,0xc4,0xdc,0x06,0x87,0xbb,0x6d,0xae,0x66,0x2d,0x18,
1201 	 0x1f,0xd8,0x47,0x06,0x5c,0xcf,0x8a,0xb5,0x00,0x51,0x57,0x9b,0xea,0x1e,0xd8,
1202 	 0xdb,0x8e,0x3c,0x1f,0xd3,0x2f,0xba,0x1f,0x5f,0x3d,0x15,0xc1,0x3b,0x2c,0x82,
1203 	 0x42,0xc8,0x8c,0x87,0x79,0x5b,0x38,0x86,0x3a,0xeb,0xfd,0x81,0xa9,0xba,0xf7,
1204 	 0x26,0x5b,0x93,0xc5,0x3e,0x03,0x30,0x4b,0x00,0x5c,0xb6,0x23,0x3e,0xea,0x94,
1205 	 0xc3,0xb4,0x71,0xc7,0x6e,0x64,0x3b,0xf8,0x92,0x65,0xad,0x60,0x6c,0xd4,0x7b,
1206 	 0xa9,0x67,0x26,0x04,0xa8,0x0a,0xb2,0x06,0xeb,0xe0,0x7d,0x90,0xdd,0xdd,0xf5,
1207 	 0xcf,0xb4,0x11,0x7c,0xab,0xc1,0xa3,0x84,0xbe,0x27,0x77,0xc7,0xde,0x20,0x57,
1208 	 0x66,0x47,0xa7,0x35,0xfe,0x0d,0x6a,0x1c,0x52,0xb8,0x58,0xbf,0x26,0x33,0x81,
1209 	 0x5e,0xb7,0xa9,0xc0,0xee,0x58,0x11,0x74,0x86,0x19,0x08,0x89,0x1c,0x37,0x0d,
1210 	 0x52,0x47,0x70,0x75,0x8b,0xa8,0x8b,0x30,0x11,0x71,0x36,0x62,0xf0,0x73,0x41,
1211 	 0xee,0x34,0x9d,0x0a,0x2b,0x67,0x4e,0x6a,0xa3,0xe2,0x99,0x92,0x1b,0xf5,0x32,
1212 	 0x73,0x63
1213       };
1214       static unsigned char dh2048_g[] = {
1215 	 0x02,
1216       };
1217       DH *dh;
1218       BIGNUM *p = NULL, *g = NULL;
1219       unsigned long err;
1220 
1221       dh = DH_new();
1222       p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
1223       g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
1224       if (!dh || !p || !g) {
1225          if (dh)
1226             DH_free(dh);
1227          if (p)
1228             BN_free(p);
1229          if (g)
1230             BN_free(g);
1231          while (err = ERR_get_error()) {
1232             Warn1("dh2048 setup(): %s",
1233                   ERR_error_string(err, NULL));
1234          }
1235          Error("dh2048 setup failed");
1236          goto cont_out;
1237       }
1238 #if HAVE_DH_set0_pqg
1239       if (!DH_set0_pqg(dh, p, NULL, g)) {
1240 	      DH_free(dh);
1241 	      BN_free(p);
1242 	      BN_free(g);
1243 	      goto cont_out;
1244       }
1245 #else
1246       dh->p = p;
1247       dh->g = g;
1248 #endif /* HAVE_DH_set0_pqg */
1249       if (sycSSL_CTX_set_tmp_dh(ctx, dh) <= 0) {
1250          while (err = ERR_get_error()) {
1251             Warn3("SSL_CTX_set_tmp_dh(%p, %p): %s", ctx, dh,
1252                   ERR_error_string(err, NULL));
1253          }
1254          Error2("SSL_CTX_set_tmp_dh(%p, %p) failed", ctx, dh);
1255       }
1256       /* p & g are freed by DH_free() once attached */
1257       DH_free(dh);
1258 cont_out:
1259       ;
1260    }
1261 
1262 #if HAVE_TYPE_EC_KEY	/* not on Openindiana 5.11 */
1263    {
1264       /* see http://openssl.6102.n7.nabble.com/Problem-with-cipher-suite-ECDHE-ECDSA-AES256-SHA384-td42229.html */
1265       int	 nid;
1266       EC_KEY *ecdh;
1267 
1268 #if 0
1269       nid = OBJ_sn2nid(ECDHE_CURVE);
1270       if (nid == NID_undef) {
1271 	 Error("openssl: failed to set ECDHE parameters");
1272 	 return -1;
1273       }
1274 #endif
1275       nid = NID_X9_62_prime256v1;
1276       ecdh = EC_KEY_new_by_curve_name(nid);
1277       if (NULL == ecdh) {
1278 	 Error("openssl: failed to set ECDHE parameters");
1279 	 return -1;
1280       }
1281 
1282       SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1283    }
1284 #endif /* HAVE_TYPE_EC_KEY */
1285 
1286 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
1287    if (opt_compress) {
1288       int result;
1289       result = openssl_setup_compression(ctx, opt_compress);
1290       if (result != STAT_OK) {
1291 	return result;
1292       }
1293    }
1294 #endif
1295 
1296 #if defined(HAVE_SSL_CTX_clear_mode) || defined(SSL_CTX_clear_mode)
1297    /* It seems that OpenSSL-1.1.1 presets the mode differently.
1298       Without correction socat might hang in SSL_read() */
1299    {
1300       long mode = 0;
1301       mode = SSL_CTX_get_mode(ctx);
1302       if (mode & SSL_MODE_AUTO_RETRY) {
1303 	 Info("SSL_CTX mode has SSL_MODE_AUTO_RETRY set. Correcting..");
1304 	 Debug1("SSL_CTX_clear_mode(%p, SSL_MODE_AUTO_RETRY)", ctx);
1305 	 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1306       }
1307    }
1308 #endif /* defined(HAVE_SSL_CTX_clear_mode) || defined(SSL_CTX_clear_mode) */
1309 
1310    if (opt_cafile != NULL || opt_capath != NULL) {
1311       if (sycSSL_CTX_load_verify_locations(ctx, opt_cafile, opt_capath) != 1) {
1312 	 int result;
1313 
1314 	 if ((result =
1315 	      openssl_SSL_ERROR_SSL(E_ERROR, "SSL_CTX_load_verify_locations"))
1316 	     != STAT_OK) {
1317 	    /*! free ctx */
1318 	    return STAT_RETRYLATER;
1319 	 }
1320       }
1321 #ifdef HAVE_SSL_CTX_set_default_verify_paths
1322    } else {
1323       SSL_CTX_set_default_verify_paths(ctx);
1324 #endif
1325    }
1326 
1327    if (opt_cert) {
1328       BIO *bio;
1329       DH *dh;
1330 
1331       if (sycSSL_CTX_use_certificate_chain_file(ctx, opt_cert) <= 0) {
1332 	 /*! trace functions */
1333 	 /*0 ERR_print_errors_fp(stderr);*/
1334 	 if (ERR_peek_error() == 0)
1335 	    Error2("SSL_CTX_use_certificate_file(%p, \"%s\", SSL_FILETYPE_PEM) failed",
1336 		 ctx, opt_cert);
1337 	 while (err = ERR_get_error()) {
1338 	    Error1("SSL_CTX_use_certificate_file(): %s",
1339 		   ERR_error_string(err, NULL));
1340 	 }
1341 	 return STAT_RETRYLATER;
1342       }
1343 
1344       if (sycSSL_CTX_use_PrivateKey_file(ctx, opt_key?opt_key:opt_cert, SSL_FILETYPE_PEM) <= 0) {
1345 	 /*ERR_print_errors_fp(stderr);*/
1346 	 openssl_SSL_ERROR_SSL(E_ERROR/*!*/, "SSL_CTX_use_PrivateKey_file");
1347 	 return STAT_RETRYLATER;
1348       }
1349 
1350       if (opt_dhparam == NULL) {
1351 	 opt_dhparam = (char *)opt_cert;
1352       }
1353       if ((bio = sycBIO_new_file(opt_dhparam, "r")) == NULL) {
1354 	 Warn2("BIO_new_file(\"%s\", \"r\"): %s",
1355 	       opt_dhparam, strerror(errno));
1356       } else {
1357 	 if ((dh = sycPEM_read_bio_DHparams(bio, NULL, NULL, NULL)) == NULL) {
1358 	    Info1("PEM_read_bio_DHparams(%p, NULL, NULL, NULL): error", bio);
1359 	 } else {
1360 	    BIO_free(bio);
1361 	    if (sycSSL_CTX_set_tmp_dh(ctx, dh) <= 0) {
1362 	       while (err = ERR_get_error()) {
1363 		  Warn3("SSL_CTX_set_tmp_dh(%p, %p): %s", ctx, dh,
1364 			ERR_error_string(err, NULL));
1365 	       }
1366 	       Error2("SSL_CTX_set_tmp_dh(%p, %p): error", ctx, dh);
1367 	    }
1368 	 }
1369       }
1370    }
1371 
1372    /* set pre openssl-connect options */
1373    /* SSL_CIPHERS */
1374    if (ci_str != NULL) {
1375       if (sycSSL_CTX_set_cipher_list(ctx, ci_str) <= 0) {
1376 	 if (ERR_peek_error() == 0)
1377 	    Error1("SSL_set_cipher_list(, \"%s\") failed", ci_str);
1378 	 while (err = ERR_get_error()) {
1379 	    Error2("SSL_set_cipher_list(, \"%s\"): %s",
1380 		   ci_str, ERR_error_string(err, NULL));
1381 	 }
1382 	 /*Error("SSL_new()");*/
1383 	 return STAT_RETRYLATER;
1384       }
1385    }
1386 
1387    if (*opt_ver) {
1388       sycSSL_CTX_set_verify(ctx,
1389 			    SSL_VERIFY_PEER| SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1390 			    NULL);
1391    } else {
1392       sycSSL_CTX_set_verify(ctx,
1393 			    SSL_VERIFY_NONE,
1394 			    NULL);
1395    }
1396 
1397    return STAT_OK;
1398 }
1399 
1400 
1401 /* analyses an OpenSSL error condition, prints the appropriate messages with
1402    severity 'level' and returns one of STAT_OK, STAT_RETRYLATER, or
1403    STAT_NORETRY */
openssl_SSL_ERROR_SSL(int level,const char * funcname)1404 static int openssl_SSL_ERROR_SSL(int level, const char *funcname) {
1405    unsigned long e;
1406    char buf[120];	/* this value demanded by "man ERR_error_string" */
1407    int stat = STAT_OK;
1408 
1409    while (e = ERR_get_error()) {
1410       Debug1("ERR_get_error(): %lx", e);
1411       if
1412 	 (
1413 #if defined(OPENSSL_IS_BORINGSSL)
1414 	  0  /* BoringSSL's RNG always succeeds. */
1415 #elif defined(HAVE_RAND_status)
1416 	  ERR_GET_LIB(e) == ERR_LIB_RAND && RAND_status() != 1
1417 #else
1418 	  e == ((ERR_LIB_RAND<<24)|
1419 #if defined(RAND_F_RAND_BYTES)
1420 		(RAND_F_RAND_BYTES<<12)|
1421 #else
1422 		(RAND_F_SSLEAY_RAND_BYTES<<12)|
1423 #endif
1424 		(RAND_R_PRNG_NOT_SEEDED)) /*0x24064064*/
1425 #endif
1426 	  )
1427       {
1428 	 Error("too few entropy; use options \"egd\" or \"pseudo\"");
1429 	 stat = STAT_NORETRY;
1430       } else {
1431 	 Msg2(level, "%s(): %s", funcname, ERR_error_string(e, buf));
1432 	 stat =  level==E_ERROR ? STAT_NORETRY : STAT_RETRYLATER;
1433       }
1434    }
1435    return stat;
1436 }
1437 
1438 static const char *openssl_verify_messages[] = {
1439    /*  0 */ "ok",
1440    /*  1 */ NULL,
1441    /*  2 */ "unable to get issuer certificate",
1442    /*  3 */ "unable to get certificate CRL",
1443    /*  4 */ "unable to decrypt certificate's signature",
1444    /*  5 */ "unable to decrypt CRL's signature",
1445    /*  6 */ "unable to decode issuer public key",
1446    /*  7 */ "certificate signature failure",
1447    /*  8 */ "CRL signature failure",
1448    /*  9 */ "certificate is not yet valid",
1449    /* 10 */ "certificate has expired",
1450    /* 11 */ "CRL is not yet valid",
1451    /* 12 */ "CRL has expired",
1452    /* 13 */ "format error in certificate's notBefore field",
1453    /* 14 */ "format error in certificate's notAfter field",
1454    /* 15 */ "format error in CRL's lastUpdate field",
1455    /* 16 */ "format error in CRL's nextUpdate field",
1456    /* 17 */ "out of memory",
1457    /* 18 */ "self signed certificate",
1458    /* 19 */ "self signed certificate in certificate chain",
1459    /* 20 */ "unable to get local issuer certificate",
1460    /* 21 */ "unable to verify the first certificate",
1461    /* 22 */ "certificate chain too long",
1462    /* 23 */ "certificate revoked",
1463    /* 24 */ "invalid CA certificate",
1464    /* 25 */ "path length constraint exceeded",
1465    /* 26 */ "unsupported certificate purpose",
1466    /* 27 */ "certificate not trusted",
1467    /* 28 */ "certificate rejected",
1468    /* 29 */ "subject issuer mismatch",
1469    /* 30 */ "authority and subject key identifier mismatch",
1470    /* 31 */ "authority and issuer serial number mismatch",
1471    /* 32 */ "key usage does not include certificate signing",
1472    /* 33 */ NULL,
1473    /* 34 */ NULL,
1474    /* 35 */ NULL,
1475    /* 36 */ NULL,
1476    /* 37 */ NULL,
1477    /* 38 */ NULL,
1478    /* 39 */ NULL,
1479    /* 40 */ NULL,
1480    /* 41 */ NULL,
1481    /* 42 */ NULL,
1482    /* 43 */ NULL,
1483    /* 44 */ NULL,
1484    /* 45 */ NULL,
1485    /* 46 */ NULL,
1486    /* 47 */ NULL,
1487    /* 48 */ NULL,
1488    /* 49 */ NULL,
1489    /* 50 */ "application verification failure",
1490 } ;
1491 
1492 
1493 /* delete all environment variables whose name begins with SOCAT_OPENSSL_
1494    resp. <progname>_OPENSSL_ */
openssl_delete_cert_info(void)1495 static int openssl_delete_cert_info(void) {
1496 #  define XIO_ENVNAMELEN 256
1497    const char *progname;
1498    char envprefix[XIO_ENVNAMELEN];
1499    char envname[XIO_ENVNAMELEN];
1500    size_t i, l;
1501    const char **entry;
1502 
1503    progname = diag_get_string('p');
1504    envprefix[0] = '\0'; strncat(envprefix, progname, XIO_ENVNAMELEN-1);
1505    l = strlen(envprefix);
1506    for (i = 0; i < l; ++i)  envprefix[i] = toupper(envprefix[i]);
1507    strncat(envprefix+l, "_OPENSSL_", XIO_ENVNAMELEN-l-1);
1508 
1509 #if HAVE_VAR_ENVIRON
1510    entry = (const char **)environ;
1511    while (*entry != NULL) {
1512       if (!strncmp(*entry, envprefix, strlen(envprefix))) {
1513 	 const char *eq = strchr(*entry, '=');
1514 	 if (eq == NULL)  eq = *entry + strlen(*entry);
1515 	 envname[0] = '\0'; strncat(envname, *entry, eq-*entry);
1516 #if HAVE_UNSETENV
1517 	 Unsetenv(envname);
1518 #endif
1519       } else {
1520 	 ++entry;
1521       }
1522    }
1523 #endif /* HAVE_VAR_ENVIRON */
1524    return 0;
1525 }
1526 
1527 /* read in the "name" information (from field "issuer" or "subject") and
1528    create environment variable with complete info, eg:
1529    SOCAT_OPENSSL_X509_SUBJECT */
openssl_setenv_cert_name(const char * field,X509_NAME * name)1530 static int openssl_setenv_cert_name(const char *field, X509_NAME *name) {
1531    BIO *bio = BIO_new(BIO_s_mem());
1532    char *buf = NULL, *str;
1533    size_t len;
1534    X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE&~ASN1_STRFLGS_ESC_MSB);	/* rc not documented */
1535    len = BIO_get_mem_data (bio, &buf);
1536    if ((str = Malloc(len+1)) == NULL) {
1537       BIO_free(bio);
1538       return -1;
1539    }
1540    memcpy(str, buf, len);
1541    str[len] = '\0';
1542    Info2("SSL peer cert %s: \"%s\"", field, buf);
1543    xiosetenv2("OPENSSL_X509", field, str, 1, NULL);
1544    free(str);
1545    BIO_free(bio);
1546    return 0;
1547 }
1548 
1549 /* read in the "name" information (from field "issuer" or "subject") and
1550    create environment variables with the fields, eg:
1551    SOCAT_OPENSSL_X509_COMMONNAME
1552 */
openssl_setenv_cert_fields(const char * field,X509_NAME * name)1553 static int openssl_setenv_cert_fields(const char *field, X509_NAME *name) {
1554    int n, i;
1555    n = X509_NAME_entry_count(name);
1556    /* extract fields of cert name */
1557    for (i = 0; i < n; ++i) {
1558       X509_NAME_ENTRY *entry;
1559       ASN1_OBJECT *obj;
1560       ASN1_STRING *data;
1561       const unsigned char *text;
1562       int nid;
1563       entry = X509_NAME_get_entry(name, i);
1564       obj  = X509_NAME_ENTRY_get_object(entry);
1565       data = X509_NAME_ENTRY_get_data(entry);
1566       nid  = OBJ_obj2nid(obj);
1567 #if HAVE_ASN1_STRING_get0_data
1568       text = ASN1_STRING_get0_data(data);
1569 #else
1570       text = ASN1_STRING_data(data);
1571 #endif
1572       Debug3("SSL peer cert %s entry: %s=\"%s\"", (field[0]?field:"subject"), OBJ_nid2ln(nid), text);
1573       if (field != NULL && field[0] != '\0') {
1574          xiosetenv3("OPENSSL_X509", field, OBJ_nid2ln(nid), (const char *)text, 2, " // ");
1575       } else {
1576          xiosetenv2("OPENSSL_X509", OBJ_nid2ln(nid), (const char *)text, 2, " // ");
1577       }
1578    }
1579    return 0;
1580 }
1581 
1582 /* compares the peername used/provided by the client to cn as extracted from
1583    the peer certificate.
1584    supports wildcard cn like *.domain which matches domain and
1585    host.domain
1586    returns true on match */
openssl_check_name(const char * nametype,const char * cn,const char * peername)1587 static bool openssl_check_name(const char *nametype, const char *cn, const char *peername) {
1588    const char *dotp;
1589    if (peername == NULL) {
1590       Info2("%s \"%s\": no peername", nametype, cn);
1591       return false;
1592    } else if (peername[0] == '\0') {
1593       Info2("%s \"%s\": matched by empty peername", nametype, cn);
1594       return true;
1595    }
1596    if (! (cn[0] == '*' && cn[1] == '.')) {
1597       /* normal server name - this is simple */
1598       if (strcmp(cn, peername) == 0) {
1599 	 Debug3("%s \"%s\" matches peername \"%s\"", nametype, cn, peername);
1600 	 return true;
1601       } else {
1602 	 Info3("%s \"%s\" does not match peername \"%s\"", nametype, cn, peername);
1603 	 return false;
1604       }
1605    }
1606    /* wildcard cert */
1607    Debug2("%s \"%s\" is a wildcard name", nametype, cn);
1608    /* case: just the base domain */
1609    if (strcmp(cn+2, peername) == 0) {
1610       Debug3("wildcard %s \"%s\" matches base domain \"%s\"", nametype, cn, peername);
1611       return true;
1612    }
1613    /* case: subdomain; only one level! */
1614    dotp = strchr(peername, '.');
1615    if (dotp == NULL) {
1616       Info2("peername \"%s\" is not a subdomain, thus is not matched by wildcard commonName \"%s\"",
1617 	    peername, cn);
1618       return false;
1619    }
1620    if (strcmp(cn+1, dotp) != 0) {
1621       Info3("%s \"%s\" does not match subdomain peername \"%s\"", nametype, cn, peername);
1622       return false;
1623    }
1624    Debug3("%s \"%s\" matches subdomain peername \"%s\"", nametype, cn, peername);
1625    return true;
1626 }
1627 
1628 /* retrieves the commonName field and compares it to the peername
1629    returns true on match, false otherwise */
openssl_check_peername(X509_NAME * name,const char * peername)1630 static bool openssl_check_peername(X509_NAME *name, const char *peername) {
1631    int ind = -1;
1632    X509_NAME_ENTRY *entry;
1633    ASN1_STRING *data;
1634    const unsigned char *text;
1635    ind = X509_NAME_get_index_by_NID(name, NID_commonName, -1);
1636    if (ind < 0) {
1637       Info("no COMMONNAME field in peer certificate");
1638       return false;
1639    }
1640    entry = X509_NAME_get_entry(name, ind);
1641    data = X509_NAME_ENTRY_get_data(entry);
1642 #if HAVE_ASN1_STRING_get0_data
1643    text = ASN1_STRING_get0_data(data);
1644 #else
1645    text = ASN1_STRING_data(data);
1646 #endif
1647    return openssl_check_name("commonName", (const char *)text, peername);
1648 }
1649 
1650 /* retrieves certificate provided by peer, sets env vars containing
1651    certificates field values, and checks peername if provided by
1652    calling function */
1653 /* parts of this code were copied from Gene Spaffords C/C++ Secure Programming at Etutorials.org:
1654    http://etutorials.org/Programming/secure+programming/Chapter+10.+Public+Key+Infrastructure/10.8+Adding+Hostname+Checking+to+Certificate+Verification/
1655    The code examples in this tutorial do not seem to have explicit license restrictions.
1656 */
1657 /* peername is, with OpenSSL client, the server name, or the value of option
1658    commonname if provided;
1659    With OpenSSL server, it is the value of option commonname */
openssl_handle_peer_certificate(struct single * xfd,const char * peername,bool opt_ver,int level)1660 static int openssl_handle_peer_certificate(struct single *xfd,
1661 					   const char *peername,
1662 					   bool opt_ver, int level) {
1663    X509 *peer_cert;
1664    X509_NAME *subjectname, *issuername;
1665    /*ASN1_TIME not_before, not_after;*/
1666    int extcount, i, ok = 0;
1667    int status;
1668 
1669    if ((peer_cert = SSL_get_peer_certificate(xfd->para.openssl.ssl)) == NULL) {
1670       if (opt_ver) {
1671 	 Msg(level, "no peer certificate");
1672 	 status = STAT_RETRYLATER;
1673       } else {
1674 	 Notice("no peer certificate and no check");
1675 	 status = STAT_OK;
1676       }
1677       return status;
1678    }
1679 
1680    /* verify peer certificate (trust, signature, validity dates) */
1681    if (opt_ver) {
1682       long verify_result;
1683       if ((verify_result = sycSSL_get_verify_result(xfd->para.openssl.ssl)) != X509_V_OK) {
1684 	 const char *message = NULL;
1685 	 if (verify_result >= 0 &&
1686 	     (size_t)verify_result <
1687 	     sizeof(openssl_verify_messages)/sizeof(char*)) {
1688 	    message = openssl_verify_messages[verify_result];
1689 	 }
1690 	 if (message) {
1691 	    Msg1(level, "%s", message);
1692 	 } else {
1693 	    Msg1(level, "rejected peer certificate with error %ld", verify_result);
1694 	 }
1695 	 status = STAT_RETRYLATER;
1696 	 X509_free(peer_cert);
1697 	 return STAT_RETRYLATER;
1698       }
1699       Info("peer certificate is trusted");
1700    }
1701 
1702    /* set env vars from cert's subject and issuer values */
1703    if ((subjectname = X509_get_subject_name(peer_cert)) != NULL) {
1704       openssl_setenv_cert_name("subject", subjectname);
1705       openssl_setenv_cert_fields("", subjectname);
1706       /*! I'd like to provide dates too; see
1707 	 http://markmail.org/message/yi4vspp7aeu3xwtu#query:+page:1+mid:jhnl4wklif3pgzqf+state:results */
1708    }
1709    if ((issuername = X509_get_issuer_name(peer_cert)) != NULL) {
1710       openssl_setenv_cert_name("issuer", issuername);
1711    }
1712 
1713    if (!opt_ver) {
1714       Notice("option openssl-verify disabled, no check of certificate");
1715       X509_free(peer_cert);
1716       return STAT_OK;
1717    }
1718 
1719    /* check peername against cert's subjectAltName DNS entries */
1720    /* this code is based on example from Gerhard Gappmeier in
1721       http://openssl.6102.n7.nabble.com/How-to-extract-subjectAltName-td17236.html
1722       and the GEN_IPADD from
1723       http://openssl.6102.n7.nabble.com/reading-IP-addresses-from-Subject-Alternate-Name-extension-td29245.html
1724    */
1725    if ((extcount = X509_get_ext_count(peer_cert)) > 0) {
1726       for (i = 0;  !ok && i < extcount;  ++i) {
1727 	 const char            *extstr;
1728 	 X509_EXTENSION        *ext;
1729 	 const X509V3_EXT_METHOD     *meth;
1730 	 ext = X509_get_ext(peer_cert, i);
1731 	 extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
1732 	 if (!strcasecmp(extstr, "subjectAltName")) {
1733 	    void *names;
1734 	    if (!(meth = X509V3_EXT_get(ext))) break;
1735 	    names = X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
1736 	    if (names) {
1737 	       int numalts;
1738 	       int i;
1739 
1740 	       /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */
1741 	       numalts = sk_GENERAL_NAME_num ( names );
1742 	       /* loop through all alternatives */
1743 	       for (i = 0; i < numalts; ++i) {
1744 		  /* get a handle to alternative name number i */
1745 		  const GENERAL_NAME *pName = sk_GENERAL_NAME_value (names, i);
1746 		  unsigned char *pBuffer;
1747 		  switch (pName->type) {
1748 
1749 		  case GEN_DNS:
1750 		     ASN1_STRING_to_UTF8(&pBuffer, pName->d.ia5);
1751 		     xiosetenv("OPENSSL_X509V3_SUBJECTALTNAME_DNS", (char *)pBuffer, 2, " // ");
1752 		     if (peername != NULL &&
1753 			 openssl_check_name("subjectAltName", (char *)pBuffer, /*const char*/peername)) {
1754 			ok = 1;
1755 		     }
1756 		     OPENSSL_free(pBuffer);
1757 		     break;
1758 
1759 		  case GEN_IPADD:
1760 		     {
1761 			/* binary address format */
1762 			const unsigned char *data = pName->d.iPAddress->data;
1763 			size_t len = pName->d.iPAddress->length;
1764 			char aBuffer[INET6_ADDRSTRLEN]; 	/* canonical peername */
1765 			struct in6_addr ip6bin;
1766 
1767 			switch (len) {
1768 			case 4: /* IPv4 */
1769 			   snprintf(aBuffer, sizeof(aBuffer), "%u.%u.%u.%u", data[0], data[1], data[2], data[3]);
1770 			   if (peername != NULL &&
1771 			       openssl_check_name("subjectAltName", aBuffer, /*const char*/peername)) {
1772 			      ok = 1;
1773 			   }
1774 			   break;
1775 #if WITH_IP6
1776 			case 16: /* IPv6 */
1777 			   inet_ntop(AF_INET6, data, aBuffer, sizeof(aBuffer));
1778 			   if (peername != NULL) {
1779 			      xioip6_pton(peername, &ip6bin);
1780 			      if (memcmp(data, &ip6bin, sizeof(ip6bin)) == 0) {
1781 			         Debug2("subjectAltName \"%s\" matches peername \"%s\"",
1782 					aBuffer, peername);
1783 			         ok = 1;
1784 			      } else {
1785 			         Info2("subjectAltName \"%s\" does not match peername \"%s\"",
1786 				       aBuffer, peername);
1787 			      }
1788 			   }
1789 			   break;
1790 #endif
1791 			}
1792 			xiosetenv("OPENSSL_X509V3_SUBJECTALTNAME_IPADD", (char *)aBuffer, 2, " // ");
1793 		     }
1794 		     break;
1795 		  default: Warn3("Unknown subject type %d (GEN_DNS=%d, GEN_IPADD=%d",
1796 				 pName->type, GEN_DNS, GEN_IPADD);
1797 		     continue;
1798 		  }
1799 		  if (ok)  { break; }
1800 	       }
1801 	    }
1802 	 }
1803       }
1804    }
1805 
1806    if (ok) {
1807       Notice("trusting certificate, commonName matches");
1808       X509_free(peer_cert);
1809       return STAT_OK;
1810    }
1811 
1812    if (peername == NULL || peername[0] == '\0') {
1813       Notice("trusting certificate, no check of commonName");
1814       X509_free(peer_cert);
1815       return STAT_OK;
1816    }
1817 
1818    /* here: all envs set; opt_ver, cert verified, no subjAltName match -> check subject CN */
1819    if (!openssl_check_peername(/*X509_NAME*/subjectname, /*const char*/peername)) {
1820       Error1("certificate is valid but its commonName does not match hostname \"%s\"",
1821 	     peername);
1822       status = STAT_NORETRY;
1823    } else {
1824       Notice("trusting certificate, commonName matches");
1825       status = STAT_OK;
1826    }
1827    X509_free(peer_cert);
1828    return status;
1829 }
1830 
xioSSL_set_fd(struct single * xfd,int level)1831 static int xioSSL_set_fd(struct single *xfd, int level) {
1832    unsigned long err;
1833 
1834    /* assign a network connection to the SSL object */
1835    if (sycSSL_set_fd(xfd->para.openssl.ssl, xfd->fd) <= 0) {
1836       Msg(level, "SSL_set_fd() failed");
1837       while (err = ERR_get_error()) {
1838 	 Msg2(level, "SSL_set_fd(, %d): %s",
1839 	      xfd->fd, ERR_error_string(err, NULL));
1840       }
1841       return STAT_RETRYLATER;
1842    }
1843    return STAT_OK;
1844 }
1845 
1846 
1847 /* ...
1848    in case of an error condition, this function check forever and retry
1849    options and ev. sleeps an interval. It returns NORETRY when the caller
1850    should not retry for any reason. */
xioSSL_connect(struct single * xfd,const char * opt_commonname,bool opt_ver,int level)1851 static int xioSSL_connect(struct single *xfd, const char *opt_commonname,
1852 			  bool opt_ver, int level) {
1853    char error_string[120];
1854    int errint, status, ret;
1855    unsigned long err;
1856 
1857    /* connect via SSL by performing handshake */
1858    if ((ret = sycSSL_connect(xfd->para.openssl.ssl)) <= 0) {
1859       /*if (ERR_peek_error() == 0) Msg(level, "SSL_connect() failed");*/
1860       errint = SSL_get_error(xfd->para.openssl.ssl, ret);
1861       switch (errint) {
1862       case SSL_ERROR_NONE:
1863 	 /* this is not an error, but I dare not continue for security reasons*/
1864 	 Msg(level, "ok");
1865 	 status = STAT_RETRYLATER;
1866       case SSL_ERROR_ZERO_RETURN:
1867 	 Msg(level, "connection closed (wrong version number?)");
1868 	 status = STAT_RETRYLATER;
1869 	 break;
1870       case SSL_ERROR_WANT_READ:
1871       case SSL_ERROR_WANT_WRITE:
1872       case SSL_ERROR_WANT_CONNECT:
1873       case SSL_ERROR_WANT_X509_LOOKUP:
1874 	 Msg(level, "nonblocking operation did not complete");
1875 	 status = STAT_RETRYLATER;
1876 	 break;	/*!*/
1877       case SSL_ERROR_SYSCALL:
1878 	 if (ERR_peek_error() == 0) {
1879 	    if (ret == 0) {
1880 	       Msg(level, "SSL_connect(): socket closed by peer");
1881 	    } else if (ret == -1) {
1882 	       Msg1(level, "SSL_connect(): %s", strerror(errno));
1883 	    }
1884 	 } else {
1885 	    Msg(level, "I/O error");	/*!*/
1886 	    while (err = ERR_get_error()) {
1887 	       ERR_error_string_n(err, error_string, sizeof(error_string));
1888 	       Msg4(level, "SSL_connect(): %s / %s / %s / %s", error_string,
1889 		    ERR_lib_error_string(err), ERR_func_error_string(err),
1890 		    ERR_reason_error_string(err));
1891 	    }
1892 	 }
1893 	 status = STAT_RETRYLATER;
1894 	 break;
1895       case SSL_ERROR_SSL:
1896 	 status = openssl_SSL_ERROR_SSL(level, "SSL_connect");
1897 	 if (openssl_handle_peer_certificate(xfd, opt_commonname, opt_ver, level/*!*/) < 0) {
1898 	    return STAT_RETRYLATER;
1899 	 }
1900 	 break;
1901       default:
1902 	 Msg(level, "unknown error");
1903 	 status = STAT_RETRYLATER;
1904 	 break;
1905       }
1906       return status;
1907    }
1908    return STAT_OK;
1909 }
1910 
1911 /* on result < 0: errno is set (at least to EIO) */
xioread_openssl(struct single * pipe,void * buff,size_t bufsiz)1912 ssize_t xioread_openssl(struct single *pipe, void *buff, size_t bufsiz) {
1913    unsigned long err;
1914    char error_string[120];
1915    int _errno = EIO;	/* if we have no better idea about nature of error */
1916    int errint, ret;
1917 
1918    ret = sycSSL_read(pipe->para.openssl.ssl, buff, bufsiz);
1919    if (ret < 0) {
1920       errint = SSL_get_error(pipe->para.openssl.ssl, ret);
1921       switch (errint) {
1922       case SSL_ERROR_NONE:
1923 	 /* this is not an error, but I dare not continue for security reasons*/
1924 	 Error("ok");
1925 	 break;
1926       case SSL_ERROR_ZERO_RETURN:
1927 	 Error("connection closed by peer");
1928 	 break;
1929       case SSL_ERROR_WANT_READ:
1930       case SSL_ERROR_WANT_WRITE:
1931       case SSL_ERROR_WANT_CONNECT:
1932       case SSL_ERROR_WANT_X509_LOOKUP:
1933 	 Info("nonblocking operation did not complete");
1934 	 errno = EAGAIN;
1935 	 return -1;
1936       case SSL_ERROR_SYSCALL:
1937 	 if (ERR_peek_error() == 0) {
1938 	    if (ret == 0) {
1939 	       Error("SSL_read(): socket closed by peer");
1940 	    } else if (ret == -1) {
1941 	       _errno = errno;
1942 	       Error1("SSL_read(): %s", strerror(errno));
1943 	    }
1944 	 } else {
1945 	    Error("I/O error");	/*!*/
1946 	    while (err = ERR_get_error()) {
1947 	       ERR_error_string_n(err, error_string, sizeof(error_string));
1948 	       Error4("SSL_read(): %s / %s / %s / %s", error_string,
1949 		      ERR_lib_error_string(err), ERR_func_error_string(err),
1950 		      ERR_reason_error_string(err));
1951 	    }
1952 	 }
1953 	 break;
1954       case SSL_ERROR_SSL:
1955 	 openssl_SSL_ERROR_SSL(E_ERROR, "SSL_read");
1956 	 break;
1957       default:
1958 	 Error("unknown error");
1959 	 break;
1960       }
1961       errno = _errno;
1962       return -1;
1963    }
1964    return ret;
1965 }
1966 
xiopending_openssl(struct single * pipe)1967 ssize_t xiopending_openssl(struct single *pipe) {
1968    int bytes = sycSSL_pending(pipe->para.openssl.ssl);
1969    return bytes;
1970 }
1971 
1972 /* on result < 0: errno is set (at least to EIO) */
xiowrite_openssl(struct single * pipe,const void * buff,size_t bufsiz)1973 ssize_t xiowrite_openssl(struct single *pipe, const void *buff, size_t bufsiz) {
1974    unsigned long err;
1975    char error_string[120];
1976    int _errno = EIO;	/* if we have no better idea about nature of error */
1977    int errint, ret;
1978 
1979    ret = sycSSL_write(pipe->para.openssl.ssl, buff, bufsiz);
1980    if (ret < 0) {
1981       errint = SSL_get_error(pipe->para.openssl.ssl, ret);
1982       switch (errint) {
1983       case SSL_ERROR_NONE:
1984 	 /* this is not an error, but I dare not continue for security reasons*/
1985 	 Error("ok");
1986       case SSL_ERROR_ZERO_RETURN:
1987 	 Error("connection closed by peer");
1988 	 break;
1989       case SSL_ERROR_WANT_READ:
1990       case SSL_ERROR_WANT_WRITE:
1991       case SSL_ERROR_WANT_CONNECT:
1992       case SSL_ERROR_WANT_X509_LOOKUP:
1993 	 Error("nonblocking operation did not complete");
1994 	 break;	/*!*/
1995       case SSL_ERROR_SYSCALL:
1996 	 if (ERR_peek_error() == 0) {
1997 	    if (ret == 0) {
1998 	       Error("SSL_write(): socket closed by peer");
1999 	    } else if (ret == -1) {
2000 	       _errno = errno;
2001 	       Error1("SSL_write(): %s", strerror(errno));
2002 	    }
2003 	 } else {
2004 	    Error("I/O error");	/*!*/
2005 	    while (err = ERR_get_error()) {
2006 	       ERR_error_string_n(err, error_string, sizeof(error_string));
2007 	       Error4("SSL_write(): %s / %s / %s / %s", error_string,
2008 		      ERR_lib_error_string(err), ERR_func_error_string(err),
2009 		      ERR_reason_error_string(err));
2010 	    }
2011 	 }
2012 	 break;
2013       case SSL_ERROR_SSL:
2014 	 openssl_SSL_ERROR_SSL(E_ERROR, "SSL_write");
2015 	 break;
2016       default:
2017 	 Error("unknown error");
2018 	 break;
2019       }
2020       errno = _errno;
2021       return -1;
2022    }
2023    return ret;
2024 }
2025 
xioshutdown_openssl(struct single * sfd,int how)2026 int xioshutdown_openssl(struct single *sfd, int how)
2027 {
2028    int rc;
2029 
2030    if ((rc = sycSSL_shutdown(sfd->para.openssl.ssl)) < 0) {
2031       Warn1("xioshutdown_openssl(): SSL_shutdown() -> %d", rc);
2032    }
2033    if (sfd->tag == XIO_TAG_WRONLY) {
2034       char buff[1];
2035       /* give peer time to read all data before closing socket */
2036       xioread_openssl(sfd, buff, 1);
2037    }
2038    return 0;
2039 }
2040 
2041 #endif /* WITH_OPENSSL */
2042