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