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