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