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