Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/apps/s_server.c

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