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