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