Version 1.8.0.2 - CVE-2024-54661: Arbitrary file overwrite in readline.sh
[socat.git] / xio-openssl.c
blob1278bf4b4f68621c63bc69e6df3f7dd10e6a9eee
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 **themarr, *themp;
245 bool needbind = false;
246 bool lowport = false;
247 int level = E_ERROR;
248 int i;
249 SSL_CTX* ctx;
250 bool opt_ver = true; /* verify peer certificate */
251 char *opt_cert = NULL; /* file name of client certificate */
252 const char *opt_commonname = NULL; /* for checking peer certificate */
253 bool opt_no_sni = false;
254 const char *opt_snihost = NULL; /* for SNI host */
255 int result;
257 if (!(xioflags & XIO_MAYCONVERT)) {
258 Error("address with data processing not allowed here");
259 return STAT_NORETRY;
261 sfd->flags |= XIO_DOESCONVERT;
263 if (argc != 3) {
264 xio_syntax(argv[0], 2, argc-1, addrdesc->syntax);
265 return STAT_NORETRY;
267 hostname = argv[1];
268 portname = argv[2];
269 if (hostname[0] == '\0') {
270 /* we catch this explicitely because empty commonname (peername) disables
271 commonName check of peer certificate */
272 Error1("%s: empty host name", argv[0]);
273 return STAT_NORETRY;
276 if (sfd->howtoend == END_UNSPEC)
277 sfd->howtoend = END_SHUTDOWN;
278 if (applyopts_single(sfd, opts, PH_INIT) < 0)
279 return -1;
280 applyopts(sfd, -1, opts, PH_INIT);
282 retropt_bool(opts, OPT_FORK, &dofork);
284 retropt_string(opts, OPT_OPENSSL_CERTIFICATE, &opt_cert);
285 retropt_string(opts, OPT_OPENSSL_COMMONNAME, (char **)&opt_commonname);
286 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
287 retropt_bool(opts, OPT_OPENSSL_NO_SNI, &opt_no_sni);
288 retropt_string(opts, OPT_OPENSSL_SNIHOST, (char **)&opt_snihost);
289 #endif
291 if (opt_commonname == NULL) {
292 opt_commonname = strdup(hostname);
293 if (opt_commonname == NULL) {
294 Error1("strdup("F_Zu"): out of memory", strlen(hostname)+1);
298 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
299 if (opt_snihost != NULL) {
300 if (check_ipaddr(opt_snihost) == 0) {
301 Warn1("specified SNI host \"%s\" is an IP address", opt_snihost);
303 } else if (check_ipaddr(opt_commonname) != 0) {
304 opt_snihost = strdup(opt_commonname);
305 if (opt_snihost == NULL) {
306 Error1("strdup("F_Zu"): out of memory", strlen(opt_commonname)+1);
309 #endif
311 result =
312 _xioopen_openssl_prepare(opts, sfd, false, &opt_ver, opt_cert, &ctx, (bool *)&use_dtls);
313 if (result != STAT_OK) return STAT_NORETRY;
315 if (use_dtls) {
316 socktype = SOCK_DGRAM;
317 ipproto = IPPROTO_UDP;
319 retropt_int(opts, OPT_SO_TYPE, &socktype);
320 retropt_int(opts, OPT_SO_PROTOTYPE, &ipproto);
322 result =
323 _xioopen_ipapp_prepare(opts, &opts0, hostname, portname, &pf, ipproto,
324 sfd->para.socket.ip.ai_flags,
325 &themarr, us, &uslen,
326 &needbind, &lowport, socktype);
327 if (result != STAT_OK) return STAT_NORETRY;
329 if (xioparms.logopt == 'm') {
330 Info("starting connect loop, switching to syslog");
331 diag_set('y', xioparms.syslogfac); xioparms.logopt = 'y';
332 } else {
333 Info("starting connect loop");
336 do { /* loop over failed connect and SSL handshake attempts */
338 /* Loop over themarr (which had been "ai_sorted") */
339 i = 0;
340 themp = themarr[i++];
341 while (themp != NULL) {
343 #if WITH_RETRY
344 if (sfd->forever || sfd->retry || themarr[i] != NULL) {
345 level = E_INFO;
346 } else
347 #endif /* WITH_RETRY */
348 level = E_ERROR;
350 /* This cannot fork because we retrieved fork option above */
351 result =
352 _xioopen_connect(sfd,
353 needbind?us:NULL, uslen,
354 themp->ai_addr, themp->ai_addrlen,
355 opts, pf?pf:themp->ai_addr->sa_family, socktype, ipproto, lowport, level);
356 if (result == STAT_OK)
357 break;
358 themp = themarr[i++];
359 if (themp == NULL) {
360 result = STAT_RETRYLATER;
363 switch (result) {
364 case STAT_OK: break;
365 #if WITH_RETRY
366 case STAT_RETRYLATER:
367 case STAT_RETRYNOW:
368 if (sfd->forever || sfd->retry) {
369 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
370 if (result == STAT_RETRYLATER) {
371 Nanosleep(&sfd->intervall, NULL);
373 --sfd->retry;
374 continue;
376 xiofreeaddrinfo(themarr);
377 return STAT_NORETRY;
378 #endif /* WITH_RETRY */
379 default:
380 xiofreeaddrinfo(themarr);
381 return result;
383 /*! isn't this too early? */
384 if ((result = _xio_openlate(sfd, opts)) < 0) {
385 xiofreeaddrinfo(themarr);
386 return result;
389 result = _xioopen_openssl_connect(sfd, opt_ver, opt_commonname,
390 opt_no_sni, opt_snihost, ctx, level);
391 switch (result) {
392 case STAT_OK: break;
393 #if WITH_RETRY
394 case STAT_RETRYLATER:
395 case STAT_RETRYNOW:
396 if (sfd->forever || sfd->retry) {
397 Close(sfd->fd);
398 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
399 if (result == STAT_RETRYLATER) {
400 Nanosleep(&sfd->intervall, NULL);
402 --sfd->retry;
403 continue;
405 #endif /* WITH_RETRY */
406 default:
407 xiofreeaddrinfo(themarr);
408 return STAT_NORETRY;
411 if (dofork) {
412 xiosetchilddied(); /* set SIGCHLD handler */
415 #if WITH_RETRY
416 if (dofork) {
417 pid_t pid;
418 int level = E_ERROR;
419 if (sfd->forever || sfd->retry) {
420 level = E_WARN;
422 while ((pid = xio_fork(false, level, sfd->shutup)) < 0) {
423 if (sfd->forever || --sfd->retry) {
424 Nanosleep(&sfd->intervall, NULL); continue;
426 xiofreeaddrinfo(themarr);
427 return STAT_RETRYLATER;
430 if (pid == 0) { /* child process */
431 sfd->forever = false; sfd->retry = 0;
432 break;
435 /* parent process */
436 Close(sfd->fd);
437 sycSSL_free(sfd->para.openssl.ssl);
438 sfd->para.openssl.ssl = NULL;
439 /* with and without retry */
440 Nanosleep(&sfd->intervall, NULL);
441 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
442 continue; /* with next socket() bind() connect() */
444 #endif /* WITH_RETRY */
445 break;
446 } while (true); /* drop out on success */
447 xiofreeaddrinfo(themarr);
449 openssl_conn_loginfo(sfd->para.openssl.ssl);
451 free((void *)opt_commonname);
452 free((void *)opt_snihost);
454 /* fill in the fd structure */
455 return STAT_OK;
459 /* this function is typically called within the OpenSSL client fork/retry loop.
460 sfd must be of type DATA_OPENSSL, and its fd must be set with a valid file
461 descriptor. this function then performs all SSL related step to make a valid
462 SSL connection from an FD and a CTX. */
463 int _xioopen_openssl_connect(struct single *sfd,
464 bool opt_ver,
465 const char *opt_commonname,
466 bool no_sni,
467 const char *snihost,
468 SSL_CTX *ctx,
469 int level) {
470 SSL *ssl;
471 unsigned long err;
472 int result;
474 /* create a SSL object */
475 if ((ssl = sycSSL_new(ctx)) == NULL) {
476 if (ERR_peek_error() == 0) Msg(level, "SSL_new() failed");
477 while (err = ERR_get_error()) {
478 Msg1(level, "SSL_new(): %s", ERR_error_string(err, NULL));
480 /*Error("SSL_new()");*/
481 return STAT_RETRYLATER;
483 sfd->para.openssl.ssl = ssl;
485 result = xioSSL_set_fd(sfd, level);
486 if (result != STAT_OK) {
487 sycSSL_free(sfd->para.openssl.ssl);
488 sfd->para.openssl.ssl = NULL;
489 return result;
492 #if defined(HAVE_SSL_set_tlsext_host_name) || defined(SSL_set_tlsext_host_name)
493 if (!no_sni) {
494 if (snihost == NULL || strlen(snihost) == 0) {
495 Warn("refusing to set empty SNI host name");
496 } else if (!SSL_set_tlsext_host_name(ssl, snihost)) {
497 Error1("Failed to set SNI host \"%s\"", snihost);
498 sycSSL_free(sfd->para.openssl.ssl);
499 sfd->para.openssl.ssl = NULL;
500 return STAT_NORETRY;
503 #endif
505 result = xioSSL_connect(sfd, opt_commonname, opt_ver, level);
506 if (result != STAT_OK) {
507 sycSSL_free(sfd->para.openssl.ssl);
508 sfd->para.openssl.ssl = NULL;
509 return result;
512 result = openssl_handle_peer_certificate(sfd, opt_commonname,
513 opt_ver, level);
514 if (result != STAT_OK) {
515 sycSSL_free(sfd->para.openssl.ssl);
516 sfd->para.openssl.ssl = NULL;
517 return result;
520 return STAT_OK;
524 #if WITH_LISTEN
526 static int xioopen_openssl_listen(
527 int argc,
528 const char *argv[], /* the arguments in the address string */
529 struct opt *opts,
530 int xioflags, /* is the open meant for reading (0),
531 writing (1), or both (2) ? */
532 xiofile_t *xxfd, /* a xio file descriptor structure,
533 already allocated */
534 const struct addrdesc *addrdesc) /* the above descriptor */
536 struct single *sfd = &xxfd->stream;
537 const char *portname;
538 int protogrp = addrdesc->arg1;
539 struct opt *opts0 = NULL;
540 union sockaddr_union us_sa, *us = &us_sa;
541 socklen_t uslen = sizeof(us_sa);
542 int pf = PF_UNSPEC;
543 bool use_dtls = (protogrp != 0);
544 int socktype = SOCK_STREAM;
545 int ipproto = IPPROTO_TCP;
546 /*! lowport? */
547 int level;
548 SSL_CTX* ctx;
549 bool opt_ver = true; /* verify peer certificate - changed with 1.6.0 */
550 char *opt_cert = NULL; /* file name of server certificate */
551 const char *opt_commonname = NULL; /* for checking peer certificate */
552 int result;
554 if (!(xioflags & XIO_MAYCONVERT)) {
555 Error("address with data processing not allowed here");
556 return STAT_NORETRY;
558 sfd->flags |= XIO_DOESCONVERT;
560 if (argc != 2) {
561 xio_syntax(argv[0], 1, argc-1, addrdesc->syntax);
562 return STAT_NORETRY;
565 xioinit_ip(&pf, xioparms.default_ip);
566 #if WITH_IP4 && WITH_IP6
567 switch (xioparms.default_ip) {
568 case '4': pf = PF_INET; break;
569 case '6': pf = PF_INET6; break;
570 default: break; /* includes \0 */
572 #elif WITH_IP6
573 pf = PF_INET6;
574 #else
575 pf = PF_INET;
576 #endif
578 portname = argv[1];
580 if (sfd->howtoend == END_UNSPEC)
581 sfd->howtoend = END_SHUTDOWN;
582 if (applyopts_single(sfd, opts, PH_INIT) < 0) return -1;
583 applyopts(sfd, -1, opts, PH_INIT);
585 retropt_string(opts, OPT_OPENSSL_CERTIFICATE, &opt_cert);
586 if (opt_cert == NULL) {
587 Warn("no certificate given; consider option \"cert\"");
590 retropt_string(opts, OPT_OPENSSL_COMMONNAME, (char **)&opt_commonname);
592 applyopts(sfd, -1, opts, PH_EARLY);
594 result =
595 _xioopen_openssl_prepare(opts, sfd, true, &opt_ver, opt_cert, &ctx, &use_dtls);
596 if (result != STAT_OK) return STAT_NORETRY;
598 if (use_dtls) {
599 socktype = SOCK_DGRAM;
600 ipproto = IPPROTO_UDP;
602 retropt_int(opts, OPT_SO_TYPE, &socktype);
603 retropt_int(opts, OPT_SO_PROTOTYPE, &ipproto);
605 if (_xioopen_ipapp_listen_prepare(opts, &opts0, portname, &pf, ipproto,
606 sfd->para.socket.ip.ai_flags,
607 us, &uslen, socktype)
608 != STAT_OK) {
609 return STAT_NORETRY;
611 if (pf == 0)
612 pf = us->soa.sa_family;
614 sfd->dtype = XIODATA_OPENSSL;
616 while (true) { /* loop over failed attempts */
618 #if WITH_RETRY
619 if (sfd->forever || sfd->retry) {
620 level = E_INFO;
621 } else
622 #endif /* WITH_RETRY */
623 level = E_ERROR;
625 /* this can fork() for us; it only returns on error or on
626 successful establishment of connection */
627 if (ipproto == IPPROTO_TCP
628 #ifdef IPPROTO_DCCP
629 || ipproto == IPPROTO_DCCP
630 #endif
632 result = _xioopen_listen(sfd, xioflags,
633 (struct sockaddr *)us, uslen,
634 opts, pf, socktype, ipproto,
635 #if WITH_RETRY
636 (sfd->retry||sfd->forever)?E_INFO:E_ERROR
637 #else
638 E_ERROR
639 #endif /* WITH_RETRY */
641 #if WITH_UDP
642 } else {
643 result = _xioopen_ipdgram_listen(sfd, xioflags,
644 us, uslen, opts, pf, socktype, ipproto);
645 #endif /* WITH_UDP */
647 /*! not sure if we should try again on retry/forever */
648 switch (result) {
649 case STAT_OK: break;
650 #if WITH_RETRY
651 case STAT_RETRYLATER:
652 case STAT_RETRYNOW:
653 if (sfd->forever || sfd->retry) {
654 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
655 if (result == STAT_RETRYLATER) {
656 Nanosleep(&sfd->intervall, NULL);
658 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
659 --sfd->retry;
660 continue;
662 return STAT_NORETRY;
663 #endif /* WITH_RETRY */
664 default:
665 return result;
668 result = _xioopen_openssl_listen(sfd, opt_ver, opt_commonname, ctx, level);
669 switch (result) {
670 case STAT_OK: break;
671 #if WITH_RETRY
672 case STAT_RETRYLATER:
673 case STAT_RETRYNOW:
674 if (sfd->forever || sfd->retry) {
675 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
676 if (result == STAT_RETRYLATER) {
677 Nanosleep(&sfd->intervall, NULL);
679 dropopts(opts, PH_ALL); opts = copyopts(opts0, GROUP_ALL);
680 --sfd->retry;
681 continue;
683 return STAT_NORETRY;
684 #endif /* WITH_RETRY */
685 default:
686 return result;
689 openssl_conn_loginfo(sfd->para.openssl.ssl);
690 break;
692 } /* drop out on success */
694 /* fill in the fd structure */
696 return STAT_OK;
700 int _xioopen_openssl_listen(struct single *sfd,
701 bool opt_ver,
702 const char *opt_commonname,
703 SSL_CTX *ctx,
704 int level) {
705 char error_string[120];
706 unsigned long err;
707 int errint, ret;
709 /* create an SSL object */
710 if ((sfd->para.openssl.ssl = sycSSL_new(ctx)) == NULL) {
711 if (ERR_peek_error() == 0) Msg(level, "SSL_new() failed");
712 while (err = ERR_get_error()) {
713 Msg1(level, "SSL_new(): %s", ERR_error_string(err, NULL));
715 /*Error("SSL_new()");*/
716 return STAT_NORETRY;
719 /* assign the network connection to the SSL object */
720 if (sycSSL_set_fd(sfd->para.openssl.ssl, sfd->fd) <= 0) {
721 if (ERR_peek_error() == 0) Msg(level, "SSL_set_fd() failed");
722 while (err = ERR_get_error()) {
723 Msg2(level, "SSL_set_fd(, %d): %s",
724 sfd->fd, ERR_error_string(err, NULL));
728 #if WITH_DEBUG
730 int i = 0;
731 const char *ciphers = NULL;
732 Debug("available ciphers:");
733 do {
734 ciphers = SSL_get_cipher_list(sfd->para.openssl.ssl, i);
735 if (ciphers == NULL) break;
736 Debug2("CIPHERS pri=%d: %s", i, ciphers);
737 ++i;
738 } while (1);
740 #endif /* WITH_DEBUG */
742 /* connect via SSL by performing handshake */
743 if ((ret = sycSSL_accept(sfd->para.openssl.ssl)) <= 0) {
744 /*if (ERR_peek_error() == 0) Msg(level, "SSL_accept() failed");*/
745 errint = SSL_get_error(sfd->para.openssl.ssl, ret);
746 switch (errint) {
747 case SSL_ERROR_NONE:
748 Msg(level, "ok"); break;
749 case SSL_ERROR_ZERO_RETURN:
750 Msg(level, "connection closed (wrong version number?)"); break;
751 case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE:
752 case SSL_ERROR_WANT_CONNECT:
753 case SSL_ERROR_WANT_X509_LOOKUP:
754 Msg(level, "nonblocking operation did not complete"); break; /*!*/
755 case SSL_ERROR_SYSCALL:
756 if (ERR_peek_error() == 0) {
757 if (ret == 0) {
758 Msg(level, "SSL_accept(): socket closed by peer");
759 } else if (ret == -1) {
760 Msg1(level, "SSL_accept(): %s", strerror(errno));
762 } else {
763 Msg(level, "I/O error"); /*!*/
764 while (err = ERR_get_error()) {
765 ERR_error_string_n(err, error_string, sizeof(error_string));
766 Msg4(level, "SSL_accept(): %s / %s / %s / %s", error_string,
767 ERR_lib_error_string(err), ERR_func_error_string(err),
768 ERR_reason_error_string(err));
770 /* Msg1(level, "SSL_accept(): %s", ERR_error_string(e, buf));*/
772 break;
773 case SSL_ERROR_SSL:
774 /*ERR_print_errors_fp(stderr);*/
775 openssl_SSL_ERROR_SSL(level, "SSL_accept");
776 break;
777 default:
778 Msg(level, "unknown error");
781 return STAT_RETRYLATER;
784 if (openssl_handle_peer_certificate(sfd, opt_commonname, opt_ver, E_ERROR/*!*/) < 0) {
785 return STAT_NORETRY;
788 return STAT_OK;
791 #endif /* WITH_LISTEN */
794 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
795 /* In OpenSSL 0.9.7 compression methods could be added using
796 * SSL_COMP_add_compression_method(3), but the implemntation is not compatible
797 * with the standard (RFC3749).
799 static int openssl_setup_compression(SSL_CTX *ctx, char *method)
801 STACK_OF(SSL_COMP)* comp_methods;
803 assert(method);
805 /* Getting the stack of compression methods has the intended side-effect of
806 * initializing the SSL library's compression part.
808 comp_methods = SSL_COMP_get_compression_methods();
809 if (!comp_methods) {
810 Info("OpenSSL built without compression support");
811 return STAT_OK;
814 if (strcasecmp(method, "auto") == 0) {
815 Info("Using default OpenSSL compression");
816 return STAT_OK;
819 if (strcasecmp(method, "none") == 0) {
820 /* Disable compression */
821 #ifdef SSL_OP_NO_COMPRESSION
822 Info("Disabling OpenSSL compression");
823 SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
824 #else
825 /* SSL_OP_NO_COMPRESSION was only introduced in OpenSSL 0.9.9 (released
826 * as 1.0.0). Removing all compression methods is a work-around for
827 * earlier versions of OpenSSL, but it affects all SSL connections.
829 Info("Disabling OpenSSL compression globally");
830 sk_SSL_COMP_zero(comp_methods);
831 #endif
832 return STAT_OK;
835 /* zlib compression in OpenSSL before version 0.9.8e-beta1 uses the libc's
836 * default malloc/free instead of the ones passed to OpenSSL. Should socat
837 * ever use custom malloc/free functions for OpenSSL, this must be taken
838 * into consideration. See OpenSSL bug #1468.
841 Error1("openssl-compress=\"%s\": unknown compression method", method);
842 return STAT_NORETRY;
844 #endif
847 #if HAVE_CTX_SSL_set_min_proto_version || defined(SSL_CTX_set_min_proto_version) || \
848 HAVE_SSL_CTX_set_max_proto_version || defined(SSL_CTX_set_max_proto_version)
849 #define XIO_OPENSSL_VERSIONGROUP_TLS 1
850 #define XIO_OPENSSL_VERSIONGROUP_DTLS 2
852 static struct wordent _xio_openssl_versions[] = {
853 #ifdef DTLS1_VERSION
854 { "DTLS1", (void *)DTLS1_VERSION },
855 { "DTLS1.0", (void *)DTLS1_VERSION },
856 #endif
857 #ifdef DTLS1_2_VERSION
858 { "DTLS1.2", (void *)DTLS1_2_VERSION },
859 #endif
860 #ifdef DTLS1_VERSION
861 { "DTLSv1", (void *)DTLS1_VERSION },
862 { "DTLSv1.0", (void *)DTLS1_VERSION },
863 #endif
864 #ifdef DTLS1_2_VERSION
865 { "DTLSv1.2", (void *)DTLS1_2_VERSION },
866 #endif
867 #ifdef SSL2_VERSION
868 { "SSL2", (void *)SSL2_VERSION },
869 #endif
870 #ifdef SSL3_VERSION
871 { "SSL3", (void *)SSL3_VERSION },
872 #endif
873 #ifdef SSL2_VERSION
874 { "SSLv2", (void *)SSL2_VERSION },
875 #endif
876 #ifdef SSL3_VERSION
877 { "SSLv3", (void *)SSL3_VERSION },
878 #endif
879 #ifdef TLS1_VERSION
880 { "TLS1", (void *)TLS1_VERSION },
881 { "TLS1.0", (void *)TLS1_VERSION },
882 #endif
883 #ifdef TLS1_1_VERSION
884 { "TLS1.1", (void *)TLS1_1_VERSION },
885 #endif
886 #ifdef TLS1_2_VERSION
887 { "TLS1.2", (void *)TLS1_2_VERSION },
888 #endif
889 #ifdef TLS1_3_VERSION
890 { "TLS1.3", (void *)TLS1_3_VERSION },
891 #endif
892 #ifdef TLS1_VERSION
893 { "TLSv1", (void *)TLS1_VERSION },
894 { "TLSv1.0", (void *)TLS1_VERSION },
895 #endif
896 #ifdef TLS1_1_VERSION
897 { "TLSv1.1", (void *)TLS1_1_VERSION },
898 #endif
899 #ifdef TLS1_2_VERSION
900 { "TLSv1.2", (void *)TLS1_2_VERSION },
901 #endif
902 #ifdef TLS1_3_VERSION
903 { "TLSv1.3", (void *)TLS1_3_VERSION },
904 #endif
907 static int _xio_openssl_parse_version(const char *verstring, int vergroups) {
908 int sslver;
909 const struct wordent *we;
910 we = keyw(_xio_openssl_versions, verstring,
911 sizeof(_xio_openssl_versions)/sizeof(struct wordent));
912 if (we == 0) {
913 Error1("Unknown SSL/TLS version \"%s\"", verstring);
914 return -1;
916 sslver = (size_t)we->desc;
917 switch (sslver) {
918 #ifdef SSL2_VERSION
919 case SSL2_VERSION:
920 #endif
921 #ifdef SSL3_VERSION
922 case SSL3_VERSION:
923 #endif
924 #ifdef TLS1_VERSION
925 case TLS1_VERSION:
926 #endif
927 #ifdef TLS1_1_VERSION
928 case TLS1_1_VERSION:
929 #endif
930 #ifdef TLS1_2_VERSION
931 case TLS1_2_VERSION:
932 #endif
933 #ifdef TLS1_3_VERSION
934 case TLS1_3_VERSION:
935 #endif
936 if (!(vergroups & XIO_OPENSSL_VERSIONGROUP_TLS)) {
937 Error1("Wrong type of TLS/DTLS version \"%s\"", verstring);
938 return -1;
940 #ifdef DTLS1_VERSION
941 case DTLS1_VERSION:
942 #endif
943 #ifdef DTLS1_2_VERSION
944 case DTLS1_2_VERSION:
945 #endif
946 if (!(vergroups & XIO_OPENSSL_VERSIONGROUP_DTLS)) {
947 Error1("Wrong type of TLS/DTLS version \"%s\"", verstring);
948 return -1;
950 break;
952 return sslver;
954 #endif /* defined(SSL_CTX_set_min_proto_version) || defined(SSL_CTX_set_max_proto_version) */
958 _xioopen_openssl_prepare(struct opt *opts,
959 struct single *sfd,/* a xio file descriptor
960 structure, already allocated
962 bool server, /* SSL client: false */
963 bool *opt_ver,
964 const char *opt_cert,
965 SSL_CTX **ctxp,
966 bool *use_dtls) /* checked,overwritten with true if DTLS-method */
968 SSL_CTX *ctx;
969 bool opt_fips = false;
970 const SSL_METHOD *method = NULL;
971 char *me_str = NULL; /* method string */
972 char *ci_str = "HIGH:-NULL:-PSK:-aNULL"; /* cipher string */
973 char *opt_key = NULL; /* file name of client private key */
974 char *opt_dhparam = NULL; /* file name of DH params */
975 char *opt_cafile = NULL; /* certificate authority file */
976 char *opt_capath = NULL; /* certificate authority directory */
977 char *opt_egd = NULL; /* entropy gathering daemon socket path */
978 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
979 char *opt_compress = NULL; /* compression method */
980 #endif
981 bool opt_pseudo = false; /* use pseudo entropy if nothing else */
982 unsigned long err;
983 int result;
985 sfd->dtype = XIODATA_OPENSSL;
987 retropt_bool(opts, OPT_OPENSSL_FIPS, &opt_fips);
988 retropt_string(opts, OPT_OPENSSL_METHOD, &me_str);
989 retropt_string(opts, OPT_OPENSSL_CIPHERLIST, &ci_str);
990 retropt_bool(opts, OPT_OPENSSL_VERIFY, opt_ver);
991 retropt_string(opts, OPT_OPENSSL_CAFILE, &opt_cafile);
992 retropt_string(opts, OPT_OPENSSL_CAPATH, &opt_capath);
993 retropt_string(opts, OPT_OPENSSL_KEY, &opt_key);
994 retropt_string(opts, OPT_OPENSSL_DHPARAM, &opt_dhparam);
995 retropt_string(opts, OPT_OPENSSL_EGD, &opt_egd);
996 retropt_bool(opts,OPT_OPENSSL_PSEUDO, &opt_pseudo);
997 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
998 retropt_string(opts, OPT_OPENSSL_COMPRESS, &opt_compress);
999 #endif
1000 #if WITH_FIPS
1001 if (opt_fips) {
1002 if (!sycFIPS_mode_set(1)) {
1003 ERR_load_crypto_strings();
1004 ERR_print_errors(BIO_new_fp(stderr,BIO_NOCLOSE));
1005 Error("Failed to set FIPS mode");
1006 } else {
1007 xio_openssl_fips = true;
1010 #endif
1012 openssl_delete_cert_info();
1014 /* OpenSSL preparation */
1015 #if defined(HAVE_OPENSSL_INIT_SSL) && defined(HAVE_OPENSSL_INIT_new)
1017 uint64_t opts = 0;
1018 #if defined(OPENSSL_INIT_SETTINGS)
1019 OPENSSL_INIT_SETTINGS *settings;
1020 #else
1021 void *settings;
1022 #endif
1023 settings = OPENSSL_INIT_new();
1024 #ifdef OPENSSL_INIT_NO_ATEXIT
1025 opts |= OPENSSL_INIT_NO_ATEXIT;
1026 #endif
1027 sycOPENSSL_init_ssl(opts, settings);
1029 #else
1030 # if defined(HAVE_SSL_library_init)
1031 sycSSL_library_init();
1032 # endif
1033 OpenSSL_add_all_algorithms();
1034 OpenSSL_add_all_ciphers();
1035 OpenSSL_add_all_digests();
1036 sycSSL_load_error_strings();
1037 #endif /* defined(HAVE_OPENSSL_INIT_SSL) && defined(HAVE OPENSSL_INIT_new) */
1039 /*! actions_to_seed_PRNG();*/
1041 if (!server) {
1042 if (me_str != NULL) {
1043 if (false) {
1044 ; /* for canonical reasons */
1045 #if HAVE_SSLv2_client_method
1046 } else if (!strcasecmp(me_str, "SSL2")) {
1047 method = sycSSLv2_client_method();
1048 #endif
1049 #if HAVE_SSLv3_client_method
1050 } else if (!strcasecmp(me_str, "SSL3")) {
1051 method = sycSSLv3_client_method();
1052 #endif
1053 #if HAVE_SSLv23_client_method
1054 } else if (!strcasecmp(me_str, "SSL23")) {
1055 method = sycSSLv23_client_method();
1056 #endif
1057 #if HAVE_TLSv1_client_method
1058 } else if (!strcasecmp(me_str, "TLS1") || !strcasecmp(me_str, "TLS1.0")) {
1059 method = sycTLSv1_client_method();
1060 #endif
1061 #if HAVE_TLSv1_1_client_method
1062 } else if (!strcasecmp(me_str, "TLS1.1")) {
1063 method = sycTLSv1_1_client_method();
1064 #endif
1065 #if HAVE_TLSv1_2_client_method
1066 } else if (!strcasecmp(me_str, "TLS1.2")) {
1067 method = sycTLSv1_2_client_method();
1068 #endif
1069 #if HAVE_DTLSv1_client_method
1070 } else if (!strcasecmp(me_str, "DTLS1") || !strcasecmp(me_str, "DTLS1.0")) {
1071 method = sycDTLSv1_client_method();
1072 *use_dtls = true;
1073 #endif
1074 #if HAVE_DTLSv1_2_client_method
1075 } else if (!strcasecmp(me_str, "DTLS1.2")) {
1076 method = sycDTLSv1_2_client_method();
1077 *use_dtls = true;
1078 #endif
1079 } else {
1080 Error1("openssl-method=\"%s\": method unknown or not provided by library", me_str);
1082 } else if (!*use_dtls) {
1083 #if HAVE_TLS_client_method
1084 method = sycTLS_client_method();
1085 #elif HAVE_SSLv23_client_method
1086 method = sycSSLv23_client_method();
1087 #elif HAVE_TLSv1_2_client_method
1088 method = sycTLSv1_2_client_method();
1089 #elif HAVE_TLSv1_1_client_method
1090 method = sycTLSv1_1_client_method();
1091 #elif HAVE_TLSv1_client_method
1092 method = sycTLSv1_client_method();
1093 #elif HAVE_SSLv3_client_method
1094 method = sycSSLv3_client_method();
1095 #elif HAVE_SSLv2_client_method
1096 method = sycSSLv2_client_method();
1097 #else
1098 # error "OpenSSL does not seem to provide SSL/TLS client methods"
1099 #endif
1100 } else {
1101 #if HAVE_DTLS_client_method
1102 method = sycDTLS_client_method();
1103 #elif HAVE_DTLSv1_2_client_method
1104 method = sycDTLSv1_2_client_method();
1105 #elif HAVE_DTLSv1_client_method
1106 method = sycDTLSv1_client_method();
1107 #else
1108 # warning "OpenSSL does not seem to provide DTLS client methods"
1109 #endif
1110 *use_dtls = true;
1112 } else /* server */ {
1113 if (me_str != 0) {
1114 if (false) {
1115 ; /* for canonical reasons */
1116 #if HAVE_SSLv2_server_method
1117 } else if (!strcasecmp(me_str, "SSL2")) {
1118 method = sycSSLv2_server_method();
1119 #endif
1120 #if HAVE_SSLv3_server_method
1121 } else if (!strcasecmp(me_str, "SSL3")) {
1122 method = sycSSLv3_server_method();
1123 #endif
1124 #if HAVE_SSLv23_server_method
1125 } else if (!strcasecmp(me_str, "SSL23")) {
1126 method = sycSSLv23_server_method();
1127 #endif
1128 #if HAVE_TLSv1_server_method
1129 } else if (!strcasecmp(me_str, "TLS1") || !strcasecmp(me_str, "TLS1.0")) {
1130 method = sycTLSv1_server_method();
1131 #endif
1132 #if HAVE_TLSv1_1_server_method
1133 } else if (!strcasecmp(me_str, "TLS1.1")) {
1134 method = sycTLSv1_1_server_method();
1135 #endif
1136 #if HAVE_TLSv1_2_server_method
1137 } else if (!strcasecmp(me_str, "TLS1.2")) {
1138 method = sycTLSv1_2_server_method();
1139 #endif
1140 #if HAVE_DTLSv1_server_method
1141 } else if (!strcasecmp(me_str, "DTLS1") || !strcasecmp(me_str, "DTLS1.0")) {
1142 method = sycDTLSv1_server_method();
1143 *use_dtls = true;
1144 #endif
1145 #if HAVE_DTLSv1_2_server_method
1146 } else if (!strcasecmp(me_str, "DTLS1.2")) {
1147 method = sycDTLSv1_2_server_method();
1148 *use_dtls = true;
1149 #endif
1150 } else {
1151 Error1("openssl-method=\"%s\": method unknown or not provided by library", me_str);
1153 } else if (!*use_dtls) {
1154 #if HAVE_TLS_server_method
1155 method = sycTLS_server_method();
1156 #elif HAVE_SSLv23_server_method
1157 method = sycSSLv23_server_method();
1158 #elif HAVE_TLSv1_2_server_method
1159 method = sycTLSv1_2_server_method();
1160 #elif HAVE_TLSv1_1_server_method
1161 method = sycTLSv1_1_server_method();
1162 #elif HAVE_TLSv1_server_method
1163 method = sycTLSv1_server_method();
1164 #elif HAVE_SSLv3_server_method
1165 method = sycSSLv3_server_method();
1166 #elif HAVE_SSLv2_server_method
1167 method = sycSSLv2_server_method();
1168 #else
1169 # error "OpenSSL does not seem to provide SSL/TLS server methods"
1170 #endif
1171 } else {
1172 #if HAVE_DTLS_server_method
1173 method = sycDTLS_server_method();
1174 #elif HAVE_DTLSv1_2_server_method
1175 method = sycDTLSv1_2_server_method();
1176 #elif HAVE_DTLSv1_server_method
1177 method = sycDTLSv1_server_method();
1178 #else
1179 # warning "OpenSSL does not seem to provide DTLS server methods"
1180 #endif
1181 *use_dtls = true;
1185 if (method == NULL) {
1186 Error("no OpenSSL method available");
1187 return STAT_NORETRY;
1190 if (opt_egd) {
1191 #if !defined(OPENSSL_NO_EGD) && HAVE_RAND_egd
1192 sycRAND_egd(opt_egd);
1193 #else
1194 Debug("RAND_egd() is not available by OpenSSL");
1195 #endif
1198 if (opt_pseudo) {
1199 long int randdata;
1200 /* initialize libc random from actual microseconds */
1201 struct timeval tv;
1202 struct timezone tz;
1203 tz.tz_minuteswest = 0;
1204 tz.tz_dsttime = 0;
1205 if ((result = Gettimeofday(&tv, &tz)) < 0) {
1206 Warn2("gettimeofday(%p, {0,0}): %s", &tv, strerror(errno));
1208 srandom(tv.tv_sec*1000000+tv.tv_usec);
1210 while (!RAND_status()) {
1211 randdata = random();
1212 Debug2("RAND_seed(0x{%lx}, "F_Zu")",
1213 randdata, sizeof(randdata));
1214 RAND_seed(&randdata, sizeof(randdata));
1218 if ((ctx = sycSSL_CTX_new(method)) == NULL) {
1219 if (ERR_peek_error() == 0) Error("SSL_CTX_new()");
1220 while (err = ERR_get_error()) {
1221 Error1("SSL_CTX_new(): %s", ERR_error_string(err, NULL));
1224 /*ERR_clear_error;*/
1225 return STAT_RETRYLATER;
1227 sfd->para.openssl.ctx = ctx;
1228 *ctxp = ctx;
1230 #if HAVE_SSL_CTX_set_min_proto_version || defined(SSL_CTX_set_min_proto_version)
1231 if (sfd->para.openssl.min_proto_version != NULL) {
1232 int sslver, rc;
1233 sslver = _xio_openssl_parse_version(sfd->para.openssl.min_proto_version,
1234 XIO_OPENSSL_VERSIONGROUP_TLS|XIO_OPENSSL_VERSIONGROUP_DTLS);
1235 if (sslver < 0)
1236 return STAT_NORETRY;
1237 if ((rc = SSL_CTX_set_min_proto_version(ctx, sslver)) <= 0) {
1238 Debug1("version: %ld", SSL_CTX_get_min_proto_version(ctx));
1239 Error3("_xioopen_openssl_prepare(): SSL_CTX_set_min_proto_version(\"%s\"->%d): failed (%d)",
1240 sfd->para.openssl.min_proto_version, sslver, rc);
1241 return STAT_NORETRY;
1243 Debug1("version: %ld", SSL_CTX_get_min_proto_version(ctx));
1245 #endif /* HAVE_SSL_set_min_proto_version || defined(SSL_set_min_proto_version) */
1246 #if HAVE_SSL_CTX_set_max_proto_version || defined(SSL_CTX_set_max_proto_version)
1247 if (sfd->para.openssl.max_proto_version != NULL) {
1248 int sslver;
1249 sslver = _xio_openssl_parse_version(sfd->para.openssl.max_proto_version,
1250 XIO_OPENSSL_VERSIONGROUP_TLS|XIO_OPENSSL_VERSIONGROUP_DTLS);
1251 if (sslver < 0)
1252 return STAT_NORETRY;
1253 if (SSL_CTX_set_max_proto_version(ctx, sslver) <= 0) {
1254 Error2("_xioopen_openssl_prepare(): SSL_CTX_set_max_proto_version(\"%s\"->%d): failed",
1255 sfd->para.openssl.max_proto_version, sslver);
1256 return STAT_NORETRY;
1259 #endif /* HAVE_SSL_set_max_proto_version || defined(SSL_set_max_proto_version) */
1262 static unsigned char dh2048_p[] = {
1263 0x00,0xdc,0x21,0x64,0x56,0xbd,0x9c,0xb2,0xac,0xbe,0xc9,0x98,0xef,0x95,0x3e,
1264 0x26,0xfa,0xb5,0x57,0xbc,0xd9,0xe6,0x75,0xc0,0x43,0xa2,0x1c,0x7a,0x85,0xdf,
1265 0x34,0xab,0x57,0xa8,0xf6,0xbc,0xf6,0x84,0x7d,0x05,0x69,0x04,0x83,0x4c,0xd5,
1266 0x56,0xd3,0x85,0x09,0x0a,0x08,0xff,0xb5,0x37,0xa1,0xa3,0x8a,0x37,0x04,0x46,
1267 0xd2,0x93,0x31,0x96,0xf4,0xe4,0x0d,0x9f,0xbd,0x3e,0x7f,0x9e,0x4d,0xaf,0x08,
1268 0xe2,0xe8,0x03,0x94,0x73,0xc4,0xdc,0x06,0x87,0xbb,0x6d,0xae,0x66,0x2d,0x18,
1269 0x1f,0xd8,0x47,0x06,0x5c,0xcf,0x8a,0xb5,0x00,0x51,0x57,0x9b,0xea,0x1e,0xd8,
1270 0xdb,0x8e,0x3c,0x1f,0xd3,0x2f,0xba,0x1f,0x5f,0x3d,0x15,0xc1,0x3b,0x2c,0x82,
1271 0x42,0xc8,0x8c,0x87,0x79,0x5b,0x38,0x86,0x3a,0xeb,0xfd,0x81,0xa9,0xba,0xf7,
1272 0x26,0x5b,0x93,0xc5,0x3e,0x03,0x30,0x4b,0x00,0x5c,0xb6,0x23,0x3e,0xea,0x94,
1273 0xc3,0xb4,0x71,0xc7,0x6e,0x64,0x3b,0xf8,0x92,0x65,0xad,0x60,0x6c,0xd4,0x7b,
1274 0xa9,0x67,0x26,0x04,0xa8,0x0a,0xb2,0x06,0xeb,0xe0,0x7d,0x90,0xdd,0xdd,0xf5,
1275 0xcf,0xb4,0x11,0x7c,0xab,0xc1,0xa3,0x84,0xbe,0x27,0x77,0xc7,0xde,0x20,0x57,
1276 0x66,0x47,0xa7,0x35,0xfe,0x0d,0x6a,0x1c,0x52,0xb8,0x58,0xbf,0x26,0x33,0x81,
1277 0x5e,0xb7,0xa9,0xc0,0xee,0x58,0x11,0x74,0x86,0x19,0x08,0x89,0x1c,0x37,0x0d,
1278 0x52,0x47,0x70,0x75,0x8b,0xa8,0x8b,0x30,0x11,0x71,0x36,0x62,0xf0,0x73,0x41,
1279 0xee,0x34,0x9d,0x0a,0x2b,0x67,0x4e,0x6a,0xa3,0xe2,0x99,0x92,0x1b,0xf5,0x32,
1280 0x73,0x63
1282 static unsigned char dh2048_g[] = {
1283 0x02,
1285 DH *dh;
1286 BIGNUM *p = NULL, *g = NULL;
1287 unsigned long err;
1289 dh = DH_new();
1290 p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
1291 g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
1292 if (!dh || !p || !g) {
1293 if (dh)
1294 DH_free(dh);
1295 if (p)
1296 BN_free(p);
1297 if (g)
1298 BN_free(g);
1299 while (err = ERR_get_error()) {
1300 Warn1("dh2048 setup(): %s",
1301 ERR_error_string(err, NULL));
1303 Error("dh2048 setup failed");
1304 goto cont_out;
1306 #if HAVE_DH_set0_pqg
1307 if (!DH_set0_pqg(dh, p, NULL, g)) {
1308 DH_free(dh);
1309 BN_free(p);
1310 BN_free(g);
1311 goto cont_out;
1313 #else
1314 dh->p = p;
1315 dh->g = g;
1316 #endif /* HAVE_DH_set0_pqg */
1317 if (sycSSL_CTX_set_tmp_dh(ctx, dh) <= 0) {
1318 while (err = ERR_get_error()) {
1319 Warn3("SSL_CTX_set_tmp_dh(%p, %p): %s", ctx, dh,
1320 ERR_error_string(err, NULL));
1322 Error2("SSL_CTX_set_tmp_dh(%p, %p) failed", ctx, dh);
1324 /* p & g are freed by DH_free() once attached */
1325 DH_free(dh);
1326 cont_out:
1330 #if HAVE_TYPE_EC_KEY /* not on Openindiana 5.11 */
1332 /* see http://openssl.6102.n7.nabble.com/Problem-with-cipher-suite-ECDHE-ECDSA-AES256-SHA384-td42229.html */
1333 int nid;
1334 EC_KEY *ecdh;
1336 #if 0
1337 nid = OBJ_sn2nid(ECDHE_CURVE);
1338 if (nid == NID_undef) {
1339 Error("openssl: failed to set ECDHE parameters");
1340 return -1;
1342 #endif
1343 nid = NID_X9_62_prime256v1;
1344 ecdh = EC_KEY_new_by_curve_name(nid);
1345 if (NULL == ecdh) {
1346 Error("openssl: failed to set ECDHE parameters");
1347 return -1;
1350 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1352 #endif /* HAVE_TYPE_EC_KEY */
1354 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
1355 if (opt_compress) {
1356 int result;
1357 result = openssl_setup_compression(ctx, opt_compress);
1358 if (result != STAT_OK) {
1359 return result;
1362 #endif
1364 #if defined(HAVE_SSL_CTX_clear_mode) || defined(SSL_CTX_clear_mode)
1365 /* It seems that OpenSSL-1.1.1 presets the mode differently.
1366 Without correction socat might hang in SSL_read() */
1368 long mode = 0;
1369 mode = SSL_CTX_get_mode(ctx);
1370 if (mode & SSL_MODE_AUTO_RETRY) {
1371 Info("SSL_CTX mode has SSL_MODE_AUTO_RETRY set. Correcting..");
1372 Debug1("SSL_CTX_clear_mode(%p, SSL_MODE_AUTO_RETRY)", ctx);
1373 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1376 #endif /* defined(HAVE_SSL_CTX_clear_mode) || defined(SSL_CTX_clear_mode) */
1378 if (opt_cafile != NULL || opt_capath != NULL) {
1379 if (sycSSL_CTX_load_verify_locations(ctx, opt_cafile, opt_capath) != 1) {
1380 int result;
1382 if ((result =
1383 openssl_SSL_ERROR_SSL(E_ERROR, "SSL_CTX_load_verify_locations"))
1384 != STAT_OK) {
1385 /*! free ctx */
1386 return STAT_RETRYLATER;
1389 #ifdef HAVE_SSL_CTX_set_default_verify_paths
1390 } else {
1391 SSL_CTX_set_default_verify_paths(ctx);
1392 #endif
1395 /* set pre openssl-connect options */
1396 /* SSL_CIPHERS */
1397 if (ci_str != NULL) {
1398 if (sycSSL_CTX_set_cipher_list(ctx, ci_str) <= 0) {
1399 if (ERR_peek_error() == 0)
1400 Error1("SSL_set_cipher_list(, \"%s\") failed", ci_str);
1401 while (err = ERR_get_error()) {
1402 Error2("SSL_set_cipher_list(, \"%s\"): %s",
1403 ci_str, ERR_error_string(err, NULL));
1405 /*Error("SSL_new()");*/
1406 return STAT_RETRYLATER;
1410 if (opt_cert) {
1411 BIO *bio;
1412 DH *dh;
1414 if (sycSSL_CTX_use_certificate_chain_file(ctx, opt_cert) <= 0) {
1415 /*! trace functions */
1416 /*0 ERR_print_errors_fp(stderr);*/
1417 if (ERR_peek_error() == 0)
1418 Error2("SSL_CTX_use_certificate_file(%p, \"%s\", SSL_FILETYPE_PEM) failed",
1419 ctx, opt_cert);
1420 while (err = ERR_get_error()) {
1421 Error1("SSL_CTX_use_certificate_file(): %s",
1422 ERR_error_string(err, NULL));
1424 return STAT_RETRYLATER;
1427 if (sycSSL_CTX_use_PrivateKey_file(ctx, opt_key?opt_key:opt_cert, SSL_FILETYPE_PEM) <= 0) {
1428 /*ERR_print_errors_fp(stderr);*/
1429 openssl_SSL_ERROR_SSL(E_ERROR/*!*/, "SSL_CTX_use_PrivateKey_file");
1430 return STAT_RETRYLATER;
1433 if (opt_dhparam == NULL) {
1434 opt_dhparam = (char *)opt_cert;
1436 if ((bio = sycBIO_new_file(opt_dhparam, "r")) == NULL) {
1437 Warn2("BIO_new_file(\"%s\", \"r\"): %s",
1438 opt_dhparam, strerror(errno));
1439 } else {
1440 if ((dh = sycPEM_read_bio_DHparams(bio, NULL, NULL, NULL)) == NULL) {
1441 Info1("PEM_read_bio_DHparams(%p, NULL, NULL, NULL): error", bio);
1442 } else {
1443 BIO_free(bio);
1444 if (sycSSL_CTX_set_tmp_dh(ctx, dh) <= 0) {
1445 while (err = ERR_get_error()) {
1446 Warn3("SSL_CTX_set_tmp_dh(%p, %p): %s", ctx, dh,
1447 ERR_error_string(err, NULL));
1449 Error2("SSL_CTX_set_tmp_dh(%p, %p): error", ctx, dh);
1455 if (*opt_ver) {
1456 sycSSL_CTX_set_verify(ctx,
1457 SSL_VERIFY_PEER| SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1458 NULL);
1459 if (first_child) {
1460 /* The first forked off process, print the warning only once */
1461 Warn("OpenSSL: Warning: this implementation does not check CRLs");
1463 } else {
1464 sycSSL_CTX_set_verify(ctx,
1465 SSL_VERIFY_NONE,
1466 NULL);
1469 #if HAVE_SSL_CTX_set_tlsext_max_fragment_length || defined(SSL_CTX_set_tlsext_max_fragment_length)
1471 /* set client max fragment length negotiation (512, 1024, 2048, or 4096) */
1473 int opt_maxfraglen = -1;
1475 retropt_int(opts, OPT_OPENSSL_MAXFRAGLEN, &opt_maxfraglen);
1477 if (!server) {
1478 /* on client connection, ask the server not to send us packets bigger than our inbound buffer */
1479 uint8_t mfl_code = TLSEXT_max_fragment_length_DISABLED;
1480 if (opt_maxfraglen == -1) {
1481 /* max frag length is not specified, leave DISABLED */
1482 } else if (opt_maxfraglen == 512) {
1483 mfl_code = TLSEXT_max_fragment_length_512;
1484 } else if (opt_maxfraglen == 1024) {
1485 mfl_code = TLSEXT_max_fragment_length_1024;
1486 } else if (opt_maxfraglen == 2048) {
1487 mfl_code = TLSEXT_max_fragment_length_2048;
1488 } else if (opt_maxfraglen == 4096) {
1489 mfl_code = TLSEXT_max_fragment_length_4096;
1490 } else {
1491 Error1("openssl: maxfraglen %d is not one of 512, 1024, 2048, or 4096", opt_maxfraglen);
1492 return STAT_NORETRY;
1495 sycSSL_CTX_set_tlsext_max_fragment_length(ctx, mfl_code);
1496 } else {
1497 if (opt_maxfraglen != -1) {
1498 Error("openssl: maxfraglen option not applicable to a server");
1499 return STAT_NORETRY;
1503 #endif
1505 #if HAVE_SSL_CTX_set_max_send_fragment || defined(SSL_CTX_set_max_send_fragment)
1507 /* limit the maximum size of sent packets */
1508 const int maxsendfrag_min = 512; /* per OpenSSL documentation */
1509 int opt_maxsendfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1511 retropt_int(opts, OPT_OPENSSL_MAXSENDFRAG, &opt_maxsendfrag);
1513 if (opt_maxsendfrag < maxsendfrag_min || opt_maxsendfrag > SSL3_RT_MAX_PLAIN_LENGTH) {
1514 Error2("openssl: maxsendfrag %d out of range 512 - %d", maxsendfrag_min,
1515 SSL3_RT_MAX_PLAIN_LENGTH);
1516 return STAT_NORETRY;
1519 sycSSL_CTX_set_max_send_fragment(ctx, opt_maxsendfrag);
1521 #endif
1523 return STAT_OK;
1527 /* analyses an OpenSSL error condition, prints the appropriate messages with
1528 severity 'level' and returns one of STAT_OK, STAT_RETRYLATER, or
1529 STAT_NORETRY */
1530 static int openssl_SSL_ERROR_SSL(int level, const char *funcname) {
1531 unsigned long e;
1532 char buf[120]; /* this value demanded by "man ERR_error_string" */
1533 int stat = STAT_OK;
1535 while (e = ERR_get_error()) {
1536 Debug1("ERR_get_error(): %lx", e);
1539 #if defined(OPENSSL_IS_BORINGSSL)
1540 0 /* BoringSSL's RNG always succeeds. */
1541 #elif defined(HAVE_RAND_status)
1542 ERR_GET_LIB(e) == ERR_LIB_RAND && RAND_status() != 1
1543 #else
1544 e == ((ERR_LIB_RAND<<24)|
1545 #if defined(RAND_F_RAND_BYTES)
1546 (RAND_F_RAND_BYTES<<12)|
1547 #else
1548 (RAND_F_SSLEAY_RAND_BYTES<<12)|
1549 #endif
1550 (RAND_R_PRNG_NOT_SEEDED)) /*0x24064064*/
1551 #endif
1554 Error("too few entropy; use options \"egd\" or \"pseudo\"");
1555 stat = STAT_NORETRY;
1556 } else {
1557 Msg2(level, "%s(): %s", funcname, ERR_error_string(e, buf));
1558 stat = level==E_ERROR ? STAT_NORETRY : STAT_RETRYLATER;
1561 return stat;
1564 static const char *openssl_verify_messages[] = {
1565 /* 0 */ "ok",
1566 /* 1 */ NULL,
1567 /* 2 */ "unable to get issuer certificate",
1568 /* 3 */ "unable to get certificate CRL",
1569 /* 4 */ "unable to decrypt certificate's signature",
1570 /* 5 */ "unable to decrypt CRL's signature",
1571 /* 6 */ "unable to decode issuer public key",
1572 /* 7 */ "certificate signature failure",
1573 /* 8 */ "CRL signature failure",
1574 /* 9 */ "certificate is not yet valid",
1575 /* 10 */ "certificate has expired",
1576 /* 11 */ "CRL is not yet valid",
1577 /* 12 */ "CRL has expired",
1578 /* 13 */ "format error in certificate's notBefore field",
1579 /* 14 */ "format error in certificate's notAfter field",
1580 /* 15 */ "format error in CRL's lastUpdate field",
1581 /* 16 */ "format error in CRL's nextUpdate field",
1582 /* 17 */ "out of memory",
1583 /* 18 */ "self signed certificate",
1584 /* 19 */ "self signed certificate in certificate chain",
1585 /* 20 */ "unable to get local issuer certificate",
1586 /* 21 */ "unable to verify the first certificate",
1587 /* 22 */ "certificate chain too long",
1588 /* 23 */ "certificate revoked",
1589 /* 24 */ "invalid CA certificate",
1590 /* 25 */ "path length constraint exceeded",
1591 /* 26 */ "unsupported certificate purpose",
1592 /* 27 */ "certificate not trusted",
1593 /* 28 */ "certificate rejected",
1594 /* 29 */ "subject issuer mismatch",
1595 /* 30 */ "authority and subject key identifier mismatch",
1596 /* 31 */ "authority and issuer serial number mismatch",
1597 /* 32 */ "key usage does not include certificate signing",
1598 /* 33 */ NULL,
1599 /* 34 */ NULL,
1600 /* 35 */ NULL,
1601 /* 36 */ NULL,
1602 /* 37 */ NULL,
1603 /* 38 */ NULL,
1604 /* 39 */ NULL,
1605 /* 40 */ NULL,
1606 /* 41 */ NULL,
1607 /* 42 */ NULL,
1608 /* 43 */ NULL,
1609 /* 44 */ NULL,
1610 /* 45 */ NULL,
1611 /* 46 */ NULL,
1612 /* 47 */ NULL,
1613 /* 48 */ NULL,
1614 /* 49 */ NULL,
1615 /* 50 */ "application verification failure",
1619 /* delete all environment variables whose name begins with SOCAT_OPENSSL_
1620 resp. <progname>_OPENSSL_ */
1621 static int openssl_delete_cert_info(void) {
1622 # define XIO_ENVNAMELEN 256
1623 const char *progname;
1624 char envprefix[XIO_ENVNAMELEN];
1625 char envname[XIO_ENVNAMELEN];
1626 size_t i, l;
1627 const char **entry;
1629 progname = diag_get_string('p');
1630 envprefix[0] = '\0'; strncat(envprefix, progname, XIO_ENVNAMELEN-1);
1631 l = strlen(envprefix);
1632 for (i = 0; i < l; ++i) envprefix[i] = toupper((unsigned char)envprefix[i]);
1633 strncat(envprefix+l, "_OPENSSL_", XIO_ENVNAMELEN-l-1);
1635 #if HAVE_VAR_ENVIRON
1636 entry = (const char **)environ;
1637 while (*entry != NULL) {
1638 if (!strncmp(*entry, envprefix, strlen(envprefix))) {
1639 const char *eq = strchr(*entry, '=');
1640 if (eq == NULL) eq = *entry + strlen(*entry);
1641 envname[0] = '\0'; strncat(envname, *entry, eq-*entry);
1642 #if HAVE_UNSETENV
1643 Unsetenv(envname);
1644 #endif
1645 } else {
1646 ++entry;
1649 #endif /* HAVE_VAR_ENVIRON */
1650 return 0;
1653 /* read in the "name" information (from field "issuer" or "subject") and
1654 create environment variable with complete info, eg:
1655 SOCAT_OPENSSL_X509_SUBJECT */
1656 static int openssl_setenv_cert_name(const char *field, X509_NAME *name) {
1657 BIO *bio = BIO_new(BIO_s_mem());
1658 char *buf = NULL, *str;
1659 size_t len;
1660 X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE&~ASN1_STRFLGS_ESC_MSB); /* rc not documented */
1661 len = BIO_get_mem_data (bio, &buf);
1662 if ((str = Malloc(len+1)) == NULL) {
1663 BIO_free(bio);
1664 return -1;
1666 memcpy(str, buf, len);
1667 str[len] = '\0';
1668 Info2("SSL peer cert %s: \"%s\"", field, str);
1669 xiosetenv2("OPENSSL_X509", field, str, 1, NULL);
1670 free(str);
1671 BIO_free(bio);
1672 return 0;
1675 /* read in the "name" information (from field "issuer" or "subject") and
1676 create environment variables with the fields, eg:
1677 SOCAT_OPENSSL_X509_COMMONNAME
1679 static int openssl_setenv_cert_fields(const char *field, X509_NAME *name) {
1680 int n, i;
1681 n = X509_NAME_entry_count(name);
1682 /* extract fields of cert name */
1683 for (i = 0; i < n; ++i) {
1684 X509_NAME_ENTRY *entry;
1685 ASN1_OBJECT *obj;
1686 ASN1_STRING *data;
1687 const unsigned char *text;
1688 int nid;
1689 entry = X509_NAME_get_entry(name, i);
1690 obj = X509_NAME_ENTRY_get_object(entry);
1691 data = X509_NAME_ENTRY_get_data(entry);
1692 nid = OBJ_obj2nid(obj);
1693 #if HAVE_ASN1_STRING_get0_data
1694 text = ASN1_STRING_get0_data(data);
1695 #else
1696 text = ASN1_STRING_data(data);
1697 #endif
1698 Debug3("SSL peer cert %s entry: %s=\"%s\"", (field[0]?field:"subject"), OBJ_nid2ln(nid), text);
1699 if (field != NULL && field[0] != '\0') {
1700 xiosetenv3("OPENSSL_X509", field, OBJ_nid2ln(nid), (const char *)text, 2, " // ");
1701 } else {
1702 xiosetenv2("OPENSSL_X509", OBJ_nid2ln(nid), (const char *)text, 2, " // ");
1705 return 0;
1708 /* compares the peername used/provided by the client to cn as extracted from
1709 the peer certificate.
1710 supports wildcard cn like *.domain which matches domain and
1711 host.domain
1712 returns true on match */
1713 static bool openssl_check_name(const char *nametype, const char *cn, const char *peername) {
1714 const char *dotp;
1715 if (peername == NULL) {
1716 Info2("%s \"%s\": no peername", nametype, cn);
1717 return false;
1718 } else if (peername[0] == '\0') {
1719 Info2("%s \"%s\": matched by empty peername", nametype, cn);
1720 return true;
1722 if (! (cn[0] == '*' && cn[1] == '.')) {
1723 /* normal server name - this is simple */
1724 if (strcmp(cn, peername) == 0) {
1725 Debug3("%s \"%s\" matches peername \"%s\"", nametype, cn, peername);
1726 return true;
1727 } else {
1728 Info3("%s \"%s\" does not match peername \"%s\"", nametype, cn, peername);
1729 return false;
1732 /* wildcard cert */
1733 Debug2("%s \"%s\" is a wildcard name", nametype, cn);
1734 /* case: just the base domain */
1735 if (strcmp(cn+2, peername) == 0) {
1736 Debug3("wildcard %s \"%s\" matches base domain \"%s\"", nametype, cn, peername);
1737 return true;
1739 /* case: subdomain; only one level! */
1740 dotp = strchr(peername, '.');
1741 if (dotp == NULL) {
1742 Info2("peername \"%s\" is not a subdomain, thus is not matched by wildcard commonName \"%s\"",
1743 peername, cn);
1744 return false;
1746 if (strcmp(cn+1, dotp) != 0) {
1747 Info3("%s \"%s\" does not match subdomain peername \"%s\"", nametype, cn, peername);
1748 return false;
1750 Debug3("%s \"%s\" matches subdomain peername \"%s\"", nametype, cn, peername);
1751 return true;
1754 /* retrieves the commonName field and compares it to the peername
1755 returns true on match, false otherwise */
1756 static bool openssl_check_peername(X509_NAME *name, const char *peername) {
1757 int ind = -1;
1758 X509_NAME_ENTRY *entry;
1759 ASN1_STRING *data;
1760 const unsigned char *text;
1761 ind = X509_NAME_get_index_by_NID(name, NID_commonName, -1);
1762 if (ind < 0) {
1763 Info("no COMMONNAME field in peer certificate");
1764 return false;
1766 entry = X509_NAME_get_entry(name, ind);
1767 data = X509_NAME_ENTRY_get_data(entry);
1768 #if HAVE_ASN1_STRING_get0_data
1769 text = ASN1_STRING_get0_data(data);
1770 #else
1771 text = ASN1_STRING_data(data);
1772 #endif
1773 return openssl_check_name("commonName", (const char *)text, peername);
1776 /* retrieves certificate provided by peer, sets env vars containing
1777 certificates field values, and checks peername if provided by
1778 calling function */
1779 /* parts of this code were copied from Gene Spaffords C/C++ Secure Programming at Etutorials.org:
1780 http://etutorials.org/Programming/secure+programming/Chapter+10.+Public+Key+Infrastructure/10.8+Adding+Hostname+Checking+to+Certificate+Verification/
1781 The code examples in this tutorial do not seem to have explicit license restrictions.
1783 /* peername is, with OpenSSL client, the server name, or the value of option
1784 commonname if provided;
1785 With OpenSSL server, it is the value of option commonname */
1786 static int openssl_handle_peer_certificate(struct single *sfd,
1787 const char *peername,
1788 bool opt_ver, int level) {
1789 X509 *peer_cert;
1790 X509_NAME *subjectname, *issuername;
1791 /*ASN1_TIME not_before, not_after;*/
1792 int extcount, i, ok = 0;
1793 int status;
1795 if ((peer_cert = SSL_get_peer_certificate(sfd->para.openssl.ssl)) == NULL) {
1796 if (opt_ver) {
1797 Msg(level, "no peer certificate");
1798 status = STAT_RETRYLATER;
1799 } else {
1800 Notice("no peer certificate and no check");
1801 status = STAT_OK;
1803 return status;
1806 /* verify peer certificate (trust, signature, validity dates) */
1807 if (opt_ver) {
1808 long verify_result;
1809 if ((verify_result = sycSSL_get_verify_result(sfd->para.openssl.ssl)) != X509_V_OK) {
1810 const char *message = NULL;
1811 if (verify_result >= 0 &&
1812 (size_t)verify_result <
1813 sizeof(openssl_verify_messages)/sizeof(char*)) {
1814 message = openssl_verify_messages[verify_result];
1816 if (message) {
1817 Msg1(level, "%s", message);
1818 } else {
1819 Msg1(level, "rejected peer certificate with error %ld", verify_result);
1821 status = STAT_RETRYLATER;
1822 X509_free(peer_cert);
1823 return STAT_RETRYLATER;
1825 Info("peer certificate is trusted");
1828 /* set env vars from cert's subject and issuer values */
1829 if ((subjectname = X509_get_subject_name(peer_cert)) != NULL) {
1830 openssl_setenv_cert_name("subject", subjectname);
1831 openssl_setenv_cert_fields("", subjectname);
1832 /*! I'd like to provide dates too; see
1833 http://markmail.org/message/yi4vspp7aeu3xwtu#query:+page:1+mid:jhnl4wklif3pgzqf+state:results */
1835 if ((issuername = X509_get_issuer_name(peer_cert)) != NULL) {
1836 openssl_setenv_cert_name("issuer", issuername);
1839 if (!opt_ver) {
1840 Notice("option openssl-verify disabled, no check of certificate");
1841 X509_free(peer_cert);
1842 return STAT_OK;
1845 /* check peername against cert's subjectAltName DNS entries */
1846 /* this code is based on example from Gerhard Gappmeier in
1847 http://openssl.6102.n7.nabble.com/How-to-extract-subjectAltName-td17236.html
1848 and the GEN_IPADD from
1849 http://openssl.6102.n7.nabble.com/reading-IP-addresses-from-Subject-Alternate-Name-extension-td29245.html
1851 if ((extcount = X509_get_ext_count(peer_cert)) > 0) {
1852 for (i = 0; !ok && i < extcount; ++i) {
1853 const char *extstr;
1854 X509_EXTENSION *ext;
1855 const X509V3_EXT_METHOD *meth;
1856 ext = X509_get_ext(peer_cert, i);
1857 extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
1858 if (!strcasecmp(extstr, "subjectAltName")) {
1859 void *names;
1860 if (!(meth = X509V3_EXT_get(ext))) break;
1861 names = X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
1862 if (names) {
1863 int numalts;
1864 int i;
1866 /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */
1867 numalts = sk_GENERAL_NAME_num ( names );
1868 /* loop through all alternatives */
1869 for (i = 0; i < numalts; ++i) {
1870 /* get a handle to alternative name number i */
1871 const GENERAL_NAME *pName = sk_GENERAL_NAME_value (names, i);
1872 unsigned char *pBuffer;
1873 switch (pName->type) {
1875 case GEN_DNS:
1876 ASN1_STRING_to_UTF8(&pBuffer, pName->d.ia5);
1877 xiosetenv("OPENSSL_X509V3_SUBJECTALTNAME_DNS", (char *)pBuffer, 2, " // ");
1878 if (peername != NULL &&
1879 openssl_check_name("subjectAltName", (char *)pBuffer, /*const char*/peername)) {
1880 ok = 1;
1882 OPENSSL_free(pBuffer);
1883 break;
1885 case GEN_IPADD:
1887 /* binary address format */
1888 const unsigned char *data = pName->d.iPAddress->data;
1889 size_t len = pName->d.iPAddress->length;
1890 char aBuffer[INET6_ADDRSTRLEN]; /* canonical peername */
1891 struct in6_addr ip6bin;
1893 switch (len) {
1894 case 4: /* IPv4 */
1895 snprintf(aBuffer, sizeof(aBuffer), "%u.%u.%u.%u", data[0], data[1], data[2], data[3]);
1896 if (peername != NULL &&
1897 openssl_check_name("subjectAltName", aBuffer, /*const char*/peername)) {
1898 ok = 1;
1900 break;
1901 #if WITH_IP6
1902 case 16: /* IPv6 */
1903 inet_ntop(AF_INET6, data, aBuffer, sizeof(aBuffer));
1904 if (peername != NULL) {
1905 xioip6_pton(peername, &ip6bin, sfd->para.socket.ip.ai_flags);
1906 if (memcmp(data, &ip6bin, sizeof(ip6bin)) == 0) {
1907 Debug2("subjectAltName \"%s\" matches peername \"%s\"",
1908 aBuffer, peername);
1909 ok = 1;
1910 } else {
1911 Info2("subjectAltName \"%s\" does not match peername \"%s\"",
1912 aBuffer, peername);
1915 break;
1916 #endif
1918 xiosetenv("OPENSSL_X509V3_SUBJECTALTNAME_IPADD", (char *)aBuffer, 2, " // ");
1920 break;
1921 default: Warn3("Unknown subject type %d (GEN_DNS=%d, GEN_IPADD=%d",
1922 pName->type, GEN_DNS, GEN_IPADD);
1923 continue;
1925 if (ok) { break; }
1932 if (ok) {
1933 Notice("trusting certificate, commonName matches");
1934 X509_free(peer_cert);
1935 return STAT_OK;
1938 if (peername == NULL || peername[0] == '\0') {
1939 Notice("trusting certificate, no check of commonName");
1940 X509_free(peer_cert);
1941 return STAT_OK;
1944 /* here: all envs set; opt_ver, cert verified, no subjAltName match -> check subject CN */
1945 if (!openssl_check_peername(/*X509_NAME*/subjectname, /*const char*/peername)) {
1946 Error1("certificate is valid but its commonName does not match hostname \"%s\"",
1947 peername);
1948 status = STAT_NORETRY;
1949 } else {
1950 Notice("trusting certificate, commonName matches");
1951 status = STAT_OK;
1953 X509_free(peer_cert);
1954 return status;
1957 static int xioSSL_set_fd(struct single *sfd, int level) {
1958 unsigned long err;
1960 /* assign a network connection to the SSL object */
1961 if (sycSSL_set_fd(sfd->para.openssl.ssl, sfd->fd) <= 0) {
1962 Msg(level, "SSL_set_fd() failed");
1963 while (err = ERR_get_error()) {
1964 Msg2(level, "SSL_set_fd(, %d): %s",
1965 sfd->fd, ERR_error_string(err, NULL));
1967 return STAT_RETRYLATER;
1969 return STAT_OK;
1973 /* ...
1974 in case of an error condition, this function check forever and retry
1975 options and ev. sleeps an interval. It returns NORETRY when the caller
1976 should not retry for any reason. */
1977 static int xioSSL_connect(struct single *sfd, const char *opt_commonname,
1978 bool opt_ver, int level) {
1979 char error_string[120];
1980 int errint, status, ret;
1981 unsigned long err;
1983 /* connect via SSL by performing handshake */
1984 if ((ret = sycSSL_connect(sfd->para.openssl.ssl)) <= 0) {
1985 /*if (ERR_peek_error() == 0) Msg(level, "SSL_connect() failed");*/
1986 errint = SSL_get_error(sfd->para.openssl.ssl, ret);
1987 switch (errint) {
1988 case SSL_ERROR_NONE:
1989 /* this is not an error, but I dare not continue for security reasons*/
1990 Msg(level, "ok");
1991 status = STAT_RETRYLATER;
1992 case SSL_ERROR_ZERO_RETURN:
1993 Msg(level, "connection closed (wrong version number?)");
1994 status = STAT_RETRYLATER;
1995 break;
1996 case SSL_ERROR_WANT_READ:
1997 case SSL_ERROR_WANT_WRITE:
1998 case SSL_ERROR_WANT_CONNECT:
1999 case SSL_ERROR_WANT_X509_LOOKUP:
2000 Msg(level, "nonblocking operation did not complete");
2001 status = STAT_RETRYLATER;
2002 break; /*!*/
2003 case SSL_ERROR_SYSCALL:
2004 if (ERR_peek_error() == 0) {
2005 if (ret == 0) {
2006 Msg(level, "SSL_connect(): socket closed by peer");
2007 } else if (ret == -1) {
2008 Msg1(level, "SSL_connect(): %s", strerror(errno));
2010 } else {
2011 Msg(level, "I/O error"); /*!*/
2012 while (err = ERR_get_error()) {
2013 ERR_error_string_n(err, error_string, sizeof(error_string));
2014 Msg4(level, "SSL_connect(): %s / %s / %s / %s", error_string,
2015 ERR_lib_error_string(err), ERR_func_error_string(err),
2016 ERR_reason_error_string(err));
2019 status = STAT_RETRYLATER;
2020 break;
2021 case SSL_ERROR_SSL:
2022 status = openssl_SSL_ERROR_SSL(level, "SSL_connect");
2023 if (openssl_handle_peer_certificate(sfd, opt_commonname, opt_ver, level/*!*/) < 0) {
2024 return STAT_RETRYLATER;
2026 break;
2027 default:
2028 Msg(level, "unknown error");
2029 status = STAT_RETRYLATER;
2030 break;
2032 return status;
2034 return STAT_OK;
2037 /* on result < 0: errno is set (at least to EIO) */
2038 ssize_t xioread_openssl(struct single *pipe, void *buff, size_t bufsiz) {
2039 unsigned long err;
2040 char error_string[120];
2041 int _errno = EIO; /* if we have no better idea about nature of error */
2042 int errint, ret;
2044 ret = sycSSL_read(pipe->para.openssl.ssl, buff, bufsiz);
2045 if (ret < 0) {
2046 errint = SSL_get_error(pipe->para.openssl.ssl, ret);
2047 switch (errint) {
2048 case SSL_ERROR_NONE:
2049 /* this is not an error, but I dare not continue for security reasons*/
2050 Error("ok");
2051 break;
2052 case SSL_ERROR_ZERO_RETURN:
2053 Error("connection closed by peer");
2054 break;
2055 case SSL_ERROR_WANT_READ:
2056 case SSL_ERROR_WANT_WRITE:
2057 case SSL_ERROR_WANT_CONNECT:
2058 case SSL_ERROR_WANT_X509_LOOKUP:
2059 Info("nonblocking operation did not complete");
2060 errno = EAGAIN;
2061 return -1;
2062 case SSL_ERROR_SYSCALL:
2063 if (ERR_peek_error() == 0) {
2064 if (ret == 0) {
2065 Error("SSL_read(): socket closed by peer");
2066 } else if (ret == -1) {
2067 _errno = errno;
2068 Error1("SSL_read(): %s", strerror(errno));
2070 } else {
2071 Error("I/O error"); /*!*/
2072 while (err = ERR_get_error()) {
2073 ERR_error_string_n(err, error_string, sizeof(error_string));
2074 Error4("SSL_read(): %s / %s / %s / %s", error_string,
2075 ERR_lib_error_string(err), ERR_func_error_string(err),
2076 ERR_reason_error_string(err));
2079 break;
2080 case SSL_ERROR_SSL:
2081 openssl_SSL_ERROR_SSL(E_ERROR, "SSL_read");
2082 break;
2083 default:
2084 Error("unknown error");
2085 break;
2087 errno = _errno;
2088 return -1;
2090 return ret;
2093 ssize_t xiopending_openssl(struct single *pipe) {
2094 int bytes = sycSSL_pending(pipe->para.openssl.ssl);
2095 return bytes;
2098 /* on result < 0: errno is set (at least to EIO) */
2099 ssize_t xiowrite_openssl(struct single *pipe, const void *buff, size_t bufsiz) {
2100 unsigned long err;
2101 char error_string[120];
2102 int _errno = EIO; /* if we have no better idea about nature of error */
2103 int errint, ret;
2105 ret = sycSSL_write(pipe->para.openssl.ssl, buff, bufsiz);
2106 if (ret < 0) {
2107 errint = SSL_get_error(pipe->para.openssl.ssl, ret);
2108 switch (errint) {
2109 case SSL_ERROR_NONE:
2110 /* this is not an error, but I dare not continue for security reasons*/
2111 Error("ok");
2112 case SSL_ERROR_ZERO_RETURN:
2113 Error("connection closed by peer");
2114 break;
2115 case SSL_ERROR_WANT_READ:
2116 case SSL_ERROR_WANT_WRITE:
2117 case SSL_ERROR_WANT_CONNECT:
2118 case SSL_ERROR_WANT_X509_LOOKUP:
2119 Error("nonblocking operation did not complete");
2120 break; /*!*/
2121 case SSL_ERROR_SYSCALL:
2122 if (ERR_peek_error() == 0) {
2123 if (ret == 0) {
2124 Error("SSL_write(): socket closed by peer");
2125 } else if (ret == -1) {
2126 _errno = errno;
2127 Error1("SSL_write(): %s", strerror(errno));
2129 } else {
2130 Error("I/O error"); /*!*/
2131 while (err = ERR_get_error()) {
2132 ERR_error_string_n(err, error_string, sizeof(error_string));
2133 Error4("SSL_write(): %s / %s / %s / %s", error_string,
2134 ERR_lib_error_string(err), ERR_func_error_string(err),
2135 ERR_reason_error_string(err));
2138 break;
2139 case SSL_ERROR_SSL:
2140 openssl_SSL_ERROR_SSL(E_ERROR, "SSL_write");
2141 break;
2142 default:
2143 Error("unknown error");
2144 break;
2146 errno = _errno;
2147 return -1;
2149 return ret;
2152 int xioshutdown_openssl(struct single *sfd, int how)
2154 int rc;
2156 if ((rc = sycSSL_shutdown(sfd->para.openssl.ssl)) < 0) {
2157 Warn1("xioshutdown_openssl(): SSL_shutdown() -> %d", rc);
2159 if (sfd->tag == XIO_TAG_WRONLY) {
2160 char buff[1];
2161 /* give peer time to read all data before closing socket */
2162 xioread_openssl(sfd, buff, 1);
2164 return 0;
2167 #endif /* WITH_OPENSSL */