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