source: rtems-libbsd/freebsd/crypto/openssl/apps/s_server.c @ 0a699e7

5-freebsd-126-freebsd-12
Last change on this file since 0a699e7 was 0a699e7, checked in by Christian Mauderer <christian.mauderer@…>, on 03/28/19 at 06:13:59

bin/openssl: Import from FreeBSD.

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