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