]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/s_server.c
Copyright year updates
[thirdparty/openssl.git] / apps / s_server.c
1 /*
2 * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
5 *
6 * Licensed under the Apache License 2.0 (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
10 */
11
12 #include <ctype.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #if defined(_WIN32)
17 /* Included before async.h to avoid some warnings */
18 # include <windows.h>
19 #endif
20
21 #include <openssl/e_os2.h>
22 #include <openssl/async.h>
23 #include <openssl/ssl.h>
24 #include <openssl/decoder.h>
25
26 #ifndef OPENSSL_NO_SOCK
27
28 /*
29 * With IPv6, it looks like Digital has mixed up the proper order of
30 * recursive header file inclusion, resulting in the compiler complaining
31 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
32 * needed to have fileno() declared correctly... So let's define u_int
33 */
34 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
35 # define __U_INT
36 typedef unsigned int u_int;
37 #endif
38
39 #include <openssl/bn.h>
40 #include "apps.h"
41 #include "progs.h"
42 #include <openssl/err.h>
43 #include <openssl/pem.h>
44 #include <openssl/x509.h>
45 #include <openssl/rand.h>
46 #include <openssl/ocsp.h>
47 #ifndef OPENSSL_NO_DH
48 # include <openssl/dh.h>
49 #endif
50 #include <openssl/rsa.h>
51 #include "s_apps.h"
52 #include "timeouts.h"
53 #ifdef CHARSET_EBCDIC
54 #include <openssl/ebcdic.h>
55 #endif
56 #include "internal/sockets.h"
57
58 static int not_resumable_sess_cb(SSL *s, int is_forward_secure);
59 static int sv_body(int s, int stype, int prot, unsigned char *context);
60 static int www_body(int s, int stype, int prot, unsigned char *context);
61 static int rev_body(int s, int stype, int prot, unsigned char *context);
62 static void close_accept_socket(void);
63 static int init_ssl_connection(SSL *s);
64 static void print_stats(BIO *bp, SSL_CTX *ctx);
65 static int generate_session_id(SSL *ssl, unsigned char *id,
66 unsigned int *id_len);
67 static void init_session_cache_ctx(SSL_CTX *sctx);
68 static void free_sessions(void);
69 static void print_connection_info(SSL *con);
70
71 static const int bufsize = 16 * 1024;
72 static int accept_socket = -1;
73
74 #define TEST_CERT "server.pem"
75 #define TEST_CERT2 "server2.pem"
76
77 static int s_nbio = 0;
78 static int s_nbio_test = 0;
79 static int s_crlf = 0;
80 static SSL_CTX *ctx = NULL;
81 static SSL_CTX *ctx2 = NULL;
82 static int www = 0;
83
84 static BIO *bio_s_out = NULL;
85 static BIO *bio_s_msg = NULL;
86 static int s_debug = 0;
87 static int s_tlsextdebug = 0;
88 static int s_msg = 0;
89 static int s_quiet = 0;
90 static int s_ign_eof = 0;
91 static int s_brief = 0;
92
93 static char *keymatexportlabel = NULL;
94 static int keymatexportlen = 20;
95
96 static int async = 0;
97
98 static int use_sendfile = 0;
99 static int use_zc_sendfile = 0;
100
101 static const char *session_id_prefix = NULL;
102
103 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
104 static int enable_client_rpk = 0;
105
106 #ifndef OPENSSL_NO_DTLS
107 static int enable_timeouts = 0;
108 static long socket_mtu;
109 #endif
110
111 /*
112 * We define this but make it always be 0 in no-dtls builds to simplify the
113 * code.
114 */
115 static int dtlslisten = 0;
116 static int stateless = 0;
117
118 static int early_data = 0;
119 static SSL_SESSION *psksess = NULL;
120
121 static char *psk_identity = "Client_identity";
122 char *psk_key = NULL; /* by default PSK is not used */
123
124 static char http_server_binmode = 0; /* for now: 0/1 = default/binary */
125
126 #ifndef OPENSSL_NO_PSK
127 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
128 unsigned char *psk,
129 unsigned int max_psk_len)
130 {
131 long key_len = 0;
132 unsigned char *key;
133
134 if (s_debug)
135 BIO_printf(bio_s_out, "psk_server_cb\n");
136
137 if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) {
138 /*
139 * This callback is designed for use in (D)TLSv1.2 (or below). It is
140 * possible to use a single callback for all protocol versions - but it
141 * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we
142 * have psk_find_session_cb.
143 */
144 return 0;
145 }
146
147 if (identity == NULL) {
148 BIO_printf(bio_err, "Error: client did not send PSK identity\n");
149 goto out_err;
150 }
151 if (s_debug)
152 BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
153 (int)strlen(identity), identity);
154
155 /* here we could lookup the given identity e.g. from a database */
156 if (strcmp(identity, psk_identity) != 0) {
157 BIO_printf(bio_s_out, "PSK warning: client identity not what we expected"
158 " (got '%s' expected '%s')\n", identity, psk_identity);
159 } else {
160 if (s_debug)
161 BIO_printf(bio_s_out, "PSK client identity found\n");
162 }
163
164 /* convert the PSK key to binary */
165 key = OPENSSL_hexstr2buf(psk_key, &key_len);
166 if (key == NULL) {
167 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
168 psk_key);
169 return 0;
170 }
171 if (key_len > (int)max_psk_len) {
172 BIO_printf(bio_err,
173 "psk buffer of callback is too small (%d) for key (%ld)\n",
174 max_psk_len, key_len);
175 OPENSSL_free(key);
176 return 0;
177 }
178
179 memcpy(psk, key, key_len);
180 OPENSSL_free(key);
181
182 if (s_debug)
183 BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len);
184 return key_len;
185 out_err:
186 if (s_debug)
187 BIO_printf(bio_err, "Error in PSK server callback\n");
188 (void)BIO_flush(bio_err);
189 (void)BIO_flush(bio_s_out);
190 return 0;
191 }
192 #endif
193
194 static int psk_find_session_cb(SSL *ssl, const unsigned char *identity,
195 size_t identity_len, SSL_SESSION **sess)
196 {
197 SSL_SESSION *tmpsess = NULL;
198 unsigned char *key;
199 long key_len;
200 const SSL_CIPHER *cipher = NULL;
201
202 if (strlen(psk_identity) != identity_len
203 || memcmp(psk_identity, identity, identity_len) != 0) {
204 *sess = NULL;
205 return 1;
206 }
207
208 if (psksess != NULL) {
209 SSL_SESSION_up_ref(psksess);
210 *sess = psksess;
211 return 1;
212 }
213
214 key = OPENSSL_hexstr2buf(psk_key, &key_len);
215 if (key == NULL) {
216 BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
217 psk_key);
218 return 0;
219 }
220
221 /* We default to SHA256 */
222 cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id);
223 if (cipher == NULL) {
224 BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
225 OPENSSL_free(key);
226 return 0;
227 }
228
229 tmpsess = SSL_SESSION_new();
230 if (tmpsess == NULL
231 || !SSL_SESSION_set1_master_key(tmpsess, key, key_len)
232 || !SSL_SESSION_set_cipher(tmpsess, cipher)
233 || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) {
234 OPENSSL_free(key);
235 SSL_SESSION_free(tmpsess);
236 return 0;
237 }
238 OPENSSL_free(key);
239 *sess = tmpsess;
240
241 return 1;
242 }
243
244 #ifndef OPENSSL_NO_SRP
245 static srpsrvparm srp_callback_parm;
246 #endif
247
248 static int local_argc = 0;
249 static char **local_argv;
250
251 #ifdef CHARSET_EBCDIC
252 static int ebcdic_new(BIO *bi);
253 static int ebcdic_free(BIO *a);
254 static int ebcdic_read(BIO *b, char *out, int outl);
255 static int ebcdic_write(BIO *b, const char *in, int inl);
256 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
257 static int ebcdic_gets(BIO *bp, char *buf, int size);
258 static int ebcdic_puts(BIO *bp, const char *str);
259
260 # define BIO_TYPE_EBCDIC_FILTER (18|0x0200)
261 static BIO_METHOD *methods_ebcdic = NULL;
262
263 /* This struct is "unwarranted chumminess with the compiler." */
264 typedef struct {
265 size_t alloced;
266 char buff[1];
267 } EBCDIC_OUTBUFF;
268
269 static const BIO_METHOD *BIO_f_ebcdic_filter(void)
270 {
271 if (methods_ebcdic == NULL) {
272 methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER,
273 "EBCDIC/ASCII filter");
274 if (methods_ebcdic == NULL
275 || !BIO_meth_set_write(methods_ebcdic, ebcdic_write)
276 || !BIO_meth_set_read(methods_ebcdic, ebcdic_read)
277 || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts)
278 || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets)
279 || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl)
280 || !BIO_meth_set_create(methods_ebcdic, ebcdic_new)
281 || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free))
282 return NULL;
283 }
284 return methods_ebcdic;
285 }
286
287 static int ebcdic_new(BIO *bi)
288 {
289 EBCDIC_OUTBUFF *wbuf;
290
291 wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf");
292 wbuf->alloced = 1024;
293 wbuf->buff[0] = '\0';
294
295 BIO_set_data(bi, wbuf);
296 BIO_set_init(bi, 1);
297 return 1;
298 }
299
300 static int ebcdic_free(BIO *a)
301 {
302 EBCDIC_OUTBUFF *wbuf;
303
304 if (a == NULL)
305 return 0;
306 wbuf = BIO_get_data(a);
307 OPENSSL_free(wbuf);
308 BIO_set_data(a, NULL);
309 BIO_set_init(a, 0);
310
311 return 1;
312 }
313
314 static int ebcdic_read(BIO *b, char *out, int outl)
315 {
316 int ret = 0;
317 BIO *next = BIO_next(b);
318
319 if (out == NULL || outl == 0)
320 return 0;
321 if (next == NULL)
322 return 0;
323
324 ret = BIO_read(next, out, outl);
325 if (ret > 0)
326 ascii2ebcdic(out, out, ret);
327 return ret;
328 }
329
330 static int ebcdic_write(BIO *b, const char *in, int inl)
331 {
332 EBCDIC_OUTBUFF *wbuf;
333 BIO *next = BIO_next(b);
334 int ret = 0;
335 int num;
336
337 if ((in == NULL) || (inl <= 0))
338 return 0;
339 if (next == NULL)
340 return 0;
341
342 wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b);
343
344 if (inl > (num = wbuf->alloced)) {
345 num = num + num; /* double the size */
346 if (num < inl)
347 num = inl;
348 OPENSSL_free(wbuf);
349 wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf");
350
351 wbuf->alloced = num;
352 wbuf->buff[0] = '\0';
353
354 BIO_set_data(b, wbuf);
355 }
356
357 ebcdic2ascii(wbuf->buff, in, inl);
358
359 ret = BIO_write(next, wbuf->buff, inl);
360
361 return ret;
362 }
363
364 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
365 {
366 long ret;
367 BIO *next = BIO_next(b);
368
369 if (next == NULL)
370 return 0;
371 switch (cmd) {
372 case BIO_CTRL_DUP:
373 ret = 0L;
374 break;
375 default:
376 ret = BIO_ctrl(next, cmd, num, ptr);
377 break;
378 }
379 return ret;
380 }
381
382 static int ebcdic_gets(BIO *bp, char *buf, int size)
383 {
384 int i, ret = 0;
385 BIO *next = BIO_next(bp);
386
387 if (next == NULL)
388 return 0;
389 /* return(BIO_gets(bp->next_bio,buf,size));*/
390 for (i = 0; i < size - 1; ++i) {
391 ret = ebcdic_read(bp, &buf[i], 1);
392 if (ret <= 0)
393 break;
394 else if (buf[i] == '\n') {
395 ++i;
396 break;
397 }
398 }
399 if (i < size)
400 buf[i] = '\0';
401 return (ret < 0 && i == 0) ? ret : i;
402 }
403
404 static int ebcdic_puts(BIO *bp, const char *str)
405 {
406 if (BIO_next(bp) == NULL)
407 return 0;
408 return ebcdic_write(bp, str, strlen(str));
409 }
410 #endif
411
412 /* This is a context that we pass to callbacks */
413 typedef struct tlsextctx_st {
414 char *servername;
415 BIO *biodebug;
416 int extension_error;
417 } tlsextctx;
418
419 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
420 {
421 tlsextctx *p = (tlsextctx *) arg;
422 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
423
424 if (servername != NULL && p->biodebug != NULL) {
425 const char *cp = servername;
426 unsigned char uc;
427
428 BIO_printf(p->biodebug, "Hostname in TLS extension: \"");
429 while ((uc = *cp++) != 0)
430 BIO_printf(p->biodebug,
431 (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc);
432 BIO_printf(p->biodebug, "\"\n");
433 }
434
435 if (p->servername == NULL)
436 return SSL_TLSEXT_ERR_NOACK;
437
438 if (servername != NULL) {
439 if (OPENSSL_strcasecmp(servername, p->servername))
440 return p->extension_error;
441 if (ctx2 != NULL) {
442 BIO_printf(p->biodebug, "Switching server context.\n");
443 SSL_set_SSL_CTX(s, ctx2);
444 }
445 }
446 return SSL_TLSEXT_ERR_OK;
447 }
448
449 /* Structure passed to cert status callback */
450 typedef struct tlsextstatusctx_st {
451 int timeout;
452 /* File to load OCSP Response from (or NULL if no file) */
453 char *respin;
454 /* Default responder to use */
455 char *host, *path, *port;
456 char *proxy, *no_proxy;
457 int use_ssl;
458 int verbose;
459 } tlsextstatusctx;
460
461 static tlsextstatusctx tlscstatp = { -1 };
462
463 #ifndef OPENSSL_NO_OCSP
464
465 /*
466 * Helper function to get an OCSP_RESPONSE from a responder. This is a
467 * simplified version. It examines certificates each time and makes one OCSP
468 * responder query for each request. A full version would store details such as
469 * the OCSP certificate IDs and minimise the number of OCSP responses by caching
470 * them until they were considered "expired".
471 */
472 static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx,
473 OCSP_RESPONSE **resp)
474 {
475 char *host = NULL, *port = NULL, *path = NULL;
476 char *proxy = NULL, *no_proxy = NULL;
477 int use_ssl;
478 STACK_OF(OPENSSL_STRING) *aia = NULL;
479 X509 *x = NULL, *cert;
480 X509_NAME *iname;
481 STACK_OF(X509) *chain = NULL;
482 SSL_CTX *ssl_ctx;
483 X509_STORE_CTX *inctx = NULL;
484 X509_OBJECT *obj;
485 OCSP_REQUEST *req = NULL;
486 OCSP_CERTID *id = NULL;
487 STACK_OF(X509_EXTENSION) *exts;
488 int ret = SSL_TLSEXT_ERR_NOACK;
489 int i;
490
491 /* Build up OCSP query from server certificate */
492 x = SSL_get_certificate(s);
493 iname = X509_get_issuer_name(x);
494 aia = X509_get1_ocsp(x);
495 if (aia != NULL) {
496 if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl,
497 NULL, &host, &port, NULL, &path, NULL, NULL)) {
498 BIO_puts(bio_err, "cert_status: can't parse AIA URL\n");
499 goto err;
500 }
501 if (srctx->verbose)
502 BIO_printf(bio_err, "cert_status: AIA URL: %s\n",
503 sk_OPENSSL_STRING_value(aia, 0));
504 } else {
505 if (srctx->host == NULL) {
506 BIO_puts(bio_err,
507 "cert_status: no AIA and no default responder URL\n");
508 goto done;
509 }
510 host = srctx->host;
511 path = srctx->path;
512 port = srctx->port;
513 use_ssl = srctx->use_ssl;
514 }
515 proxy = srctx->proxy;
516 no_proxy = srctx->no_proxy;
517
518 ssl_ctx = SSL_get_SSL_CTX(s);
519 if (!SSL_CTX_get0_chain_certs(ssl_ctx, &chain))
520 goto err;
521 for (i = 0; i < sk_X509_num(chain); i++) {
522 /* check the untrusted certificate chain (-cert_chain option) */
523 cert = sk_X509_value(chain, i);
524 if (X509_name_cmp(iname, X509_get_subject_name(cert)) == 0) {
525 /* the issuer certificate is found */
526 id = OCSP_cert_to_id(NULL, x, cert);
527 break;
528 }
529 }
530 if (id == NULL) {
531 inctx = X509_STORE_CTX_new();
532 if (inctx == NULL)
533 goto err;
534 if (!X509_STORE_CTX_init(inctx, SSL_CTX_get_cert_store(ssl_ctx),
535 NULL, NULL))
536 goto err;
537 obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509, iname);
538 if (obj == NULL) {
539 BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n");
540 goto done;
541 }
542 id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj));
543 X509_OBJECT_free(obj);
544 }
545 if (id == NULL)
546 goto err;
547 req = OCSP_REQUEST_new();
548 if (req == NULL)
549 goto err;
550 if (!OCSP_request_add0_id(req, id))
551 goto err;
552 id = NULL;
553 /* Add any extensions to the request */
554 SSL_get_tlsext_status_exts(s, &exts);
555 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
556 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
557 if (!OCSP_REQUEST_add_ext(req, ext, -1))
558 goto err;
559 }
560 *resp = process_responder(req, host, port, path, proxy, no_proxy,
561 use_ssl, NULL /* headers */, srctx->timeout);
562 if (*resp == NULL) {
563 BIO_puts(bio_err, "cert_status: error querying responder\n");
564 goto done;
565 }
566
567 ret = SSL_TLSEXT_ERR_OK;
568 goto done;
569
570 err:
571 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
572 done:
573 /*
574 * If we parsed aia we need to free; otherwise they were copied and we
575 * don't
576 */
577 if (aia != NULL) {
578 OPENSSL_free(host);
579 OPENSSL_free(path);
580 OPENSSL_free(port);
581 X509_email_free(aia);
582 }
583 OCSP_CERTID_free(id);
584 OCSP_REQUEST_free(req);
585 X509_STORE_CTX_free(inctx);
586 return ret;
587 }
588
589 /*
590 * Certificate Status callback. This is called when a client includes a
591 * certificate status request extension. The response is either obtained from a
592 * file, or from an OCSP responder.
593 */
594 static int cert_status_cb(SSL *s, void *arg)
595 {
596 tlsextstatusctx *srctx = arg;
597 OCSP_RESPONSE *resp = NULL;
598 unsigned char *rspder = NULL;
599 int rspderlen;
600 int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
601
602 if (srctx->verbose)
603 BIO_puts(bio_err, "cert_status: callback called\n");
604
605 if (srctx->respin != NULL) {
606 BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1);
607 if (derbio == NULL) {
608 BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n");
609 goto err;
610 }
611 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
612 BIO_free(derbio);
613 if (resp == NULL) {
614 BIO_puts(bio_err, "cert_status: Error reading OCSP response\n");
615 goto err;
616 }
617 } else {
618 ret = get_ocsp_resp_from_responder(s, srctx, &resp);
619 if (ret != SSL_TLSEXT_ERR_OK)
620 goto err;
621 }
622
623 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
624 if (rspderlen <= 0)
625 goto err;
626
627 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
628 if (srctx->verbose) {
629 BIO_puts(bio_err, "cert_status: ocsp response sent:\n");
630 OCSP_RESPONSE_print(bio_err, resp, 2);
631 }
632
633 ret = SSL_TLSEXT_ERR_OK;
634
635 err:
636 if (ret != SSL_TLSEXT_ERR_OK)
637 ERR_print_errors(bio_err);
638
639 OCSP_RESPONSE_free(resp);
640
641 return ret;
642 }
643 #endif
644
645 #ifndef OPENSSL_NO_NEXTPROTONEG
646 /* This is the context that we pass to next_proto_cb */
647 typedef struct tlsextnextprotoctx_st {
648 unsigned char *data;
649 size_t len;
650 } tlsextnextprotoctx;
651
652 static int next_proto_cb(SSL *s, const unsigned char **data,
653 unsigned int *len, void *arg)
654 {
655 tlsextnextprotoctx *next_proto = arg;
656
657 *data = next_proto->data;
658 *len = next_proto->len;
659
660 return SSL_TLSEXT_ERR_OK;
661 }
662 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
663
664 /* This the context that we pass to alpn_cb */
665 typedef struct tlsextalpnctx_st {
666 unsigned char *data;
667 size_t len;
668 } tlsextalpnctx;
669
670 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
671 const unsigned char *in, unsigned int inlen, void *arg)
672 {
673 tlsextalpnctx *alpn_ctx = arg;
674
675 if (!s_quiet) {
676 /* We can assume that |in| is syntactically valid. */
677 unsigned int i;
678 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
679 for (i = 0; i < inlen;) {
680 if (i)
681 BIO_write(bio_s_out, ", ", 2);
682 BIO_write(bio_s_out, &in[i + 1], in[i]);
683 i += in[i] + 1;
684 }
685 BIO_write(bio_s_out, "\n", 1);
686 }
687
688 if (SSL_select_next_proto
689 ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in,
690 inlen) != OPENSSL_NPN_NEGOTIATED) {
691 return SSL_TLSEXT_ERR_ALERT_FATAL;
692 }
693
694 if (!s_quiet) {
695 BIO_printf(bio_s_out, "ALPN protocols selected: ");
696 BIO_write(bio_s_out, *out, *outlen);
697 BIO_write(bio_s_out, "\n", 1);
698 }
699
700 return SSL_TLSEXT_ERR_OK;
701 }
702
703 static int not_resumable_sess_cb(SSL *s, int is_forward_secure)
704 {
705 /* disable resumption for sessions with forward secure ciphers */
706 return is_forward_secure;
707 }
708
709 typedef enum OPTION_choice {
710 OPT_COMMON,
711 OPT_ENGINE,
712 OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT,
713 OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL,
714 OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM,
715 OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT,
716 OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT,
717 OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE,
718 OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
719 OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE,
720 OPT_VERIFYCAFILE,
721 OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE,
722 OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF,
723 OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE,
724 OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL,
725 OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE,
726 OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE,
727 OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE,
728 OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK,
729 OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW,
730 OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG,
731 OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
732 OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
733 OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS,
734 OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL,
735 OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE,
736 OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN,
737 OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA,
738 OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG,
739 OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS,
740 OPT_USE_ZC_SENDFILE,
741 OPT_TFO, OPT_CERT_COMP,
742 OPT_ENABLE_SERVER_RPK,
743 OPT_ENABLE_CLIENT_RPK,
744 OPT_R_ENUM,
745 OPT_S_ENUM,
746 OPT_V_ENUM,
747 OPT_X_ENUM,
748 OPT_PROV_ENUM
749 } OPTION_CHOICE;
750
751 const OPTIONS s_server_options[] = {
752 OPT_SECTION("General"),
753 {"help", OPT_HELP, '-', "Display this summary"},
754 {"ssl_config", OPT_SSL_CONFIG, 's',
755 "Configure SSL_CTX using the given configuration value"},
756 #ifndef OPENSSL_NO_SSL_TRACE
757 {"trace", OPT_TRACE, '-', "trace protocol messages"},
758 #endif
759 #ifndef OPENSSL_NO_ENGINE
760 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
761 #endif
762
763 OPT_SECTION("Network"),
764 {"port", OPT_PORT, 'p',
765 "TCP/IP port to listen on for connections (default is " PORT ")"},
766 {"accept", OPT_ACCEPT, 's',
767 "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"},
768 #ifdef AF_UNIX
769 {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"},
770 {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"},
771 #endif
772 {"4", OPT_4, '-', "Use IPv4 only"},
773 {"6", OPT_6, '-', "Use IPv6 only"},
774 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
775 {"tfo", OPT_TFO, '-', "Listen for TCP Fast Open connections"},
776 #endif
777
778 OPT_SECTION("Identity"),
779 {"context", OPT_CONTEXT, 's', "Set session ID context"},
780 {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
781 {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
782 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
783 {"no-CAfile", OPT_NOCAFILE, '-',
784 "Do not load the default certificates file"},
785 {"no-CApath", OPT_NOCAPATH, '-',
786 "Do not load certificates from the default certificates directory"},
787 {"no-CAstore", OPT_NOCASTORE, '-',
788 "Do not load certificates from the default certificates store URI"},
789 {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"},
790 {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"},
791 {"Verify", OPT_UPPER_V_VERIFY, 'n',
792 "Turn on peer certificate verification, must have a cert"},
793 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
794 {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT},
795 {"cert2", OPT_CERT2, '<',
796 "Certificate file to use for servername; default " TEST_CERT2},
797 {"certform", OPT_CERTFORM, 'F',
798 "Server certificate file format (PEM/DER/P12); has no effect"},
799 {"cert_chain", OPT_CERT_CHAIN, '<',
800 "Server certificate chain file in PEM format"},
801 {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"},
802 {"serverinfo", OPT_SERVERINFO, 's',
803 "PEM serverinfo file for certificate"},
804 {"key", OPT_KEY, 's',
805 "Private key file to use; default is -cert file or else" TEST_CERT},
806 {"key2", OPT_KEY2, '<',
807 "-Private Key file to use for servername if not in -cert2"},
808 {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"},
809 {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"},
810 {"dcert", OPT_DCERT, '<',
811 "Second server certificate file to use (usually for DSA)"},
812 {"dcertform", OPT_DCERTFORM, 'F',
813 "Second server certificate file format (PEM/DER/P12); has no effect"},
814 {"dcert_chain", OPT_DCERT_CHAIN, '<',
815 "second server certificate chain file in PEM format"},
816 {"dkey", OPT_DKEY, '<',
817 "Second private key file to use (usually for DSA)"},
818 {"dkeyform", OPT_DKEYFORM, 'f',
819 "Second key file format (ENGINE, other values ignored)"},
820 {"dpass", OPT_DPASS, 's',
821 "Second private key and cert file pass phrase source"},
822 {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"},
823 {"servername", OPT_SERVERNAME, 's',
824 "Servername for HostName TLS extension"},
825 {"servername_fatal", OPT_SERVERNAME_FATAL, '-',
826 "On servername mismatch send fatal alert (default warning alert)"},
827 {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"},
828 {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
829 {"quiet", OPT_QUIET, '-', "No server output"},
830 {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-',
831 "Disable caching and tickets if ephemeral (EC)DH is used"},
832 {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"},
833 {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"},
834 {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
835 "Do not treat lack of close_notify from a peer as an error"},
836 {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
837 "Hex dump of all TLS extensions received"},
838 {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"},
839 {"id_prefix", OPT_ID_PREFIX, 's',
840 "Generate SSL/TLS session IDs prefixed by arg"},
841 {"keymatexport", OPT_KEYMATEXPORT, 's',
842 "Export keying material using label"},
843 {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
844 "Export len bytes of keying material; default 20"},
845 {"CRL", OPT_CRL, '<', "CRL file to use"},
846 {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"},
847 {"crl_download", OPT_CRL_DOWNLOAD, '-',
848 "Download CRLs from distribution points in certificate CDP entries"},
849 {"chainCAfile", OPT_CHAINCAFILE, '<',
850 "CA file for certificate chain (PEM format)"},
851 {"chainCApath", OPT_CHAINCAPATH, '/',
852 "use dir as certificate store path to build CA certificate chain"},
853 {"chainCAstore", OPT_CHAINCASTORE, ':',
854 "use URI as certificate store to build CA certificate chain"},
855 {"verifyCAfile", OPT_VERIFYCAFILE, '<',
856 "CA file for certificate verification (PEM format)"},
857 {"verifyCApath", OPT_VERIFYCAPATH, '/',
858 "use dir as certificate store path to verify CA certificate"},
859 {"verifyCAstore", OPT_VERIFYCASTORE, ':',
860 "use URI as certificate store to verify CA certificate"},
861 {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"},
862 {"ext_cache", OPT_EXT_CACHE, '-',
863 "Disable internal cache, set up and use external cache"},
864 {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
865 "Close connection on verification error"},
866 {"verify_quiet", OPT_VERIFY_QUIET, '-',
867 "No verify output except verify errors"},
868 {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"},
869 {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"},
870 #ifndef OPENSSL_NO_COMP_ALG
871 {"cert_comp", OPT_CERT_COMP, '-', "Pre-compress server certificates"},
872 #endif
873
874 #ifndef OPENSSL_NO_OCSP
875 OPT_SECTION("OCSP"),
876 {"status", OPT_STATUS, '-', "Request certificate status from server"},
877 {"status_verbose", OPT_STATUS_VERBOSE, '-',
878 "Print more output in certificate status callback"},
879 {"status_timeout", OPT_STATUS_TIMEOUT, 'n',
880 "Status request responder timeout"},
881 {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"},
882 {"proxy", OPT_PROXY, 's',
883 "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"},
884 {"no_proxy", OPT_NO_PROXY, 's',
885 "List of addresses of servers not to use HTTP(S) proxy for"},
886 {OPT_MORE_STR, 0, 0,
887 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
888 {"status_file", OPT_STATUS_FILE, '<',
889 "File containing DER encoded OCSP Response"},
890 #endif
891
892 OPT_SECTION("Debug"),
893 {"security_debug", OPT_SECURITY_DEBUG, '-',
894 "Print output from SSL/TLS security framework"},
895 {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
896 "Print more output from SSL/TLS security framework"},
897 {"brief", OPT_BRIEF, '-',
898 "Restrict output to brief summary of connection parameters"},
899 {"rev", OPT_REV, '-',
900 "act as an echo server that sends back received text reversed"},
901 {"debug", OPT_DEBUG, '-', "Print more output"},
902 {"msg", OPT_MSG, '-', "Show protocol messages"},
903 {"msgfile", OPT_MSGFILE, '>',
904 "File to send output of -msg or -trace, instead of stdout"},
905 {"state", OPT_STATE, '-', "Print the SSL states"},
906 {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"},
907 {"max_pipelines", OPT_MAX_PIPELINES, 'p',
908 "Maximum number of encrypt/decrypt pipelines to be used"},
909 {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"},
910 {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
911
912 OPT_SECTION("Network"),
913 {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
914 {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"},
915 {"mtu", OPT_MTU, 'p', "Set link-layer MTU"},
916 {"read_buf", OPT_READ_BUF, 'p',
917 "Default read buffer size to be used for connections"},
918 {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
919 "Size used to split data for encrypt pipelines"},
920 {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
921
922 OPT_SECTION("Server identity"),
923 {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"},
924 #ifndef OPENSSL_NO_PSK
925 {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"},
926 #endif
927 {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
928 {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
929 #ifndef OPENSSL_NO_SRP
930 {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"},
931 {"srpuserseed", OPT_SRPUSERSEED, 's',
932 "(deprecated) A seed string for a default user salt"},
933 #endif
934
935 OPT_SECTION("Protocol and version"),
936 {"max_early_data", OPT_MAX_EARLY, 'n',
937 "The maximum number of bytes of early data as advertised in tickets"},
938 {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n',
939 "The maximum number of bytes of early data (hard limit)"},
940 {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"},
941 {"num_tickets", OPT_S_NUM_TICKETS, 'n',
942 "The number of TLSv1.3 session tickets that a server will automatically issue" },
943 {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"},
944 {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"},
945 {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"},
946 {"no_ca_names", OPT_NOCANAMES, '-',
947 "Disable TLS Extension CA Names"},
948 {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"},
949 #ifndef OPENSSL_NO_SSL3
950 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"},
951 #endif
952 #ifndef OPENSSL_NO_TLS1
953 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"},
954 #endif
955 #ifndef OPENSSL_NO_TLS1_1
956 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"},
957 #endif
958 #ifndef OPENSSL_NO_TLS1_2
959 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"},
960 #endif
961 #ifndef OPENSSL_NO_TLS1_3
962 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"},
963 #endif
964 #ifndef OPENSSL_NO_DTLS
965 {"dtls", OPT_DTLS, '-', "Use any DTLS version"},
966 {"listen", OPT_LISTEN, '-',
967 "Listen for a DTLS ClientHello with a cookie and then connect"},
968 #endif
969 #ifndef OPENSSL_NO_DTLS1
970 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"},
971 #endif
972 #ifndef OPENSSL_NO_DTLS1_2
973 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"},
974 #endif
975 #ifndef OPENSSL_NO_SCTP
976 {"sctp", OPT_SCTP, '-', "Use SCTP"},
977 {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"},
978 #endif
979 #ifndef OPENSSL_NO_SRTP
980 {"use_srtp", OPT_SRTP_PROFILES, 's',
981 "Offer SRTP key management with a colon-separated profile list"},
982 #endif
983 {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"},
984 #ifndef OPENSSL_NO_NEXTPROTONEG
985 {"nextprotoneg", OPT_NEXTPROTONEG, 's',
986 "Set the advertised protocols for the NPN extension (comma-separated list)"},
987 #endif
988 {"alpn", OPT_ALPN, 's',
989 "Set the advertised protocols for the ALPN extension (comma-separated list)"},
990 #ifndef OPENSSL_NO_KTLS
991 {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"},
992 {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"},
993 {"zerocopy_sendfile", OPT_USE_ZC_SENDFILE, '-', "Use zerocopy mode of KTLS sendfile"},
994 #endif
995 {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"},
996 {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"},
997 OPT_R_OPTIONS,
998 OPT_S_OPTIONS,
999 OPT_V_OPTIONS,
1000 OPT_X_OPTIONS,
1001 OPT_PROV_OPTIONS,
1002 {NULL}
1003 };
1004
1005 #define IS_PROT_FLAG(o) \
1006 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
1007 || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
1008
1009 int s_server_main(int argc, char *argv[])
1010 {
1011 ENGINE *engine = NULL;
1012 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
1013 SSL_CONF_CTX *cctx = NULL;
1014 const SSL_METHOD *meth = TLS_server_method();
1015 SSL_EXCERT *exc = NULL;
1016 STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
1017 STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
1018 STACK_OF(X509_CRL) *crls = NULL;
1019 X509 *s_cert = NULL, *s_dcert = NULL;
1020 X509_VERIFY_PARAM *vpm = NULL;
1021 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
1022 const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL;
1023 char *dpassarg = NULL, *dpass = NULL;
1024 char *passarg = NULL, *pass = NULL;
1025 char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
1026 char *crl_file = NULL, *prog;
1027 #ifdef AF_UNIX
1028 int unlink_unix_path = 0;
1029 #endif
1030 do_server_cb server_cb;
1031 int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0;
1032 char *dhfile = NULL;
1033 int no_dhe = 0;
1034 int nocert = 0, ret = 1;
1035 int noCApath = 0, noCAfile = 0, noCAstore = 0;
1036 int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF;
1037 int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF;
1038 int rev = 0, naccept = -1, sdebug = 0;
1039 int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
1040 int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0;
1041 char *host = NULL;
1042 char *port = NULL;
1043 unsigned char *context = NULL;
1044 OPTION_CHOICE o;
1045 EVP_PKEY *s_key2 = NULL;
1046 X509 *s_cert2 = NULL;
1047 tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING };
1048 const char *ssl_config = NULL;
1049 int read_buf_len = 0;
1050 #ifndef OPENSSL_NO_NEXTPROTONEG
1051 const char *next_proto_neg_in = NULL;
1052 tlsextnextprotoctx next_proto = { NULL, 0 };
1053 #endif
1054 const char *alpn_in = NULL;
1055 tlsextalpnctx alpn_ctx = { NULL, 0 };
1056 #ifndef OPENSSL_NO_PSK
1057 /* by default do not send a PSK identity hint */
1058 char *psk_identity_hint = NULL;
1059 #endif
1060 char *p;
1061 #ifndef OPENSSL_NO_SRP
1062 char *srpuserseed = NULL;
1063 char *srp_verifier_file = NULL;
1064 #endif
1065 #ifndef OPENSSL_NO_SRTP
1066 char *srtp_profiles = NULL;
1067 #endif
1068 int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
1069 int s_server_verify = SSL_VERIFY_NONE;
1070 int s_server_session_id_context = 1; /* anything will do */
1071 const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL;
1072 const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
1073 char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL;
1074 #ifndef OPENSSL_NO_OCSP
1075 int s_tlsextstatus = 0;
1076 #endif
1077 int no_resume_ephemeral = 0;
1078 unsigned int max_send_fragment = 0;
1079 unsigned int split_send_fragment = 0, max_pipelines = 0;
1080 const char *s_serverinfo_file = NULL;
1081 const char *keylog_file = NULL;
1082 int max_early_data = -1, recv_max_early_data = -1;
1083 char *psksessf = NULL;
1084 int no_ca_names = 0;
1085 #ifndef OPENSSL_NO_SCTP
1086 int sctp_label_bug = 0;
1087 #endif
1088 int ignore_unexpected_eof = 0;
1089 #ifndef OPENSSL_NO_KTLS
1090 int enable_ktls = 0;
1091 #endif
1092 int tfo = 0;
1093 int cert_comp = 0;
1094 int enable_server_rpk = 0;
1095
1096 /* Init of few remaining global variables */
1097 local_argc = argc;
1098 local_argv = argv;
1099
1100 ctx = ctx2 = NULL;
1101 s_nbio = s_nbio_test = 0;
1102 www = 0;
1103 bio_s_out = NULL;
1104 s_debug = 0;
1105 s_msg = 0;
1106 s_quiet = 0;
1107 s_brief = 0;
1108 async = 0;
1109 use_sendfile = 0;
1110 use_zc_sendfile = 0;
1111
1112 port = OPENSSL_strdup(PORT);
1113 cctx = SSL_CONF_CTX_new();
1114 vpm = X509_VERIFY_PARAM_new();
1115 if (port == NULL || cctx == NULL || vpm == NULL)
1116 goto end;
1117 SSL_CONF_CTX_set_flags(cctx,
1118 SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE);
1119
1120 prog = opt_init(argc, argv, s_server_options);
1121 while ((o = opt_next()) != OPT_EOF) {
1122 if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1123 BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1124 goto end;
1125 }
1126 if (IS_NO_PROT_FLAG(o))
1127 no_prot_opt++;
1128 if (prot_opt == 1 && no_prot_opt) {
1129 BIO_printf(bio_err,
1130 "Cannot supply both a protocol flag and '-no_<prot>'\n");
1131 goto end;
1132 }
1133 switch (o) {
1134 case OPT_EOF:
1135 case OPT_ERR:
1136 opthelp:
1137 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1138 goto end;
1139 case OPT_HELP:
1140 opt_help(s_server_options);
1141 ret = 0;
1142 goto end;
1143
1144 case OPT_4:
1145 #ifdef AF_UNIX
1146 if (socket_family == AF_UNIX) {
1147 OPENSSL_free(host); host = NULL;
1148 OPENSSL_free(port); port = NULL;
1149 }
1150 #endif
1151 socket_family = AF_INET;
1152 break;
1153 case OPT_6:
1154 if (1) {
1155 #ifdef AF_INET6
1156 #ifdef AF_UNIX
1157 if (socket_family == AF_UNIX) {
1158 OPENSSL_free(host); host = NULL;
1159 OPENSSL_free(port); port = NULL;
1160 }
1161 #endif
1162 socket_family = AF_INET6;
1163 } else {
1164 #endif
1165 BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog);
1166 goto end;
1167 }
1168 break;
1169 case OPT_PORT:
1170 #ifdef AF_UNIX
1171 if (socket_family == AF_UNIX) {
1172 socket_family = AF_UNSPEC;
1173 }
1174 #endif
1175 OPENSSL_free(port); port = NULL;
1176 OPENSSL_free(host); host = NULL;
1177 if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) {
1178 BIO_printf(bio_err,
1179 "%s: -port argument malformed or ambiguous\n",
1180 port);
1181 goto end;
1182 }
1183 break;
1184 case OPT_ACCEPT:
1185 #ifdef AF_UNIX
1186 if (socket_family == AF_UNIX) {
1187 socket_family = AF_UNSPEC;
1188 }
1189 #endif
1190 OPENSSL_free(port); port = NULL;
1191 OPENSSL_free(host); host = NULL;
1192 if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) {
1193 BIO_printf(bio_err,
1194 "%s: -accept argument malformed or ambiguous\n",
1195 port);
1196 goto end;
1197 }
1198 break;
1199 #ifdef AF_UNIX
1200 case OPT_UNIX:
1201 socket_family = AF_UNIX;
1202 OPENSSL_free(host); host = OPENSSL_strdup(opt_arg());
1203 if (host == NULL)
1204 goto end;
1205 OPENSSL_free(port); port = NULL;
1206 break;
1207 case OPT_UNLINK:
1208 unlink_unix_path = 1;
1209 break;
1210 #endif
1211 case OPT_NACCEPT:
1212 naccept = atol(opt_arg());
1213 break;
1214 case OPT_VERIFY:
1215 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
1216 verify_args.depth = atoi(opt_arg());
1217 if (!s_quiet)
1218 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1219 break;
1220 case OPT_UPPER_V_VERIFY:
1221 s_server_verify =
1222 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1223 SSL_VERIFY_CLIENT_ONCE;
1224 verify_args.depth = atoi(opt_arg());
1225 if (!s_quiet)
1226 BIO_printf(bio_err,
1227 "verify depth is %d, must return a certificate\n",
1228 verify_args.depth);
1229 break;
1230 case OPT_CONTEXT:
1231 context = (unsigned char *)opt_arg();
1232 break;
1233 case OPT_CERT:
1234 s_cert_file = opt_arg();
1235 break;
1236 case OPT_NAMEOPT:
1237 if (!set_nameopt(opt_arg()))
1238 goto end;
1239 break;
1240 case OPT_CRL:
1241 crl_file = opt_arg();
1242 break;
1243 case OPT_CRL_DOWNLOAD:
1244 crl_download = 1;
1245 break;
1246 case OPT_SERVERINFO:
1247 s_serverinfo_file = opt_arg();
1248 break;
1249 case OPT_CERTFORM:
1250 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format))
1251 goto opthelp;
1252 break;
1253 case OPT_KEY:
1254 s_key_file = opt_arg();
1255 break;
1256 case OPT_KEYFORM:
1257 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format))
1258 goto opthelp;
1259 break;
1260 case OPT_PASS:
1261 passarg = opt_arg();
1262 break;
1263 case OPT_CERT_CHAIN:
1264 s_chain_file = opt_arg();
1265 break;
1266 case OPT_DHPARAM:
1267 dhfile = opt_arg();
1268 break;
1269 case OPT_DCERTFORM:
1270 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format))
1271 goto opthelp;
1272 break;
1273 case OPT_DCERT:
1274 s_dcert_file = opt_arg();
1275 break;
1276 case OPT_DKEYFORM:
1277 if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format))
1278 goto opthelp;
1279 break;
1280 case OPT_DPASS:
1281 dpassarg = opt_arg();
1282 break;
1283 case OPT_DKEY:
1284 s_dkey_file = opt_arg();
1285 break;
1286 case OPT_DCERT_CHAIN:
1287 s_dchain_file = opt_arg();
1288 break;
1289 case OPT_NOCERT:
1290 nocert = 1;
1291 break;
1292 case OPT_CAPATH:
1293 CApath = opt_arg();
1294 break;
1295 case OPT_NOCAPATH:
1296 noCApath = 1;
1297 break;
1298 case OPT_CHAINCAPATH:
1299 chCApath = opt_arg();
1300 break;
1301 case OPT_VERIFYCAPATH:
1302 vfyCApath = opt_arg();
1303 break;
1304 case OPT_CASTORE:
1305 CAstore = opt_arg();
1306 break;
1307 case OPT_NOCASTORE:
1308 noCAstore = 1;
1309 break;
1310 case OPT_CHAINCASTORE:
1311 chCAstore = opt_arg();
1312 break;
1313 case OPT_VERIFYCASTORE:
1314 vfyCAstore = opt_arg();
1315 break;
1316 case OPT_NO_CACHE:
1317 no_cache = 1;
1318 break;
1319 case OPT_EXT_CACHE:
1320 ext_cache = 1;
1321 break;
1322 case OPT_CRLFORM:
1323 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1324 goto opthelp;
1325 break;
1326 case OPT_S_CASES:
1327 case OPT_S_NUM_TICKETS:
1328 case OPT_ANTI_REPLAY:
1329 case OPT_NO_ANTI_REPLAY:
1330 if (ssl_args == NULL)
1331 ssl_args = sk_OPENSSL_STRING_new_null();
1332 if (ssl_args == NULL
1333 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1334 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1335 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1336 goto end;
1337 }
1338 break;
1339 case OPT_V_CASES:
1340 if (!opt_verify(o, vpm))
1341 goto end;
1342 vpmtouched++;
1343 break;
1344 case OPT_X_CASES:
1345 if (!args_excert(o, &exc))
1346 goto end;
1347 break;
1348 case OPT_VERIFY_RET_ERROR:
1349 verify_args.return_error = 1;
1350 break;
1351 case OPT_VERIFY_QUIET:
1352 verify_args.quiet = 1;
1353 break;
1354 case OPT_BUILD_CHAIN:
1355 build_chain = 1;
1356 break;
1357 case OPT_CAFILE:
1358 CAfile = opt_arg();
1359 break;
1360 case OPT_NOCAFILE:
1361 noCAfile = 1;
1362 break;
1363 case OPT_CHAINCAFILE:
1364 chCAfile = opt_arg();
1365 break;
1366 case OPT_VERIFYCAFILE:
1367 vfyCAfile = opt_arg();
1368 break;
1369 case OPT_NBIO:
1370 s_nbio = 1;
1371 break;
1372 case OPT_NBIO_TEST:
1373 s_nbio = s_nbio_test = 1;
1374 break;
1375 case OPT_IGN_EOF:
1376 s_ign_eof = 1;
1377 break;
1378 case OPT_NO_IGN_EOF:
1379 s_ign_eof = 0;
1380 break;
1381 case OPT_DEBUG:
1382 s_debug = 1;
1383 break;
1384 case OPT_TLSEXTDEBUG:
1385 s_tlsextdebug = 1;
1386 break;
1387 case OPT_STATUS:
1388 #ifndef OPENSSL_NO_OCSP
1389 s_tlsextstatus = 1;
1390 #endif
1391 break;
1392 case OPT_STATUS_VERBOSE:
1393 #ifndef OPENSSL_NO_OCSP
1394 s_tlsextstatus = tlscstatp.verbose = 1;
1395 #endif
1396 break;
1397 case OPT_STATUS_TIMEOUT:
1398 #ifndef OPENSSL_NO_OCSP
1399 s_tlsextstatus = 1;
1400 tlscstatp.timeout = atoi(opt_arg());
1401 #endif
1402 break;
1403 case OPT_PROXY:
1404 #ifndef OPENSSL_NO_OCSP
1405 tlscstatp.proxy = opt_arg();
1406 #endif
1407 break;
1408 case OPT_NO_PROXY:
1409 #ifndef OPENSSL_NO_OCSP
1410 tlscstatp.no_proxy = opt_arg();
1411 #endif
1412 break;
1413 case OPT_STATUS_URL:
1414 #ifndef OPENSSL_NO_OCSP
1415 s_tlsextstatus = 1;
1416 if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL,
1417 &tlscstatp.host, &tlscstatp.port, NULL,
1418 &tlscstatp.path, NULL, NULL)) {
1419 BIO_printf(bio_err, "Error parsing -status_url argument\n");
1420 goto end;
1421 }
1422 #endif
1423 break;
1424 case OPT_STATUS_FILE:
1425 #ifndef OPENSSL_NO_OCSP
1426 s_tlsextstatus = 1;
1427 tlscstatp.respin = opt_arg();
1428 #endif
1429 break;
1430 case OPT_MSG:
1431 s_msg = 1;
1432 break;
1433 case OPT_MSGFILE:
1434 bio_s_msg = BIO_new_file(opt_arg(), "w");
1435 if (bio_s_msg == NULL) {
1436 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
1437 goto end;
1438 }
1439 break;
1440 case OPT_TRACE:
1441 #ifndef OPENSSL_NO_SSL_TRACE
1442 s_msg = 2;
1443 #endif
1444 break;
1445 case OPT_SECURITY_DEBUG:
1446 sdebug = 1;
1447 break;
1448 case OPT_SECURITY_DEBUG_VERBOSE:
1449 sdebug = 2;
1450 break;
1451 case OPT_STATE:
1452 state = 1;
1453 break;
1454 case OPT_CRLF:
1455 s_crlf = 1;
1456 break;
1457 case OPT_QUIET:
1458 s_quiet = 1;
1459 break;
1460 case OPT_BRIEF:
1461 s_quiet = s_brief = verify_args.quiet = 1;
1462 break;
1463 case OPT_NO_DHE:
1464 no_dhe = 1;
1465 break;
1466 case OPT_NO_RESUME_EPHEMERAL:
1467 no_resume_ephemeral = 1;
1468 break;
1469 case OPT_PSK_IDENTITY:
1470 psk_identity = opt_arg();
1471 break;
1472 case OPT_PSK_HINT:
1473 #ifndef OPENSSL_NO_PSK
1474 psk_identity_hint = opt_arg();
1475 #endif
1476 break;
1477 case OPT_PSK:
1478 for (p = psk_key = opt_arg(); *p; p++) {
1479 if (isxdigit(_UC(*p)))
1480 continue;
1481 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1482 goto end;
1483 }
1484 break;
1485 case OPT_PSK_SESS:
1486 psksessf = opt_arg();
1487 break;
1488 case OPT_SRPVFILE:
1489 #ifndef OPENSSL_NO_SRP
1490 srp_verifier_file = opt_arg();
1491 if (min_version < TLS1_VERSION)
1492 min_version = TLS1_VERSION;
1493 #endif
1494 break;
1495 case OPT_SRPUSERSEED:
1496 #ifndef OPENSSL_NO_SRP
1497 srpuserseed = opt_arg();
1498 if (min_version < TLS1_VERSION)
1499 min_version = TLS1_VERSION;
1500 #endif
1501 break;
1502 case OPT_REV:
1503 rev = 1;
1504 break;
1505 case OPT_WWW:
1506 www = 1;
1507 break;
1508 case OPT_UPPER_WWW:
1509 www = 2;
1510 break;
1511 case OPT_HTTP:
1512 www = 3;
1513 break;
1514 case OPT_SSL_CONFIG:
1515 ssl_config = opt_arg();
1516 break;
1517 case OPT_SSL3:
1518 min_version = SSL3_VERSION;
1519 max_version = SSL3_VERSION;
1520 break;
1521 case OPT_TLS1_3:
1522 min_version = TLS1_3_VERSION;
1523 max_version = TLS1_3_VERSION;
1524 break;
1525 case OPT_TLS1_2:
1526 min_version = TLS1_2_VERSION;
1527 max_version = TLS1_2_VERSION;
1528 break;
1529 case OPT_TLS1_1:
1530 min_version = TLS1_1_VERSION;
1531 max_version = TLS1_1_VERSION;
1532 break;
1533 case OPT_TLS1:
1534 min_version = TLS1_VERSION;
1535 max_version = TLS1_VERSION;
1536 break;
1537 case OPT_DTLS:
1538 #ifndef OPENSSL_NO_DTLS
1539 meth = DTLS_server_method();
1540 socket_type = SOCK_DGRAM;
1541 #endif
1542 break;
1543 case OPT_DTLS1:
1544 #ifndef OPENSSL_NO_DTLS
1545 meth = DTLS_server_method();
1546 min_version = DTLS1_VERSION;
1547 max_version = DTLS1_VERSION;
1548 socket_type = SOCK_DGRAM;
1549 #endif
1550 break;
1551 case OPT_DTLS1_2:
1552 #ifndef OPENSSL_NO_DTLS
1553 meth = DTLS_server_method();
1554 min_version = DTLS1_2_VERSION;
1555 max_version = DTLS1_2_VERSION;
1556 socket_type = SOCK_DGRAM;
1557 #endif
1558 break;
1559 case OPT_SCTP:
1560 #ifndef OPENSSL_NO_SCTP
1561 protocol = IPPROTO_SCTP;
1562 #endif
1563 break;
1564 case OPT_SCTP_LABEL_BUG:
1565 #ifndef OPENSSL_NO_SCTP
1566 sctp_label_bug = 1;
1567 #endif
1568 break;
1569 case OPT_TIMEOUT:
1570 #ifndef OPENSSL_NO_DTLS
1571 enable_timeouts = 1;
1572 #endif
1573 break;
1574 case OPT_MTU:
1575 #ifndef OPENSSL_NO_DTLS
1576 socket_mtu = atol(opt_arg());
1577 #endif
1578 break;
1579 case OPT_LISTEN:
1580 #ifndef OPENSSL_NO_DTLS
1581 dtlslisten = 1;
1582 #endif
1583 break;
1584 case OPT_STATELESS:
1585 stateless = 1;
1586 break;
1587 case OPT_ID_PREFIX:
1588 session_id_prefix = opt_arg();
1589 break;
1590 case OPT_ENGINE:
1591 #ifndef OPENSSL_NO_ENGINE
1592 engine = setup_engine(opt_arg(), s_debug);
1593 #endif
1594 break;
1595 case OPT_R_CASES:
1596 if (!opt_rand(o))
1597 goto end;
1598 break;
1599 case OPT_PROV_CASES:
1600 if (!opt_provider(o))
1601 goto end;
1602 break;
1603 case OPT_SERVERNAME:
1604 tlsextcbp.servername = opt_arg();
1605 break;
1606 case OPT_SERVERNAME_FATAL:
1607 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
1608 break;
1609 case OPT_CERT2:
1610 s_cert_file2 = opt_arg();
1611 break;
1612 case OPT_KEY2:
1613 s_key_file2 = opt_arg();
1614 break;
1615 case OPT_NEXTPROTONEG:
1616 # ifndef OPENSSL_NO_NEXTPROTONEG
1617 next_proto_neg_in = opt_arg();
1618 #endif
1619 break;
1620 case OPT_ALPN:
1621 alpn_in = opt_arg();
1622 break;
1623 case OPT_SRTP_PROFILES:
1624 #ifndef OPENSSL_NO_SRTP
1625 srtp_profiles = opt_arg();
1626 #endif
1627 break;
1628 case OPT_KEYMATEXPORT:
1629 keymatexportlabel = opt_arg();
1630 break;
1631 case OPT_KEYMATEXPORTLEN:
1632 keymatexportlen = atoi(opt_arg());
1633 break;
1634 case OPT_ASYNC:
1635 async = 1;
1636 break;
1637 case OPT_MAX_SEND_FRAG:
1638 max_send_fragment = atoi(opt_arg());
1639 break;
1640 case OPT_SPLIT_SEND_FRAG:
1641 split_send_fragment = atoi(opt_arg());
1642 break;
1643 case OPT_MAX_PIPELINES:
1644 max_pipelines = atoi(opt_arg());
1645 break;
1646 case OPT_READ_BUF:
1647 read_buf_len = atoi(opt_arg());
1648 break;
1649 case OPT_KEYLOG_FILE:
1650 keylog_file = opt_arg();
1651 break;
1652 case OPT_MAX_EARLY:
1653 max_early_data = atoi(opt_arg());
1654 if (max_early_data < 0) {
1655 BIO_printf(bio_err, "Invalid value for max_early_data\n");
1656 goto end;
1657 }
1658 break;
1659 case OPT_RECV_MAX_EARLY:
1660 recv_max_early_data = atoi(opt_arg());
1661 if (recv_max_early_data < 0) {
1662 BIO_printf(bio_err, "Invalid value for recv_max_early_data\n");
1663 goto end;
1664 }
1665 break;
1666 case OPT_EARLY_DATA:
1667 early_data = 1;
1668 if (max_early_data == -1)
1669 max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
1670 break;
1671 case OPT_HTTP_SERVER_BINMODE:
1672 http_server_binmode = 1;
1673 break;
1674 case OPT_NOCANAMES:
1675 no_ca_names = 1;
1676 break;
1677 case OPT_KTLS:
1678 #ifndef OPENSSL_NO_KTLS
1679 enable_ktls = 1;
1680 #endif
1681 break;
1682 case OPT_SENDFILE:
1683 #ifndef OPENSSL_NO_KTLS
1684 use_sendfile = 1;
1685 #endif
1686 break;
1687 case OPT_USE_ZC_SENDFILE:
1688 #ifndef OPENSSL_NO_KTLS
1689 use_zc_sendfile = 1;
1690 #endif
1691 break;
1692 case OPT_IGNORE_UNEXPECTED_EOF:
1693 ignore_unexpected_eof = 1;
1694 break;
1695 case OPT_TFO:
1696 tfo = 1;
1697 break;
1698 case OPT_CERT_COMP:
1699 cert_comp = 1;
1700 break;
1701 case OPT_ENABLE_SERVER_RPK:
1702 enable_server_rpk = 1;
1703 break;
1704 case OPT_ENABLE_CLIENT_RPK:
1705 enable_client_rpk = 1;
1706 break;
1707 }
1708 }
1709
1710 /* No extra arguments. */
1711 if (!opt_check_rest_arg(NULL))
1712 goto opthelp;
1713
1714 if (!app_RAND_load())
1715 goto end;
1716
1717 #ifndef OPENSSL_NO_NEXTPROTONEG
1718 if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1719 BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1720 goto opthelp;
1721 }
1722 #endif
1723 #ifndef OPENSSL_NO_DTLS
1724 if (www && socket_type == SOCK_DGRAM) {
1725 BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n");
1726 goto end;
1727 }
1728
1729 if (dtlslisten && socket_type != SOCK_DGRAM) {
1730 BIO_printf(bio_err, "Can only use -listen with DTLS\n");
1731 goto end;
1732 }
1733
1734 if (rev && socket_type == SOCK_DGRAM) {
1735 BIO_printf(bio_err, "Can't use -rev with DTLS\n");
1736 goto end;
1737 }
1738 #endif
1739
1740 if (tfo && socket_type != SOCK_STREAM) {
1741 BIO_printf(bio_err, "Can only use -tfo with TLS\n");
1742 goto end;
1743 }
1744
1745 if (stateless && socket_type != SOCK_STREAM) {
1746 BIO_printf(bio_err, "Can only use --stateless with TLS\n");
1747 goto end;
1748 }
1749
1750 #ifdef AF_UNIX
1751 if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1752 BIO_printf(bio_err,
1753 "Can't use unix sockets and datagrams together\n");
1754 goto end;
1755 }
1756 #endif
1757 if (early_data && (www > 0 || rev)) {
1758 BIO_printf(bio_err,
1759 "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n");
1760 goto end;
1761 }
1762
1763 #ifndef OPENSSL_NO_SCTP
1764 if (protocol == IPPROTO_SCTP) {
1765 if (socket_type != SOCK_DGRAM) {
1766 BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1767 goto end;
1768 }
1769 /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1770 socket_type = SOCK_STREAM;
1771 }
1772 #endif
1773
1774 #ifndef OPENSSL_NO_KTLS
1775 if (use_zc_sendfile && !use_sendfile) {
1776 BIO_printf(bio_out, "Warning: -zerocopy_sendfile depends on -sendfile, enabling -sendfile now.\n");
1777 use_sendfile = 1;
1778 }
1779
1780 if (use_sendfile && enable_ktls == 0) {
1781 BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n");
1782 enable_ktls = 1;
1783 }
1784
1785 if (use_sendfile && www <= 1) {
1786 BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n");
1787 goto end;
1788 }
1789 #endif
1790
1791 if (!app_passwd(passarg, dpassarg, &pass, &dpass)) {
1792 BIO_printf(bio_err, "Error getting password\n");
1793 goto end;
1794 }
1795
1796 if (s_key_file == NULL)
1797 s_key_file = s_cert_file;
1798
1799 if (s_key_file2 == NULL)
1800 s_key_file2 = s_cert_file2;
1801
1802 if (!load_excert(&exc))
1803 goto end;
1804
1805 if (nocert == 0) {
1806 s_key = load_key(s_key_file, s_key_format, 0, pass, engine,
1807 "server certificate private key");
1808 if (s_key == NULL)
1809 goto end;
1810
1811 s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass,
1812 "server certificate");
1813
1814 if (s_cert == NULL)
1815 goto end;
1816 if (s_chain_file != NULL) {
1817 if (!load_certs(s_chain_file, 0, &s_chain, NULL,
1818 "server certificate chain"))
1819 goto end;
1820 }
1821
1822 if (tlsextcbp.servername != NULL) {
1823 s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine,
1824 "second server certificate private key");
1825 if (s_key2 == NULL)
1826 goto end;
1827
1828 s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass,
1829 "second server certificate");
1830
1831 if (s_cert2 == NULL)
1832 goto end;
1833 }
1834 }
1835 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1836 if (next_proto_neg_in) {
1837 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
1838 if (next_proto.data == NULL)
1839 goto end;
1840 }
1841 #endif
1842 alpn_ctx.data = NULL;
1843 if (alpn_in) {
1844 alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in);
1845 if (alpn_ctx.data == NULL)
1846 goto end;
1847 }
1848
1849 if (crl_file != NULL) {
1850 X509_CRL *crl;
1851 crl = load_crl(crl_file, crl_format, 0, "CRL");
1852 if (crl == NULL)
1853 goto end;
1854 crls = sk_X509_CRL_new_null();
1855 if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1856 BIO_puts(bio_err, "Error adding CRL\n");
1857 ERR_print_errors(bio_err);
1858 X509_CRL_free(crl);
1859 goto end;
1860 }
1861 }
1862
1863 if (s_dcert_file != NULL) {
1864
1865 if (s_dkey_file == NULL)
1866 s_dkey_file = s_dcert_file;
1867
1868 s_dkey = load_key(s_dkey_file, s_dkey_format,
1869 0, dpass, engine, "second certificate private key");
1870 if (s_dkey == NULL)
1871 goto end;
1872
1873 s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass,
1874 "second server certificate");
1875
1876 if (s_dcert == NULL) {
1877 ERR_print_errors(bio_err);
1878 goto end;
1879 }
1880 if (s_dchain_file != NULL) {
1881 if (!load_certs(s_dchain_file, 0, &s_dchain, NULL,
1882 "second server certificate chain"))
1883 goto end;
1884 }
1885
1886 }
1887
1888 if (bio_s_out == NULL) {
1889 if (s_quiet && !s_debug) {
1890 bio_s_out = BIO_new(BIO_s_null());
1891 if (s_msg && bio_s_msg == NULL) {
1892 bio_s_msg = dup_bio_out(FORMAT_TEXT);
1893 if (bio_s_msg == NULL) {
1894 BIO_printf(bio_err, "Out of memory\n");
1895 goto end;
1896 }
1897 }
1898 } else {
1899 bio_s_out = dup_bio_out(FORMAT_TEXT);
1900 }
1901 }
1902
1903 if (bio_s_out == NULL)
1904 goto end;
1905
1906 if (nocert) {
1907 s_cert_file = NULL;
1908 s_key_file = NULL;
1909 s_dcert_file = NULL;
1910 s_dkey_file = NULL;
1911 s_cert_file2 = NULL;
1912 s_key_file2 = NULL;
1913 }
1914
1915 ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
1916 if (ctx == NULL) {
1917 ERR_print_errors(bio_err);
1918 goto end;
1919 }
1920
1921 SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1922
1923 if (sdebug)
1924 ssl_ctx_security_debug(ctx, sdebug);
1925
1926 if (!config_ctx(cctx, ssl_args, ctx))
1927 goto end;
1928
1929 if (ssl_config) {
1930 if (SSL_CTX_config(ctx, ssl_config) == 0) {
1931 BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1932 ssl_config);
1933 ERR_print_errors(bio_err);
1934 goto end;
1935 }
1936 }
1937 #ifndef OPENSSL_NO_SCTP
1938 if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
1939 SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1940 #endif
1941
1942 if (min_version != 0
1943 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1944 goto end;
1945 if (max_version != 0
1946 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1947 goto end;
1948
1949 if (session_id_prefix) {
1950 if (strlen(session_id_prefix) >= 32)
1951 BIO_printf(bio_err,
1952 "warning: id_prefix is too long, only one new session will be possible\n");
1953 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1954 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1955 ERR_print_errors(bio_err);
1956 goto end;
1957 }
1958 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1959 }
1960 if (exc != NULL)
1961 ssl_ctx_set_excert(ctx, exc);
1962
1963 if (state)
1964 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1965 if (no_cache)
1966 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1967 else if (ext_cache)
1968 init_session_cache_ctx(ctx);
1969 else
1970 SSL_CTX_sess_set_cache_size(ctx, 128);
1971
1972 if (async) {
1973 SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1974 }
1975
1976 if (no_ca_names) {
1977 SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
1978 }
1979
1980 if (ignore_unexpected_eof)
1981 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1982 #ifndef OPENSSL_NO_KTLS
1983 if (enable_ktls)
1984 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
1985 if (use_zc_sendfile)
1986 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE);
1987 #endif
1988
1989 if (max_send_fragment > 0
1990 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1991 BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1992 prog, max_send_fragment);
1993 goto end;
1994 }
1995
1996 if (split_send_fragment > 0
1997 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1998 BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1999 prog, split_send_fragment);
2000 goto end;
2001 }
2002 if (max_pipelines > 0
2003 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
2004 BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
2005 prog, max_pipelines);
2006 goto end;
2007 }
2008
2009 if (read_buf_len > 0) {
2010 SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
2011 }
2012 #ifndef OPENSSL_NO_SRTP
2013 if (srtp_profiles != NULL) {
2014 /* Returns 0 on success! */
2015 if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
2016 BIO_printf(bio_err, "Error setting SRTP profile\n");
2017 ERR_print_errors(bio_err);
2018 goto end;
2019 }
2020 }
2021 #endif
2022
2023 if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
2024 CAstore, noCAstore)) {
2025 ERR_print_errors(bio_err);
2026 goto end;
2027 }
2028 if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
2029 BIO_printf(bio_err, "Error setting verify params\n");
2030 ERR_print_errors(bio_err);
2031 goto end;
2032 }
2033
2034 ssl_ctx_add_crls(ctx, crls, 0);
2035
2036 if (!ssl_load_stores(ctx,
2037 vfyCApath, vfyCAfile, vfyCAstore,
2038 chCApath, chCAfile, chCAstore,
2039 crls, crl_download)) {
2040 BIO_printf(bio_err, "Error loading store locations\n");
2041 ERR_print_errors(bio_err);
2042 goto end;
2043 }
2044
2045 if (s_cert2) {
2046 ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
2047 if (ctx2 == NULL) {
2048 ERR_print_errors(bio_err);
2049 goto end;
2050 }
2051 }
2052
2053 if (ctx2 != NULL) {
2054 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
2055
2056 if (sdebug)
2057 ssl_ctx_security_debug(ctx2, sdebug);
2058
2059 if (session_id_prefix) {
2060 if (strlen(session_id_prefix) >= 32)
2061 BIO_printf(bio_err,
2062 "warning: id_prefix is too long, only one new session will be possible\n");
2063 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
2064 BIO_printf(bio_err, "error setting 'id_prefix'\n");
2065 ERR_print_errors(bio_err);
2066 goto end;
2067 }
2068 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
2069 }
2070 if (exc != NULL)
2071 ssl_ctx_set_excert(ctx2, exc);
2072
2073 if (state)
2074 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
2075
2076 if (no_cache)
2077 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
2078 else if (ext_cache)
2079 init_session_cache_ctx(ctx2);
2080 else
2081 SSL_CTX_sess_set_cache_size(ctx2, 128);
2082
2083 if (async)
2084 SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC);
2085
2086 if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath,
2087 noCApath, CAstore, noCAstore)) {
2088 ERR_print_errors(bio_err);
2089 goto end;
2090 }
2091 if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) {
2092 BIO_printf(bio_err, "Error setting verify params\n");
2093 ERR_print_errors(bio_err);
2094 goto end;
2095 }
2096
2097 ssl_ctx_add_crls(ctx2, crls, 0);
2098 if (!config_ctx(cctx, ssl_args, ctx2))
2099 goto end;
2100 }
2101 #ifndef OPENSSL_NO_NEXTPROTONEG
2102 if (next_proto.data)
2103 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb,
2104 &next_proto);
2105 #endif
2106 if (alpn_ctx.data)
2107 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
2108
2109 if (!no_dhe) {
2110 EVP_PKEY *dhpkey = NULL;
2111
2112 if (dhfile != NULL)
2113 dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters");
2114 else if (s_cert_file != NULL)
2115 dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH",
2116 "DH parameters", 1);
2117
2118 if (dhpkey != NULL) {
2119 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2120 } else {
2121 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
2122 }
2123 (void)BIO_flush(bio_s_out);
2124
2125 if (dhpkey == NULL) {
2126 SSL_CTX_set_dh_auto(ctx, 1);
2127 } else {
2128 /*
2129 * We need 2 references: one for use by ctx and one for use by
2130 * ctx2
2131 */
2132 if (!EVP_PKEY_up_ref(dhpkey)) {
2133 EVP_PKEY_free(dhpkey);
2134 goto end;
2135 }
2136 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) {
2137 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2138 ERR_print_errors(bio_err);
2139 /* Free 2 references */
2140 EVP_PKEY_free(dhpkey);
2141 EVP_PKEY_free(dhpkey);
2142 goto end;
2143 }
2144 }
2145
2146 if (ctx2 != NULL) {
2147 if (dhfile != NULL) {
2148 EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2,
2149 FORMAT_UNDEF,
2150 0, "DH",
2151 "DH parameters", 1);
2152
2153 if (dhpkey2 != NULL) {
2154 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
2155 (void)BIO_flush(bio_s_out);
2156
2157 EVP_PKEY_free(dhpkey);
2158 dhpkey = dhpkey2;
2159 }
2160 }
2161 if (dhpkey == NULL) {
2162 SSL_CTX_set_dh_auto(ctx2, 1);
2163 } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) {
2164 BIO_puts(bio_err, "Error setting temp DH parameters\n");
2165 ERR_print_errors(bio_err);
2166 EVP_PKEY_free(dhpkey);
2167 goto end;
2168 }
2169 dhpkey = NULL;
2170 }
2171 EVP_PKEY_free(dhpkey);
2172 }
2173
2174 if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
2175 goto end;
2176
2177 if (s_serverinfo_file != NULL
2178 && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) {
2179 ERR_print_errors(bio_err);
2180 goto end;
2181 }
2182
2183 if (ctx2 != NULL
2184 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain))
2185 goto end;
2186
2187 if (s_dcert != NULL) {
2188 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
2189 goto end;
2190 }
2191
2192 if (no_resume_ephemeral) {
2193 SSL_CTX_set_not_resumable_session_callback(ctx,
2194 not_resumable_sess_cb);
2195
2196 if (ctx2 != NULL)
2197 SSL_CTX_set_not_resumable_session_callback(ctx2,
2198 not_resumable_sess_cb);
2199 }
2200 #ifndef OPENSSL_NO_PSK
2201 if (psk_key != NULL) {
2202 if (s_debug)
2203 BIO_printf(bio_s_out, "PSK key given, setting server callback\n");
2204 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2205 }
2206
2207 if (psk_identity_hint != NULL) {
2208 if (min_version == TLS1_3_VERSION) {
2209 BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n");
2210 } else {
2211 if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) {
2212 BIO_printf(bio_err, "error setting PSK identity hint to context\n");
2213 ERR_print_errors(bio_err);
2214 goto end;
2215 }
2216 }
2217 }
2218 #endif
2219 if (psksessf != NULL) {
2220 BIO *stmp = BIO_new_file(psksessf, "r");
2221
2222 if (stmp == NULL) {
2223 BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
2224 ERR_print_errors(bio_err);
2225 goto end;
2226 }
2227 psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
2228 BIO_free(stmp);
2229 if (psksess == NULL) {
2230 BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
2231 ERR_print_errors(bio_err);
2232 goto end;
2233 }
2234
2235 }
2236
2237 if (psk_key != NULL || psksess != NULL)
2238 SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb);
2239
2240 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
2241 if (!SSL_CTX_set_session_id_context(ctx,
2242 (void *)&s_server_session_id_context,
2243 sizeof(s_server_session_id_context))) {
2244 BIO_printf(bio_err, "error setting session id context\n");
2245 ERR_print_errors(bio_err);
2246 goto end;
2247 }
2248
2249 /* Set DTLS cookie generation and verification callbacks */
2250 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2251 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2252
2253 /* Set TLS1.3 cookie generation and verification callbacks */
2254 SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback);
2255 SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback);
2256
2257 if (ctx2 != NULL) {
2258 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
2259 if (!SSL_CTX_set_session_id_context(ctx2,
2260 (void *)&s_server_session_id_context,
2261 sizeof(s_server_session_id_context))) {
2262 BIO_printf(bio_err, "error setting session id context\n");
2263 ERR_print_errors(bio_err);
2264 goto end;
2265 }
2266 tlsextcbp.biodebug = bio_s_out;
2267 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2268 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2269 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2270 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2271 }
2272
2273 #ifndef OPENSSL_NO_SRP
2274 if (srp_verifier_file != NULL) {
2275 if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed,
2276 srp_verifier_file))
2277 goto end;
2278 } else
2279 #endif
2280 if (CAfile != NULL) {
2281 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
2282
2283 if (ctx2)
2284 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
2285 }
2286 #ifndef OPENSSL_NO_OCSP
2287 if (s_tlsextstatus) {
2288 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2289 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2290 if (ctx2) {
2291 SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb);
2292 SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp);
2293 }
2294 }
2295 #endif
2296 if (set_keylog_file(ctx, keylog_file))
2297 goto end;
2298
2299 if (max_early_data >= 0)
2300 SSL_CTX_set_max_early_data(ctx, max_early_data);
2301 if (recv_max_early_data >= 0)
2302 SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data);
2303
2304 if (cert_comp) {
2305 BIO_printf(bio_s_out, "Compressing certificates\n");
2306 if (!SSL_CTX_compress_certs(ctx, 0))
2307 BIO_printf(bio_s_out, "Error compressing certs on ctx\n");
2308 if (ctx2 != NULL && !SSL_CTX_compress_certs(ctx2, 0))
2309 BIO_printf(bio_s_out, "Error compressing certs on ctx2\n");
2310 }
2311 if (enable_server_rpk)
2312 if (!SSL_CTX_set1_server_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) {
2313 BIO_printf(bio_s_out, "Error setting server certificate types\n");
2314 goto end;
2315 }
2316 if (enable_client_rpk)
2317 if (!SSL_CTX_set1_client_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) {
2318 BIO_printf(bio_s_out, "Error setting server certificate types\n");
2319 goto end;
2320 }
2321
2322 if (rev)
2323 server_cb = rev_body;
2324 else if (www)
2325 server_cb = www_body;
2326 else
2327 server_cb = sv_body;
2328 #ifdef AF_UNIX
2329 if (socket_family == AF_UNIX
2330 && unlink_unix_path)
2331 unlink(host);
2332 #endif
2333 if (tfo)
2334 BIO_printf(bio_s_out, "Listening for TFO\n");
2335 do_server(&accept_socket, host, port, socket_family, socket_type, protocol,
2336 server_cb, context, naccept, bio_s_out, tfo);
2337 print_stats(bio_s_out, ctx);
2338 ret = 0;
2339 end:
2340 SSL_CTX_free(ctx);
2341 SSL_SESSION_free(psksess);
2342 set_keylog_file(NULL, NULL);
2343 X509_free(s_cert);
2344 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2345 X509_free(s_dcert);
2346 EVP_PKEY_free(s_key);
2347 EVP_PKEY_free(s_dkey);
2348 OSSL_STACK_OF_X509_free(s_chain);
2349 OSSL_STACK_OF_X509_free(s_dchain);
2350 OPENSSL_free(pass);
2351 OPENSSL_free(dpass);
2352 OPENSSL_free(host);
2353 OPENSSL_free(port);
2354 X509_VERIFY_PARAM_free(vpm);
2355 free_sessions();
2356 OPENSSL_free(tlscstatp.host);
2357 OPENSSL_free(tlscstatp.port);
2358 OPENSSL_free(tlscstatp.path);
2359 SSL_CTX_free(ctx2);
2360 X509_free(s_cert2);
2361 EVP_PKEY_free(s_key2);
2362 #ifndef OPENSSL_NO_NEXTPROTONEG
2363 OPENSSL_free(next_proto.data);
2364 #endif
2365 OPENSSL_free(alpn_ctx.data);
2366 ssl_excert_free(exc);
2367 sk_OPENSSL_STRING_free(ssl_args);
2368 SSL_CONF_CTX_free(cctx);
2369 release_engine(engine);
2370 BIO_free(bio_s_out);
2371 bio_s_out = NULL;
2372 BIO_free(bio_s_msg);
2373 bio_s_msg = NULL;
2374 #ifdef CHARSET_EBCDIC
2375 BIO_meth_free(methods_ebcdic);
2376 #endif
2377 return ret;
2378 }
2379
2380 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2381 {
2382 BIO_printf(bio, "%4ld items in the session cache\n",
2383 SSL_CTX_sess_number(ssl_ctx));
2384 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
2385 SSL_CTX_sess_connect(ssl_ctx));
2386 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
2387 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2388 BIO_printf(bio, "%4ld client connects that finished\n",
2389 SSL_CTX_sess_connect_good(ssl_ctx));
2390 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
2391 SSL_CTX_sess_accept(ssl_ctx));
2392 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
2393 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2394 BIO_printf(bio, "%4ld server accepts that finished\n",
2395 SSL_CTX_sess_accept_good(ssl_ctx));
2396 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
2397 BIO_printf(bio, "%4ld session cache misses\n",
2398 SSL_CTX_sess_misses(ssl_ctx));
2399 BIO_printf(bio, "%4ld session cache timeouts\n",
2400 SSL_CTX_sess_timeouts(ssl_ctx));
2401 BIO_printf(bio, "%4ld callback cache hits\n",
2402 SSL_CTX_sess_cb_hits(ssl_ctx));
2403 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
2404 SSL_CTX_sess_cache_full(ssl_ctx),
2405 SSL_CTX_sess_get_cache_size(ssl_ctx));
2406 }
2407
2408 static long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len,
2409 int argi, long argl, int ret, size_t *processed)
2410 {
2411 unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio);
2412
2413 switch (cmd) {
2414 case BIO_CB_READ: /* No break here */
2415 case BIO_CB_GETS:
2416 if (p_counter != NULL)
2417 ++*p_counter;
2418 break;
2419 default:
2420 break;
2421 }
2422
2423 if (s_debug) {
2424 BIO_set_callback_arg(bio, (char *)bio_s_out);
2425 ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed);
2426 BIO_set_callback_arg(bio, (char *)p_counter);
2427 }
2428
2429 return ret;
2430 }
2431
2432 static int sv_body(int s, int stype, int prot, unsigned char *context)
2433 {
2434 char *buf = NULL;
2435 fd_set readfds;
2436 int ret = 1, width;
2437 int k;
2438 unsigned long l;
2439 SSL *con = NULL;
2440 BIO *sbio;
2441 struct timeval timeout;
2442 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
2443 struct timeval *timeoutp;
2444 #endif
2445 #ifndef OPENSSL_NO_DTLS
2446 # ifndef OPENSSL_NO_SCTP
2447 int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP);
2448 # else
2449 int isdtls = (stype == SOCK_DGRAM);
2450 # endif
2451 #endif
2452
2453 buf = app_malloc(bufsize, "server buffer");
2454 if (s_nbio) {
2455 if (!BIO_socket_nbio(s, 1))
2456 ERR_print_errors(bio_err);
2457 else if (!s_quiet)
2458 BIO_printf(bio_err, "Turned on non blocking io\n");
2459 }
2460
2461 con = SSL_new(ctx);
2462 if (con == NULL) {
2463 ret = -1;
2464 goto err;
2465 }
2466
2467 if (s_tlsextdebug) {
2468 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2469 SSL_set_tlsext_debug_arg(con, bio_s_out);
2470 }
2471
2472 if (context != NULL
2473 && !SSL_set_session_id_context(con, context,
2474 strlen((char *)context))) {
2475 BIO_printf(bio_err, "Error setting session id context\n");
2476 ret = -1;
2477 goto err;
2478 }
2479
2480 if (!SSL_clear(con)) {
2481 BIO_printf(bio_err, "Error clearing SSL connection\n");
2482 ret = -1;
2483 goto err;
2484 }
2485 #ifndef OPENSSL_NO_DTLS
2486 if (isdtls) {
2487 # ifndef OPENSSL_NO_SCTP
2488 if (prot == IPPROTO_SCTP)
2489 sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2490 else
2491 # endif
2492 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2493 if (sbio == NULL) {
2494 BIO_printf(bio_err, "Unable to create BIO\n");
2495 ERR_print_errors(bio_err);
2496 goto err;
2497 }
2498
2499 if (enable_timeouts) {
2500 timeout.tv_sec = 0;
2501 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2502 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2503
2504 timeout.tv_sec = 0;
2505 timeout.tv_usec = DGRAM_SND_TIMEOUT;
2506 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2507 }
2508
2509 if (socket_mtu) {
2510 if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2511 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2512 DTLS_get_link_min_mtu(con));
2513 ret = -1;
2514 BIO_free(sbio);
2515 goto err;
2516 }
2517 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2518 if (!DTLS_set_link_mtu(con, socket_mtu)) {
2519 BIO_printf(bio_err, "Failed to set MTU\n");
2520 ret = -1;
2521 BIO_free(sbio);
2522 goto err;
2523 }
2524 } else
2525 /* want to do MTU discovery */
2526 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2527
2528 # ifndef OPENSSL_NO_SCTP
2529 if (prot != IPPROTO_SCTP)
2530 # endif
2531 /* Turn on cookie exchange. Not necessary for SCTP */
2532 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2533 } else
2534 #endif
2535 sbio = BIO_new_socket(s, BIO_NOCLOSE);
2536
2537 if (sbio == NULL) {
2538 BIO_printf(bio_err, "Unable to create BIO\n");
2539 ERR_print_errors(bio_err);
2540 goto err;
2541 }
2542
2543 if (s_nbio_test) {
2544 BIO *test;
2545
2546 test = BIO_new(BIO_f_nbio_test());
2547 if (test == NULL) {
2548 BIO_printf(bio_err, "Unable to create BIO\n");
2549 ret = -1;
2550 BIO_free(sbio);
2551 goto err;
2552 }
2553 sbio = BIO_push(test, sbio);
2554 }
2555
2556 SSL_set_bio(con, sbio, sbio);
2557 SSL_set_accept_state(con);
2558 /* SSL_set_fd(con,s); */
2559
2560 BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback);
2561 if (s_msg) {
2562 #ifndef OPENSSL_NO_SSL_TRACE
2563 if (s_msg == 2)
2564 SSL_set_msg_callback(con, SSL_trace);
2565 else
2566 #endif
2567 SSL_set_msg_callback(con, msg_cb);
2568 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2569 }
2570
2571 if (s_tlsextdebug) {
2572 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2573 SSL_set_tlsext_debug_arg(con, bio_s_out);
2574 }
2575
2576 if (early_data) {
2577 int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR;
2578 size_t readbytes;
2579
2580 while (edret != SSL_READ_EARLY_DATA_FINISH) {
2581 for (;;) {
2582 edret = SSL_read_early_data(con, buf, bufsize, &readbytes);
2583 if (edret != SSL_READ_EARLY_DATA_ERROR)
2584 break;
2585
2586 switch (SSL_get_error(con, 0)) {
2587 case SSL_ERROR_WANT_WRITE:
2588 case SSL_ERROR_WANT_ASYNC:
2589 case SSL_ERROR_WANT_READ:
2590 /* Just keep trying - busy waiting */
2591 continue;
2592 default:
2593 BIO_printf(bio_err, "Error reading early data\n");
2594 ERR_print_errors(bio_err);
2595 goto err;
2596 }
2597 }
2598 if (readbytes > 0) {
2599 if (write_header) {
2600 BIO_printf(bio_s_out, "Early data received:\n");
2601 write_header = 0;
2602 }
2603 raw_write_stdout(buf, (unsigned int)readbytes);
2604 (void)BIO_flush(bio_s_out);
2605 }
2606 }
2607 if (write_header) {
2608 if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT)
2609 BIO_printf(bio_s_out, "No early data received\n");
2610 else
2611 BIO_printf(bio_s_out, "Early data was rejected\n");
2612 } else {
2613 BIO_printf(bio_s_out, "\nEnd of early data\n");
2614 }
2615 if (SSL_is_init_finished(con))
2616 print_connection_info(con);
2617 }
2618
2619 if (fileno_stdin() > s)
2620 width = fileno_stdin() + 1;
2621 else
2622 width = s + 1;
2623 for (;;) {
2624 int i;
2625 int read_from_terminal;
2626 int read_from_sslcon;
2627
2628 read_from_terminal = 0;
2629 read_from_sslcon = SSL_has_pending(con)
2630 || (async && SSL_waiting_for_async(con));
2631
2632 if (!read_from_sslcon) {
2633 FD_ZERO(&readfds);
2634 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2635 openssl_fdset(fileno_stdin(), &readfds);
2636 #endif
2637 openssl_fdset(s, &readfds);
2638 /*
2639 * Note: under VMS with SOCKETSHR the second parameter is
2640 * currently of type (int *) whereas under other systems it is
2641 * (void *) if you don't have a cast it will choke the compiler:
2642 * if you do have a cast then you can either go for (int *) or
2643 * (void *).
2644 */
2645 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2646 /*
2647 * Under DOS (non-djgpp) and Windows we can't select on stdin:
2648 * only on sockets. As a workaround we timeout the select every
2649 * second and check for any keypress. In a proper Windows
2650 * application we wouldn't do this because it is inefficient.
2651 */
2652 timeout.tv_sec = 1;
2653 timeout.tv_usec = 0;
2654 i = select(width, (void *)&readfds, NULL, NULL, &timeout);
2655 if (has_stdin_waiting())
2656 read_from_terminal = 1;
2657 if ((i < 0) || (!i && !read_from_terminal))
2658 continue;
2659 #else
2660 if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2661 timeoutp = &timeout;
2662 else
2663 timeoutp = NULL;
2664
2665 i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
2666
2667 if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
2668 BIO_printf(bio_err, "TIMEOUT occurred\n");
2669
2670 if (i <= 0)
2671 continue;
2672 if (FD_ISSET(fileno_stdin(), &readfds))
2673 read_from_terminal = 1;
2674 #endif
2675 if (FD_ISSET(s, &readfds))
2676 read_from_sslcon = 1;
2677 }
2678 if (read_from_terminal) {
2679 if (s_crlf) {
2680 int j, lf_num;
2681
2682 i = raw_read_stdin(buf, bufsize / 2);
2683 lf_num = 0;
2684 /* both loops are skipped when i <= 0 */
2685 for (j = 0; j < i; j++)
2686 if (buf[j] == '\n')
2687 lf_num++;
2688 for (j = i - 1; j >= 0; j--) {
2689 buf[j + lf_num] = buf[j];
2690 if (buf[j] == '\n') {
2691 lf_num--;
2692 i++;
2693 buf[j + lf_num] = '\r';
2694 }
2695 }
2696 assert(lf_num == 0);
2697 } else {
2698 i = raw_read_stdin(buf, bufsize);
2699 }
2700
2701 if (!s_quiet && !s_brief) {
2702 if ((i <= 0) || (buf[0] == 'Q')) {
2703 BIO_printf(bio_s_out, "DONE\n");
2704 (void)BIO_flush(bio_s_out);
2705 BIO_closesocket(s);
2706 close_accept_socket();
2707 ret = -11;
2708 goto err;
2709 }
2710 if ((i <= 0) || (buf[0] == 'q')) {
2711 BIO_printf(bio_s_out, "DONE\n");
2712 (void)BIO_flush(bio_s_out);
2713 if (SSL_version(con) != DTLS1_VERSION)
2714 BIO_closesocket(s);
2715 /*
2716 * close_accept_socket(); ret= -11;
2717 */
2718 goto err;
2719 }
2720 if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2721 SSL_renegotiate(con);
2722 i = SSL_do_handshake(con);
2723 printf("SSL_do_handshake -> %d\n", i);
2724 continue;
2725 }
2726 if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2727 SSL_set_verify(con,
2728 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
2729 NULL);
2730 SSL_renegotiate(con);
2731 i = SSL_do_handshake(con);
2732 printf("SSL_do_handshake -> %d\n", i);
2733 continue;
2734 }
2735 if ((buf[0] == 'K' || buf[0] == 'k')
2736 && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2737 SSL_key_update(con, buf[0] == 'K' ?
2738 SSL_KEY_UPDATE_REQUESTED
2739 : SSL_KEY_UPDATE_NOT_REQUESTED);
2740 i = SSL_do_handshake(con);
2741 printf("SSL_do_handshake -> %d\n", i);
2742 continue;
2743 }
2744 if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) {
2745 SSL_set_verify(con, SSL_VERIFY_PEER, NULL);
2746 i = SSL_verify_client_post_handshake(con);
2747 if (i == 0) {
2748 printf("Failed to initiate request\n");
2749 ERR_print_errors(bio_err);
2750 } else {
2751 i = SSL_do_handshake(con);
2752 printf("SSL_do_handshake -> %d\n", i);
2753 }
2754 continue;
2755 }
2756 if (buf[0] == 'P') {
2757 static const char str[] = "Lets print some clear text\n";
2758 BIO_write(SSL_get_wbio(con), str, sizeof(str) -1);
2759 }
2760 if (buf[0] == 'S') {
2761 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
2762 }
2763 }
2764 #ifdef CHARSET_EBCDIC
2765 ebcdic2ascii(buf, buf, i);
2766 #endif
2767 l = k = 0;
2768 for (;;) {
2769 /* should do a select for the write */
2770 #ifdef RENEG
2771 static count = 0;
2772 if (++count == 100) {
2773 count = 0;
2774 SSL_renegotiate(con);
2775 }
2776 #endif
2777 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2778 #ifndef OPENSSL_NO_SRP
2779 while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) {
2780 BIO_printf(bio_s_out, "LOOKUP renego during write\n");
2781
2782 lookup_srp_user(&srp_callback_parm, bio_s_out);
2783
2784 k = SSL_write(con, &(buf[l]), (unsigned int)i);
2785 }
2786 #endif
2787 switch (SSL_get_error(con, k)) {
2788 case SSL_ERROR_NONE:
2789 break;
2790 case SSL_ERROR_WANT_ASYNC:
2791 BIO_printf(bio_s_out, "Write BLOCK (Async)\n");
2792 (void)BIO_flush(bio_s_out);
2793 wait_for_async(con);
2794 break;
2795 case SSL_ERROR_WANT_WRITE:
2796 case SSL_ERROR_WANT_READ:
2797 case SSL_ERROR_WANT_X509_LOOKUP:
2798 BIO_printf(bio_s_out, "Write BLOCK\n");
2799 (void)BIO_flush(bio_s_out);
2800 break;
2801 case SSL_ERROR_WANT_ASYNC_JOB:
2802 /*
2803 * This shouldn't ever happen in s_server. Treat as an error
2804 */
2805 case SSL_ERROR_SYSCALL:
2806 case SSL_ERROR_SSL:
2807 BIO_printf(bio_s_out, "ERROR\n");
2808 (void)BIO_flush(bio_s_out);
2809 ERR_print_errors(bio_err);
2810 ret = 1;
2811 goto err;
2812 /* break; */
2813 case SSL_ERROR_ZERO_RETURN:
2814 BIO_printf(bio_s_out, "DONE\n");
2815 (void)BIO_flush(bio_s_out);
2816 ret = 1;
2817 goto err;
2818 }
2819 if (k > 0) {
2820 l += k;
2821 i -= k;
2822 }
2823 if (i <= 0)
2824 break;
2825 }
2826 }
2827 if (read_from_sslcon) {
2828 /*
2829 * init_ssl_connection handles all async events itself so if we're
2830 * waiting for async then we shouldn't go back into
2831 * init_ssl_connection
2832 */
2833 if ((!async || !SSL_waiting_for_async(con))
2834 && !SSL_is_init_finished(con)) {
2835 /*
2836 * Count number of reads during init_ssl_connection.
2837 * It helps us to distinguish configuration errors from errors
2838 * caused by a client.
2839 */
2840 unsigned int read_counter = 0;
2841
2842 BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter);
2843 i = init_ssl_connection(con);
2844 BIO_set_callback_arg(SSL_get_rbio(con), NULL);
2845
2846 /*
2847 * If initialization fails without reads, then
2848 * there was a fatal error in configuration.
2849 */
2850 if (i <= 0 && read_counter == 0) {
2851 ret = -1;
2852 goto err;
2853 }
2854 if (i < 0) {
2855 ret = 0;
2856 goto err;
2857 } else if (i == 0) {
2858 ret = 1;
2859 goto err;
2860 }
2861 } else {
2862 again:
2863 i = SSL_read(con, (char *)buf, bufsize);
2864 #ifndef OPENSSL_NO_SRP
2865 while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
2866 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
2867
2868 lookup_srp_user(&srp_callback_parm, bio_s_out);
2869
2870 i = SSL_read(con, (char *)buf, bufsize);
2871 }
2872 #endif
2873 switch (SSL_get_error(con, i)) {
2874 case SSL_ERROR_NONE:
2875 #ifdef CHARSET_EBCDIC
2876 ascii2ebcdic(buf, buf, i);
2877 #endif
2878 raw_write_stdout(buf, (unsigned int)i);
2879 (void)BIO_flush(bio_s_out);
2880 if (SSL_has_pending(con))
2881 goto again;
2882 break;
2883 case SSL_ERROR_WANT_ASYNC:
2884 BIO_printf(bio_s_out, "Read BLOCK (Async)\n");
2885 (void)BIO_flush(bio_s_out);
2886 wait_for_async(con);
2887 break;
2888 case SSL_ERROR_WANT_WRITE:
2889 case SSL_ERROR_WANT_READ:
2890 BIO_printf(bio_s_out, "Read BLOCK\n");
2891 (void)BIO_flush(bio_s_out);
2892 break;
2893 case SSL_ERROR_WANT_ASYNC_JOB:
2894 /*
2895 * This shouldn't ever happen in s_server. Treat as an error
2896 */
2897 case SSL_ERROR_SYSCALL:
2898 case SSL_ERROR_SSL:
2899 BIO_printf(bio_s_out, "ERROR\n");
2900 (void)BIO_flush(bio_s_out);
2901 ERR_print_errors(bio_err);
2902 ret = 1;
2903 goto err;
2904 case SSL_ERROR_ZERO_RETURN:
2905 BIO_printf(bio_s_out, "DONE\n");
2906 (void)BIO_flush(bio_s_out);
2907 ret = 1;
2908 goto err;
2909 }
2910 }
2911 }
2912 }
2913 err:
2914 if (con != NULL) {
2915 BIO_printf(bio_s_out, "shutting down SSL\n");
2916 do_ssl_shutdown(con);
2917 SSL_free(con);
2918 }
2919 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
2920 OPENSSL_clear_free(buf, bufsize);
2921 return ret;
2922 }
2923
2924 static void close_accept_socket(void)
2925 {
2926 BIO_printf(bio_err, "shutdown accept socket\n");
2927 if (accept_socket >= 0) {
2928 BIO_closesocket(accept_socket);
2929 }
2930 }
2931
2932 static int is_retryable(SSL *con, int i)
2933 {
2934 int err = SSL_get_error(con, i);
2935
2936 /* If it's not a fatal error, it must be retryable */
2937 return (err != SSL_ERROR_SSL)
2938 && (err != SSL_ERROR_SYSCALL)
2939 && (err != SSL_ERROR_ZERO_RETURN);
2940 }
2941
2942 static int init_ssl_connection(SSL *con)
2943 {
2944 int i;
2945 long verify_err;
2946 int retry = 0;
2947
2948 if (dtlslisten || stateless) {
2949 BIO_ADDR *client = NULL;
2950
2951 if (dtlslisten) {
2952 if ((client = BIO_ADDR_new()) == NULL) {
2953 BIO_printf(bio_err, "ERROR - memory\n");
2954 return 0;
2955 }
2956 i = DTLSv1_listen(con, client);
2957 } else {
2958 i = SSL_stateless(con);
2959 }
2960 if (i > 0) {
2961 BIO *wbio;
2962 int fd = -1;
2963
2964 if (dtlslisten) {
2965 wbio = SSL_get_wbio(con);
2966 if (wbio) {
2967 BIO_get_fd(wbio, &fd);
2968 }
2969
2970 if (!wbio || BIO_connect(fd, client, 0) == 0) {
2971 BIO_printf(bio_err, "ERROR - unable to connect\n");
2972 BIO_ADDR_free(client);
2973 return 0;
2974 }
2975
2976 (void)BIO_ctrl_set_connected(wbio, client);
2977 BIO_ADDR_free(client);
2978 dtlslisten = 0;
2979 } else {
2980 stateless = 0;
2981 }
2982 i = SSL_accept(con);
2983 } else {
2984 BIO_ADDR_free(client);
2985 }
2986 } else {
2987 do {
2988 i = SSL_accept(con);
2989
2990 if (i <= 0)
2991 retry = is_retryable(con, i);
2992 #ifdef CERT_CB_TEST_RETRY
2993 {
2994 while (i <= 0
2995 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
2996 && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) {
2997 BIO_printf(bio_err,
2998 "LOOKUP from certificate callback during accept\n");
2999 i = SSL_accept(con);
3000 if (i <= 0)
3001 retry = is_retryable(con, i);
3002 }
3003 }
3004 #endif
3005
3006 #ifndef OPENSSL_NO_SRP
3007 while (i <= 0
3008 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
3009 BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
3010 srp_callback_parm.login);
3011
3012 lookup_srp_user(&srp_callback_parm, bio_s_out);
3013
3014 i = SSL_accept(con);
3015 if (i <= 0)
3016 retry = is_retryable(con, i);
3017 }
3018 #endif
3019 } while (i < 0 && SSL_waiting_for_async(con));
3020 }
3021
3022 if (i <= 0) {
3023 if (((dtlslisten || stateless) && i == 0)
3024 || (!dtlslisten && !stateless && retry)) {
3025 BIO_printf(bio_s_out, "DELAY\n");
3026 return 1;
3027 }
3028
3029 BIO_printf(bio_err, "ERROR\n");
3030
3031 verify_err = SSL_get_verify_result(con);
3032 if (verify_err != X509_V_OK) {
3033 BIO_printf(bio_err, "verify error:%s\n",
3034 X509_verify_cert_error_string(verify_err));
3035 }
3036 /* Always print any error messages */
3037 ERR_print_errors(bio_err);
3038 return 0;
3039 }
3040
3041 print_connection_info(con);
3042 return 1;
3043 }
3044
3045 static void print_connection_info(SSL *con)
3046 {
3047 const char *str;
3048 X509 *peer;
3049 char buf[BUFSIZ];
3050 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3051 const unsigned char *next_proto_neg;
3052 unsigned next_proto_neg_len;
3053 #endif
3054 unsigned char *exportedkeymat;
3055 int i;
3056
3057 if (s_brief)
3058 print_ssl_summary(con);
3059
3060 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
3061
3062 peer = SSL_get0_peer_certificate(con);
3063 if (peer != NULL) {
3064 BIO_printf(bio_s_out, "Client certificate\n");
3065 PEM_write_bio_X509(bio_s_out, peer);
3066 dump_cert_text(bio_s_out, peer);
3067 peer = NULL;
3068 }
3069 /* Only display RPK information if configured */
3070 if (SSL_get_negotiated_server_cert_type(con) == TLSEXT_cert_type_rpk)
3071 BIO_printf(bio_s_out, "Server-to-client raw public key negotiated\n");
3072 if (SSL_get_negotiated_client_cert_type(con) == TLSEXT_cert_type_rpk)
3073 BIO_printf(bio_s_out, "Client-to-server raw public key negotiated\n");
3074 if (enable_client_rpk) {
3075 EVP_PKEY *client_rpk = SSL_get0_peer_rpk(con);
3076
3077 if (client_rpk != NULL) {
3078 BIO_printf(bio_s_out, "Client raw public key\n");
3079 EVP_PKEY_print_public(bio_s_out, client_rpk, 2, NULL);
3080 }
3081 }
3082
3083 if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL)
3084 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
3085 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
3086 ssl_print_sigalgs(bio_s_out, con);
3087 #ifndef OPENSSL_NO_EC
3088 ssl_print_point_formats(bio_s_out, con);
3089 ssl_print_groups(bio_s_out, con, 0);
3090 #endif
3091 print_ca_names(bio_s_out, con);
3092 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
3093
3094 #if !defined(OPENSSL_NO_NEXTPROTONEG)
3095 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
3096 if (next_proto_neg) {
3097 BIO_printf(bio_s_out, "NEXTPROTO is ");
3098 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
3099 BIO_printf(bio_s_out, "\n");
3100 }
3101 #endif
3102 #ifndef OPENSSL_NO_SRTP
3103 {
3104 SRTP_PROTECTION_PROFILE *srtp_profile
3105 = SSL_get_selected_srtp_profile(con);
3106
3107 if (srtp_profile)
3108 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
3109 srtp_profile->name);
3110 }
3111 #endif
3112 if (SSL_session_reused(con))
3113 BIO_printf(bio_s_out, "Reused session-id\n");
3114
3115 ssl_print_secure_renegotiation_notes(bio_s_out, con);
3116
3117 if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION))
3118 BIO_printf(bio_s_out, "Renegotiation is DISABLED\n");
3119
3120 if (keymatexportlabel != NULL) {
3121 BIO_printf(bio_s_out, "Keying material exporter:\n");
3122 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
3123 BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
3124 exportedkeymat = app_malloc(keymatexportlen, "export key");
3125 if (SSL_export_keying_material(con, exportedkeymat,
3126 keymatexportlen,
3127 keymatexportlabel,
3128 strlen(keymatexportlabel),
3129 NULL, 0, 0) <= 0) {
3130 BIO_printf(bio_s_out, " Error\n");
3131 } else {
3132 BIO_printf(bio_s_out, " Keying material: ");
3133 for (i = 0; i < keymatexportlen; i++)
3134 BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
3135 BIO_printf(bio_s_out, "\n");
3136 }
3137 OPENSSL_free(exportedkeymat);
3138 }
3139 #ifndef OPENSSL_NO_KTLS
3140 if (BIO_get_ktls_send(SSL_get_wbio(con)))
3141 BIO_printf(bio_err, "Using Kernel TLS for sending\n");
3142 if (BIO_get_ktls_recv(SSL_get_rbio(con)))
3143 BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
3144 #endif
3145
3146 (void)BIO_flush(bio_s_out);
3147 }
3148
3149 static int www_body(int s, int stype, int prot, unsigned char *context)
3150 {
3151 char *buf = NULL, *p;
3152 int ret = 1;
3153 int i, j, k, dot;
3154 SSL *con;
3155 const SSL_CIPHER *c;
3156 BIO *io, *ssl_bio, *sbio;
3157 #ifdef RENEG
3158 int total_bytes = 0;
3159 #endif
3160 int width;
3161 #ifndef OPENSSL_NO_KTLS
3162 int use_sendfile_for_req = use_sendfile;
3163 #endif
3164 fd_set readfds;
3165 const char *opmode;
3166 #ifdef CHARSET_EBCDIC
3167 BIO *filter;
3168 #endif
3169
3170 /* Set width for a select call if needed */
3171 width = s + 1;
3172
3173 /* as we use BIO_gets(), and it always null terminates data, we need
3174 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3175 p = buf = app_malloc(bufsize + 1, "server www buffer");
3176 io = BIO_new(BIO_f_buffer());
3177 ssl_bio = BIO_new(BIO_f_ssl());
3178 if ((io == NULL) || (ssl_bio == NULL))
3179 goto err;
3180
3181 if (s_nbio) {
3182 if (!BIO_socket_nbio(s, 1))
3183 ERR_print_errors(bio_err);
3184 else if (!s_quiet)
3185 BIO_printf(bio_err, "Turned on non blocking io\n");
3186 }
3187
3188 /* lets make the output buffer a reasonable size */
3189 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3190 goto err;
3191
3192 if ((con = SSL_new(ctx)) == NULL)
3193 goto err;
3194
3195 if (s_tlsextdebug) {
3196 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3197 SSL_set_tlsext_debug_arg(con, bio_s_out);
3198 }
3199
3200 if (context != NULL
3201 && !SSL_set_session_id_context(con, context,
3202 strlen((char *)context))) {
3203 SSL_free(con);
3204 goto err;
3205 }
3206
3207 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3208 if (sbio == NULL) {
3209 SSL_free(con);
3210 goto err;
3211 }
3212
3213 if (s_nbio_test) {
3214 BIO *test;
3215
3216 test = BIO_new(BIO_f_nbio_test());
3217 if (test == NULL) {
3218 SSL_free(con);
3219 BIO_free(sbio);
3220 goto err;
3221 }
3222
3223 sbio = BIO_push(test, sbio);
3224 }
3225 SSL_set_bio(con, sbio, sbio);
3226 SSL_set_accept_state(con);
3227
3228 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3229 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3230 BIO_push(io, ssl_bio);
3231 ssl_bio = NULL;
3232 #ifdef CHARSET_EBCDIC
3233 filter = BIO_new(BIO_f_ebcdic_filter());
3234 if (filter == NULL)
3235 goto err;
3236
3237 io = BIO_push(filter, io);
3238 #endif
3239
3240 if (s_debug) {
3241 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3242 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3243 }
3244 if (s_msg) {
3245 #ifndef OPENSSL_NO_SSL_TRACE
3246 if (s_msg == 2)
3247 SSL_set_msg_callback(con, SSL_trace);
3248 else
3249 #endif
3250 SSL_set_msg_callback(con, msg_cb);
3251 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3252 }
3253
3254 for (;;) {
3255 i = BIO_gets(io, buf, bufsize + 1);
3256 if (i < 0) { /* error */
3257 if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) {
3258 if (!s_quiet)
3259 ERR_print_errors(bio_err);
3260 goto err;
3261 } else {
3262 BIO_printf(bio_s_out, "read R BLOCK\n");
3263 #ifndef OPENSSL_NO_SRP
3264 if (BIO_should_io_special(io)
3265 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3266 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3267
3268 lookup_srp_user(&srp_callback_parm, bio_s_out);
3269
3270 continue;
3271 }
3272 #endif
3273 OSSL_sleep(1000);
3274 continue;
3275 }
3276 } else if (i == 0) { /* end of input */
3277 ret = 1;
3278 goto end;
3279 }
3280
3281 /* else we have data */
3282 if ((www == 1 && HAS_PREFIX(buf, "GET "))
3283 || (www == 2 && HAS_PREFIX(buf, "GET /stats "))) {
3284 X509 *peer = NULL;
3285 STACK_OF(SSL_CIPHER) *sk;
3286 static const char *space = " ";
3287
3288 if (www == 1 && HAS_PREFIX(buf, "GET /reneg")) {
3289 if (HAS_PREFIX(buf, "GET /renegcert"))
3290 SSL_set_verify(con,
3291 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
3292 NULL);
3293 i = SSL_renegotiate(con);
3294 BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i);
3295 /* Send the HelloRequest */
3296 i = SSL_do_handshake(con);
3297 if (i <= 0) {
3298 BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n",
3299 SSL_get_error(con, i));
3300 ERR_print_errors(bio_err);
3301 goto err;
3302 }
3303 /* Wait for a ClientHello to come back */
3304 FD_ZERO(&readfds);
3305 openssl_fdset(s, &readfds);
3306 i = select(width, (void *)&readfds, NULL, NULL, NULL);
3307 if (i <= 0 || !FD_ISSET(s, &readfds)) {
3308 BIO_printf(bio_s_out,
3309 "Error waiting for client response\n");
3310 ERR_print_errors(bio_err);
3311 goto err;
3312 }
3313 /*
3314 * We're not actually expecting any data here and we ignore
3315 * any that is sent. This is just to force the handshake that
3316 * we're expecting to come from the client. If they haven't
3317 * sent one there's not much we can do.
3318 */
3319 BIO_gets(io, buf, bufsize + 1);
3320 }
3321
3322 BIO_puts(io,
3323 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3324 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
3325 BIO_puts(io, "<pre>\n");
3326 /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */
3327 BIO_puts(io, "\n");
3328 for (i = 0; i < local_argc; i++) {
3329 const char *myp;
3330
3331 for (myp = local_argv[i]; *myp; myp++)
3332 switch (*myp) {
3333 case '<':
3334 BIO_puts(io, "&lt;");
3335 break;
3336 case '>':
3337 BIO_puts(io, "&gt;");
3338 break;
3339 case '&':
3340 BIO_puts(io, "&amp;");
3341 break;
3342 default:
3343 BIO_write(io, myp, 1);
3344 break;
3345 }
3346 BIO_write(io, " ", 1);
3347 }
3348 BIO_puts(io, "\n");
3349
3350 ssl_print_secure_renegotiation_notes(io, con);
3351
3352 /*
3353 * The following is evil and should not really be done
3354 */
3355 BIO_printf(io, "Ciphers supported in s_server binary\n");
3356 sk = SSL_get_ciphers(con);
3357 j = sk_SSL_CIPHER_num(sk);
3358 for (i = 0; i < j; i++) {
3359 c = sk_SSL_CIPHER_value(sk, i);
3360 BIO_printf(io, "%-11s:%-25s ",
3361 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3362 if ((((i + 1) % 2) == 0) && (i + 1 != j))
3363 BIO_puts(io, "\n");
3364 }
3365 BIO_puts(io, "\n");
3366 p = SSL_get_shared_ciphers(con, buf, bufsize);
3367 if (p != NULL) {
3368 BIO_printf(io,
3369 "---\nCiphers common between both SSL end points:\n");
3370 j = i = 0;
3371 while (*p) {
3372 if (*p == ':') {
3373 BIO_write(io, space, 26 - j);
3374 i++;
3375 j = 0;
3376 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
3377 } else {
3378 BIO_write(io, p, 1);
3379 j++;
3380 }
3381 p++;
3382 }
3383 BIO_puts(io, "\n");
3384 }
3385 ssl_print_sigalgs(io, con);
3386 #ifndef OPENSSL_NO_EC
3387 ssl_print_groups(io, con, 0);
3388 #endif
3389 print_ca_names(io, con);
3390 BIO_printf(io, (SSL_session_reused(con)
3391 ? "---\nReused, " : "---\nNew, "));
3392 c = SSL_get_current_cipher(con);
3393 BIO_printf(io, "%s, Cipher is %s\n",
3394 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3395 SSL_SESSION_print(io, SSL_get_session(con));
3396 BIO_printf(io, "---\n");
3397 print_stats(io, SSL_get_SSL_CTX(con));
3398 BIO_printf(io, "---\n");
3399 peer = SSL_get0_peer_certificate(con);
3400 if (peer != NULL) {
3401 BIO_printf(io, "Client certificate\n");
3402 X509_print(io, peer);
3403 PEM_write_bio_X509(io, peer);
3404 peer = NULL;
3405 } else {
3406 BIO_puts(io, "no client certificate available\n");
3407 }
3408 BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n");
3409 break;
3410 } else if ((www == 2 || www == 3) && CHECK_AND_SKIP_PREFIX(p, "GET /")) {
3411 BIO *file;
3412 char *e;
3413 static const char *text =
3414 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3415
3416 dot = 1;
3417 for (e = p; *e != '\0'; e++) {
3418 if (e[0] == ' ')
3419 break;
3420
3421 if (e[0] == ':') {
3422 /* Windows drive. We treat this the same way as ".." */
3423 dot = -1;
3424 break;
3425 }
3426
3427 switch (dot) {
3428 case 1:
3429 dot = (e[0] == '.') ? 2 : 0;
3430 break;
3431 case 2:
3432 dot = (e[0] == '.') ? 3 : 0;
3433 break;
3434 case 3:
3435 dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0;
3436 break;
3437 }
3438 if (dot == 0)
3439 dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0;
3440 }
3441 dot = (dot == 3) || (dot == -1); /* filename contains ".."
3442 * component */
3443
3444 if (*e == '\0') {
3445 BIO_puts(io, text);
3446 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
3447 break;
3448 }
3449 *e = '\0';
3450
3451 if (dot) {
3452 BIO_puts(io, text);
3453 BIO_printf(io, "'%s' contains '..' or ':'\r\n", p);
3454 break;
3455 }
3456
3457 if (*p == '/' || *p == '\\') {
3458 BIO_puts(io, text);
3459 BIO_printf(io, "'%s' is an invalid path\r\n", p);
3460 break;
3461 }
3462
3463 /* if a directory, do the index thang */
3464 if (app_isdir(p) > 0) {
3465 BIO_puts(io, text);
3466 BIO_printf(io, "'%s' is a directory\r\n", p);
3467 break;
3468 }
3469
3470 opmode = (http_server_binmode == 1) ? "rb" : "r";
3471 if ((file = BIO_new_file(p, opmode)) == NULL) {
3472 BIO_puts(io, text);
3473 BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode);
3474 ERR_print_errors(io);
3475 break;
3476 }
3477
3478 if (!s_quiet)
3479 BIO_printf(bio_err, "FILE:%s\n", p);
3480
3481 if (www == 2) {
3482 i = strlen(p);
3483 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
3484 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
3485 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
3486 BIO_puts(io,
3487 "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
3488 else
3489 BIO_puts(io,
3490 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
3491 }
3492 /* send the file */
3493 #ifndef OPENSSL_NO_KTLS
3494 if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) {
3495 BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n");
3496 use_sendfile_for_req = 0;
3497 }
3498 if (use_sendfile_for_req) {
3499 FILE *fp = NULL;
3500 int fd;
3501 struct stat st;
3502 off_t offset = 0;
3503 size_t filesize;
3504
3505 BIO_get_fp(file, &fp);
3506 fd = fileno(fp);
3507 if (fstat(fd, &st) < 0) {
3508 BIO_printf(io, "Error fstat '%s'\r\n", p);
3509 ERR_print_errors(io);
3510 goto write_error;
3511 }
3512
3513 filesize = st.st_size;
3514 if (((int)BIO_flush(io)) < 0)
3515 goto write_error;
3516
3517 for (;;) {
3518 i = SSL_sendfile(con, fd, offset, filesize, 0);
3519 if (i < 0) {
3520 BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p);
3521 ERR_print_errors(io);
3522 break;
3523 } else {
3524 offset += i;
3525 filesize -= i;
3526 }
3527
3528 if (filesize <= 0) {
3529 if (!s_quiet)
3530 BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p);
3531
3532 break;
3533 }
3534 }
3535 } else
3536 #endif
3537 {
3538 for (;;) {
3539 i = BIO_read(file, buf, bufsize);
3540 if (i <= 0)
3541 break;
3542
3543 #ifdef RENEG
3544 total_bytes += i;
3545 BIO_printf(bio_err, "%d\n", i);
3546 if (total_bytes > 3 * 1024) {
3547 total_bytes = 0;
3548 BIO_printf(bio_err, "RENEGOTIATE\n");
3549 SSL_renegotiate(con);
3550 }
3551 #endif
3552
3553 for (j = 0; j < i;) {
3554 #ifdef RENEG
3555 static count = 0;
3556 if (++count == 13)
3557 SSL_renegotiate(con);
3558 #endif
3559 k = BIO_write(io, &(buf[j]), i - j);
3560 if (k <= 0) {
3561 if (!BIO_should_retry(io)
3562 && !SSL_waiting_for_async(con)) {
3563 goto write_error;
3564 } else {
3565 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
3566 }
3567 } else {
3568 j += k;
3569 }
3570 }
3571 }
3572 }
3573 write_error:
3574 BIO_free(file);
3575 break;
3576 }
3577 }
3578
3579 for (;;) {
3580 i = (int)BIO_flush(io);
3581 if (i <= 0) {
3582 if (!BIO_should_retry(io))
3583 break;
3584 } else
3585 break;
3586 }
3587 end:
3588 /* make sure we reuse sessions */
3589 do_ssl_shutdown(con);
3590
3591 err:
3592 OPENSSL_free(buf);
3593 BIO_free(ssl_bio);
3594 BIO_free_all(io);
3595 return ret;
3596 }
3597
3598 static int rev_body(int s, int stype, int prot, unsigned char *context)
3599 {
3600 char *buf = NULL;
3601 int i;
3602 int ret = 1;
3603 SSL *con;
3604 BIO *io, *ssl_bio, *sbio;
3605 #ifdef CHARSET_EBCDIC
3606 BIO *filter;
3607 #endif
3608
3609 /* as we use BIO_gets(), and it always null terminates data, we need
3610 * to allocate 1 byte longer buffer to fit the full 2^14 byte record */
3611 buf = app_malloc(bufsize + 1, "server rev buffer");
3612 io = BIO_new(BIO_f_buffer());
3613 ssl_bio = BIO_new(BIO_f_ssl());
3614 if ((io == NULL) || (ssl_bio == NULL))
3615 goto err;
3616
3617 /* lets make the output buffer a reasonable size */
3618 if (BIO_set_write_buffer_size(io, bufsize) <= 0)
3619 goto err;
3620
3621 if ((con = SSL_new(ctx)) == NULL)
3622 goto err;
3623
3624 if (s_tlsextdebug) {
3625 SSL_set_tlsext_debug_callback(con, tlsext_cb);
3626 SSL_set_tlsext_debug_arg(con, bio_s_out);
3627 }
3628 if (context != NULL
3629 && !SSL_set_session_id_context(con, context,
3630 strlen((char *)context))) {
3631 SSL_free(con);
3632 ERR_print_errors(bio_err);
3633 goto err;
3634 }
3635
3636 sbio = BIO_new_socket(s, BIO_NOCLOSE);
3637 if (sbio == NULL) {
3638 SSL_free(con);
3639 ERR_print_errors(bio_err);
3640 goto err;
3641 }
3642
3643 SSL_set_bio(con, sbio, sbio);
3644 SSL_set_accept_state(con);
3645
3646 /* No need to free |con| after this. Done by BIO_free(ssl_bio) */
3647 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
3648 BIO_push(io, ssl_bio);
3649 ssl_bio = NULL;
3650 #ifdef CHARSET_EBCDIC
3651 filter = BIO_new(BIO_f_ebcdic_filter());
3652 if (filter == NULL)
3653 goto err;
3654
3655 io = BIO_push(filter, io);
3656 #endif
3657
3658 if (s_debug) {
3659 BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback);
3660 BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
3661 }
3662 if (s_msg) {
3663 #ifndef OPENSSL_NO_SSL_TRACE
3664 if (s_msg == 2)
3665 SSL_set_msg_callback(con, SSL_trace);
3666 else
3667 #endif
3668 SSL_set_msg_callback(con, msg_cb);
3669 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
3670 }
3671
3672 for (;;) {
3673 i = BIO_do_handshake(io);
3674 if (i > 0)
3675 break;
3676 if (!BIO_should_retry(io)) {
3677 BIO_puts(bio_err, "CONNECTION FAILURE\n");
3678 ERR_print_errors(bio_err);
3679 goto end;
3680 }
3681 #ifndef OPENSSL_NO_SRP
3682 if (BIO_should_io_special(io)
3683 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3684 BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
3685
3686 lookup_srp_user(&srp_callback_parm, bio_s_out);
3687
3688 continue;
3689 }
3690 #endif
3691 }
3692 BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
3693 print_ssl_summary(con);
3694
3695 for (;;) {
3696 i = BIO_gets(io, buf, bufsize + 1);
3697 if (i < 0) { /* error */
3698 if (!BIO_should_retry(io)) {
3699 if (!s_quiet)
3700 ERR_print_errors(bio_err);
3701 goto err;
3702 } else {
3703 BIO_printf(bio_s_out, "read R BLOCK\n");
3704 #ifndef OPENSSL_NO_SRP
3705 if (BIO_should_io_special(io)
3706 && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
3707 BIO_printf(bio_s_out, "LOOKUP renego during read\n");
3708
3709 lookup_srp_user(&srp_callback_parm, bio_s_out);
3710
3711 continue;
3712 }
3713 #endif
3714 OSSL_sleep(1000);
3715 continue;
3716 }
3717 } else if (i == 0) { /* end of input */
3718 ret = 1;
3719 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3720 goto end;
3721 } else {
3722 char *p = buf + i - 1;
3723 while (i && (*p == '\n' || *p == '\r')) {
3724 p--;
3725 i--;
3726 }
3727 if (!s_ign_eof && i == 5 && HAS_PREFIX(buf, "CLOSE")) {
3728 ret = 1;
3729 BIO_printf(bio_err, "CONNECTION CLOSED\n");
3730 goto end;
3731 }
3732 BUF_reverse((unsigned char *)buf, NULL, i);
3733 buf[i] = '\n';
3734 BIO_write(io, buf, i + 1);
3735 for (;;) {
3736 i = BIO_flush(io);
3737 if (i > 0)
3738 break;
3739 if (!BIO_should_retry(io))
3740 goto end;
3741 }
3742 }
3743 }
3744 end:
3745 /* make sure we reuse sessions */
3746 do_ssl_shutdown(con);
3747
3748 err:
3749
3750 OPENSSL_free(buf);
3751 BIO_free(ssl_bio);
3752 BIO_free_all(io);
3753 return ret;
3754 }
3755
3756 #define MAX_SESSION_ID_ATTEMPTS 10
3757 static int generate_session_id(SSL *ssl, unsigned char *id,
3758 unsigned int *id_len)
3759 {
3760 unsigned int count = 0;
3761 unsigned int session_id_prefix_len = strlen(session_id_prefix);
3762
3763 do {
3764 if (RAND_bytes(id, *id_len) <= 0)
3765 return 0;
3766 /*
3767 * Prefix the session_id with the required prefix. NB: If our prefix
3768 * is too long, clip it - but there will be worse effects anyway, eg.
3769 * the server could only possibly create 1 session ID (ie. the
3770 * prefix!) so all future session negotiations will fail due to
3771 * conflicts.
3772 */
3773 memcpy(id, session_id_prefix,
3774 (session_id_prefix_len < *id_len) ?
3775 session_id_prefix_len : *id_len);
3776 }
3777 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
3778 (++count < MAX_SESSION_ID_ATTEMPTS));
3779 if (count >= MAX_SESSION_ID_ATTEMPTS)
3780 return 0;
3781 return 1;
3782 }
3783
3784 /*
3785 * By default s_server uses an in-memory cache which caches SSL_SESSION
3786 * structures without any serialization. This hides some bugs which only
3787 * become apparent in deployed servers. By implementing a basic external
3788 * session cache some issues can be debugged using s_server.
3789 */
3790
3791 typedef struct simple_ssl_session_st {
3792 unsigned char *id;
3793 unsigned int idlen;
3794 unsigned char *der;
3795 int derlen;
3796 struct simple_ssl_session_st *next;
3797 } simple_ssl_session;
3798
3799 static simple_ssl_session *first = NULL;
3800
3801 static int add_session(SSL *ssl, SSL_SESSION *session)
3802 {
3803 simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session");
3804 unsigned char *p;
3805
3806 SSL_SESSION_get_id(session, &sess->idlen);
3807 sess->derlen = i2d_SSL_SESSION(session, NULL);
3808 if (sess->derlen < 0) {
3809 BIO_printf(bio_err, "Error encoding session\n");
3810 OPENSSL_free(sess);
3811 return 0;
3812 }
3813
3814 sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
3815 sess->der = app_malloc(sess->derlen, "get session buffer");
3816 if (!sess->id) {
3817 BIO_printf(bio_err, "Out of memory adding to external cache\n");
3818 OPENSSL_free(sess->id);
3819 OPENSSL_free(sess->der);
3820 OPENSSL_free(sess);
3821 return 0;
3822 }
3823 p = sess->der;
3824
3825 /* Assume it still works. */
3826 if (i2d_SSL_SESSION(session, &p) != sess->derlen) {
3827 BIO_printf(bio_err, "Unexpected session encoding length\n");
3828 OPENSSL_free(sess->id);
3829 OPENSSL_free(sess->der);
3830 OPENSSL_free(sess);
3831 return 0;
3832 }
3833
3834 sess->next = first;
3835 first = sess;
3836 BIO_printf(bio_err, "New session added to external cache\n");
3837 return 0;
3838 }
3839
3840 static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen,
3841 int *do_copy)
3842 {
3843 simple_ssl_session *sess;
3844 *do_copy = 0;
3845 for (sess = first; sess; sess = sess->next) {
3846 if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
3847 const unsigned char *p = sess->der;
3848 BIO_printf(bio_err, "Lookup session: cache hit\n");
3849 return d2i_SSL_SESSION_ex(NULL, &p, sess->derlen, app_get0_libctx(),
3850 app_get0_propq());
3851 }
3852 }
3853 BIO_printf(bio_err, "Lookup session: cache miss\n");
3854 return NULL;
3855 }
3856
3857 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
3858 {
3859 simple_ssl_session *sess, *prev = NULL;
3860 const unsigned char *id;
3861 unsigned int idlen;
3862 id = SSL_SESSION_get_id(session, &idlen);
3863 for (sess = first; sess; sess = sess->next) {
3864 if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
3865 if (prev)
3866 prev->next = sess->next;
3867 else
3868 first = sess->next;
3869 OPENSSL_free(sess->id);
3870 OPENSSL_free(sess->der);
3871 OPENSSL_free(sess);
3872 return;
3873 }
3874 prev = sess;
3875 }
3876 }
3877
3878 static void init_session_cache_ctx(SSL_CTX *sctx)
3879 {
3880 SSL_CTX_set_session_cache_mode(sctx,
3881 SSL_SESS_CACHE_NO_INTERNAL |
3882 SSL_SESS_CACHE_SERVER);
3883 SSL_CTX_sess_set_new_cb(sctx, add_session);
3884 SSL_CTX_sess_set_get_cb(sctx, get_session);
3885 SSL_CTX_sess_set_remove_cb(sctx, del_session);
3886 }
3887
3888 static void free_sessions(void)
3889 {
3890 simple_ssl_session *sess, *tsess;
3891 for (sess = first; sess;) {
3892 OPENSSL_free(sess->id);
3893 OPENSSL_free(sess->der);
3894 tsess = sess;
3895 sess = sess->next;
3896 OPENSSL_free(tsess);
3897 }
3898 first = NULL;
3899 }
3900
3901 #endif /* OPENSSL_NO_SOCK */