VirtualBox

source: vbox/trunk/src/libs/openssl-3.1.7/apps/s_server.c@ 107850

Last change on this file since 107850 was 104078, checked in by vboxsync, 11 months ago

openssl-3.1.5: Applied and adjusted our OpenSSL changes to 3.1.4. bugref:10638

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette