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