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