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