Add TLS exporter.
[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 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
144  * deprecated functions for openssl-internal code */
145 #ifdef OPENSSL_NO_DEPRECATED
146 #undef OPENSSL_NO_DEPRECATED
147 #endif
148
149 #include <assert.h>
150 #include <ctype.h>
151 #include <stdio.h>
152 #include <stdlib.h>
153 #include <string.h>
154
155 #include <openssl/e_os2.h>
156 #ifdef OPENSSL_NO_STDIO
157 #define APPS_WIN16
158 #endif
159
160 #if !defined(OPENSSL_SYS_NETWARE)  /* conflicts with winsock2 stuff on netware */
161 #include <sys/types.h>
162 #endif
163
164 /* With IPv6, it looks like Digital has mixed up the proper order of
165    recursive header file inclusion, resulting in the compiler complaining
166    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
167    is needed to have fileno() declared correctly...  So let's define u_int */
168 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
169 #define __U_INT
170 typedef unsigned int u_int;
171 #endif
172
173 #include <openssl/lhash.h>
174 #include <openssl/bn.h>
175 #define USE_SOCKETS
176 #include "apps.h"
177 #include <openssl/err.h>
178 #include <openssl/pem.h>
179 #include <openssl/x509.h>
180 #include <openssl/ssl.h>
181 #include <openssl/rand.h>
182 #include <openssl/ocsp.h>
183 #ifndef OPENSSL_NO_DH
184 #include <openssl/dh.h>
185 #endif
186 #ifndef OPENSSL_NO_RSA
187 #include <openssl/rsa.h>
188 #endif
189 #ifndef OPENSSL_NO_SRP
190 #include <openssl/srp.h>
191 #endif
192 #include "s_apps.h"
193 #include "timeouts.h"
194
195 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
196 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
197 #undef FIONBIO
198 #endif
199
200 #if defined(OPENSSL_SYS_BEOS_R5)
201 #include <fcntl.h>
202 #endif
203
204 #ifndef OPENSSL_NO_RSA
205 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
206 #endif
207 static int sv_body(char *hostname, int s, unsigned char *context);
208 static int www_body(char *hostname, int s, unsigned char *context);
209 static void close_accept_socket(void );
210 static void sv_usage(void);
211 static int init_ssl_connection(SSL *s);
212 static void print_stats(BIO *bp,SSL_CTX *ctx);
213 static int generate_session_id(const SSL *ssl, unsigned char *id,
214                                 unsigned int *id_len);
215 #ifndef OPENSSL_NO_DH
216 static DH *load_dh_param(const char *dhfile);
217 static DH *get_dh512(void);
218 #endif
219
220 #ifdef MONOLITH
221 static void s_server_init(void);
222 #endif
223
224 #ifndef OPENSSL_NO_DH
225 static unsigned char dh512_p[]={
226         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
227         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
228         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
229         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
230         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
231         0x47,0x74,0xE8,0x33,
232         };
233 static unsigned char dh512_g[]={
234         0x02,
235         };
236
237 static DH *get_dh512(void)
238         {
239         DH *dh=NULL;
240
241         if ((dh=DH_new()) == NULL) return(NULL);
242         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
243         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
244         if ((dh->p == NULL) || (dh->g == NULL))
245                 return(NULL);
246         return(dh);
247         }
248 #endif
249
250
251 /* static int load_CA(SSL_CTX *ctx, char *file);*/
252
253 #undef BUFSIZZ
254 #define BUFSIZZ 16*1024
255 static int bufsize=BUFSIZZ;
256 static int accept_socket= -1;
257
258 #define TEST_CERT       "server.pem"
259 #ifndef OPENSSL_NO_TLSEXT
260 #define TEST_CERT2      "server2.pem"
261 #endif
262 #undef PROG
263 #define PROG            s_server_main
264
265 extern int verify_depth, verify_return_error;
266
267 static char *cipher=NULL;
268 static int s_server_verify=SSL_VERIFY_NONE;
269 static int s_server_session_id_context = 1; /* anything will do */
270 static const char *s_cert_file=TEST_CERT,*s_key_file=NULL;
271 #ifndef OPENSSL_NO_TLSEXT
272 static const char *s_cert_file2=TEST_CERT2,*s_key_file2=NULL;
273 #endif
274 static char *s_dcert_file=NULL,*s_dkey_file=NULL;
275 #ifdef FIONBIO
276 static int s_nbio=0;
277 #endif
278 static int s_nbio_test=0;
279 int s_crlf=0;
280 static SSL_CTX *ctx=NULL;
281 #ifndef OPENSSL_NO_TLSEXT
282 static SSL_CTX *ctx2=NULL;
283 #endif
284 static int www=0;
285
286 static BIO *bio_s_out=NULL;
287 static int s_debug=0;
288 #ifndef OPENSSL_NO_TLSEXT
289 static int s_tlsextdebug=0;
290 static int s_tlsextstatus=0;
291 static int cert_status_cb(SSL *s, void *arg);
292 #endif
293 static int s_msg=0;
294 static int s_quiet=0;
295
296 static char *keymatexportlabel=NULL;
297 static int keymatexportlen=20;
298
299 static int hack=0;
300 #ifndef OPENSSL_NO_ENGINE
301 static char *engine_id=NULL;
302 #endif
303 static const char *session_id_prefix=NULL;
304
305 static int enable_timeouts = 0;
306 static long socket_mtu;
307 #ifndef OPENSSL_NO_DTLS1
308 static int cert_chain = 0;
309 #endif
310
311
312 #ifndef OPENSSL_NO_PSK
313 static char *psk_identity="Client_identity";
314 char *psk_key=NULL; /* by default PSK is not used */
315
316 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
317         unsigned char *psk, unsigned int max_psk_len)
318         {
319         unsigned int psk_len = 0;
320         int ret;
321         BIGNUM *bn = NULL;
322
323         if (s_debug)
324                 BIO_printf(bio_s_out,"psk_server_cb\n");
325         if (!identity)
326                 {
327                 BIO_printf(bio_err,"Error: client did not send PSK identity\n");
328                 goto out_err;
329                 }
330         if (s_debug)
331                 BIO_printf(bio_s_out,"identity_len=%d identity=%s\n",
332                         identity ? (int)strlen(identity) : 0, identity);
333
334         /* here we could lookup the given identity e.g. from a database */
335         if (strcmp(identity, psk_identity) != 0)
336                 {
337                 BIO_printf(bio_s_out, "PSK error: client identity not found"
338                            " (got '%s' expected '%s')\n", identity,
339                            psk_identity);
340                 goto out_err;
341                 }
342         if (s_debug)
343                 BIO_printf(bio_s_out, "PSK client identity found\n");
344
345         /* convert the PSK key to binary */
346         ret = BN_hex2bn(&bn, psk_key);
347         if (!ret)
348                 {
349                 BIO_printf(bio_err,"Could not convert PSK key '%s' to BIGNUM\n", psk_key);
350                 if (bn)
351                         BN_free(bn);
352                 return 0;
353                 }
354         if (BN_num_bytes(bn) > (int)max_psk_len)
355                 {
356                 BIO_printf(bio_err,"psk buffer of callback is too small (%d) for key (%d)\n",
357                         max_psk_len, BN_num_bytes(bn));
358                 BN_free(bn);
359                 return 0;
360                 }
361
362         ret = BN_bn2bin(bn, psk);
363         BN_free(bn);
364
365         if (ret < 0)
366                 goto out_err;
367         psk_len = (unsigned int)ret;
368
369         if (s_debug)
370                 BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
371         return psk_len;
372  out_err:
373         if (s_debug)
374                 BIO_printf(bio_err, "Error in PSK server callback\n");
375         return 0;
376         }
377 #endif
378
379 #ifndef OPENSSL_NO_SRP
380 /* This is a context that we pass to callbacks */
381 typedef struct srpsrvparm_st
382         {
383         int verbose;
384         char *login;
385         SRP_VBASE *vb;
386         } srpsrvparm;
387
388 static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
389         {
390         srpsrvparm *p = (srpsrvparm *) arg;
391         SRP_user_pwd *user;
392
393         p->login = BUF_strdup(SSL_get_srp_username(s));
394         BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
395
396         user = SRP_VBASE_get_by_user(p->vb, p->login);
397         if (user == NULL)
398                 {
399                 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
400                 return SSL3_AL_FATAL;
401                 }
402         if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
403                                      user->info) < 0)
404                 {
405                 *ad = SSL_AD_INTERNAL_ERROR;
406                 return SSL3_AL_FATAL;
407                 }
408         return SSL_ERROR_NONE;
409         }
410
411 #endif
412
413 #ifdef MONOLITH
414 static void s_server_init(void)
415         {
416         accept_socket=-1;
417         cipher=NULL;
418         s_server_verify=SSL_VERIFY_NONE;
419         s_dcert_file=NULL;
420         s_dkey_file=NULL;
421         s_cert_file=TEST_CERT;
422         s_key_file=NULL;
423 #ifndef OPENSSL_NO_TLSEXT
424         s_cert_file2=TEST_CERT2;
425         s_key_file2=NULL;
426         ctx2=NULL;
427 #endif
428 #ifdef FIONBIO
429         s_nbio=0;
430 #endif
431         s_nbio_test=0;
432         ctx=NULL;
433         www=0;
434
435         bio_s_out=NULL;
436         s_debug=0;
437         s_msg=0;
438         s_quiet=0;
439         hack=0;
440 #ifndef OPENSSL_NO_ENGINE
441         engine_id=NULL;
442 #endif
443         }
444 #endif
445
446 static void sv_usage(void)
447         {
448         BIO_printf(bio_err,"usage: s_server [args ...]\n");
449         BIO_printf(bio_err,"\n");
450         BIO_printf(bio_err," -accept arg   - port to accept on (default is %d)\n",PORT);
451         BIO_printf(bio_err," -context arg  - set session ID context\n");
452         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
453         BIO_printf(bio_err," -Verify arg   - turn on peer certificate verification, must have a cert.\n");
454         BIO_printf(bio_err," -cert arg     - certificate file to use\n");
455         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT);
456         BIO_printf(bio_err," -crl_check    - check the peer certificate has not been revoked by its CA.\n" \
457                            "                 The CRL(s) are appended to the certificate file\n");
458         BIO_printf(bio_err," -crl_check_all - check the peer certificate has not been revoked by its CA\n" \
459                            "                 or any other CRL in the CA chain. CRL(s) are appened to the\n" \
460                            "                 the certificate file.\n");
461         BIO_printf(bio_err," -certform arg - certificate format (PEM or DER) PEM default\n");
462         BIO_printf(bio_err," -key arg      - Private Key file to use, in cert file if\n");
463         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT);
464         BIO_printf(bio_err," -keyform arg  - key format (PEM, DER or ENGINE) PEM default\n");
465         BIO_printf(bio_err," -pass arg     - private key file pass phrase source\n");
466         BIO_printf(bio_err," -dcert arg    - second certificate file to use (usually for DSA)\n");
467         BIO_printf(bio_err," -dcertform x  - second certificate format (PEM or DER) PEM default\n");
468         BIO_printf(bio_err," -dkey arg     - second private key file to use (usually for DSA)\n");
469         BIO_printf(bio_err," -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n");
470         BIO_printf(bio_err," -dpass arg    - second private key file pass phrase source\n");
471         BIO_printf(bio_err," -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
472         BIO_printf(bio_err,"                 or a default set of parameters is used\n");
473 #ifndef OPENSSL_NO_ECDH
474         BIO_printf(bio_err," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
475                            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
476                            "                 (default is nistp256).\n");
477 #endif
478 #ifdef FIONBIO
479         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
480 #endif
481         BIO_printf(bio_err," -nbio_test    - test with the non-blocking test bio\n");
482         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
483         BIO_printf(bio_err," -debug        - Print more output\n");
484         BIO_printf(bio_err," -msg          - Show protocol messages\n");
485         BIO_printf(bio_err," -state        - Print the SSL states\n");
486         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
487         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
488         BIO_printf(bio_err," -nocert       - Don't use any certificates (Anon-DH)\n");
489         BIO_printf(bio_err," -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
490         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences\n");
491         BIO_printf(bio_err," -quiet        - No server output\n");
492         BIO_printf(bio_err," -no_tmp_rsa   - Do not generate a tmp RSA key\n");
493 #ifndef OPENSSL_NO_PSK
494         BIO_printf(bio_err," -psk_hint arg - PSK identity hint to use\n");
495         BIO_printf(bio_err," -psk arg      - PSK in hex (without 0x)\n");
496 # ifndef OPENSSL_NO_JPAKE
497         BIO_printf(bio_err," -jpake arg    - JPAKE secret to use\n");
498 # endif
499 #endif
500 #ifndef OPENSSL_NO_SRP
501         BIO_printf(bio_err," -srpvfile file      - The verifier file for SRP\n");
502         BIO_printf(bio_err," -srpuserseed string - A seed string for a default user salt.\n");
503 #endif
504         BIO_printf(bio_err," -ssl2         - Just talk SSLv2\n");
505         BIO_printf(bio_err," -ssl3         - Just talk SSLv3\n");
506         BIO_printf(bio_err," -tls1_2       - Just talk TLSv1.2\n");
507         BIO_printf(bio_err," -tls1_1       - Just talk TLSv1.1\n");
508         BIO_printf(bio_err," -tls1         - Just talk TLSv1\n");
509         BIO_printf(bio_err," -dtls1        - Just talk DTLSv1\n");
510         BIO_printf(bio_err," -timeout      - Enable timeouts\n");
511         BIO_printf(bio_err," -mtu          - Set link layer MTU\n");
512         BIO_printf(bio_err," -chain        - Read a certificate chain\n");
513         BIO_printf(bio_err," -no_ssl2      - Just disable SSLv2\n");
514         BIO_printf(bio_err," -no_ssl3      - Just disable SSLv3\n");
515         BIO_printf(bio_err," -no_tls1      - Just disable TLSv1\n");
516         BIO_printf(bio_err," -no_tls1_1    - Just disable TLSv1.1\n");
517         BIO_printf(bio_err," -no_tls1_2    - Just disable TLSv1.2\n");
518 #ifndef OPENSSL_NO_DH
519         BIO_printf(bio_err," -no_dhe       - Disable ephemeral DH\n");
520 #endif
521 #ifndef OPENSSL_NO_ECDH
522         BIO_printf(bio_err," -no_ecdhe     - Disable ephemeral ECDH\n");
523 #endif
524         BIO_printf(bio_err," -bugs         - Turn on SSL bug compatibility\n");
525         BIO_printf(bio_err," -www          - Respond to a 'GET /' with a status page\n");
526         BIO_printf(bio_err," -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
527         BIO_printf(bio_err," -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
528         BIO_printf(bio_err,"                 with the assumption it contains a complete HTTP response.\n");
529 #ifndef OPENSSL_NO_ENGINE
530         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
531 #endif
532         BIO_printf(bio_err," -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
533         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
534 #ifndef OPENSSL_NO_TLSEXT
535         BIO_printf(bio_err," -servername host - servername for HostName TLS extension\n");
536         BIO_printf(bio_err," -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
537         BIO_printf(bio_err," -cert2 arg    - certificate file to use for servername\n");
538         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT2);
539         BIO_printf(bio_err," -key2 arg     - Private Key file to use for servername, in cert file if\n");
540         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT2);
541         BIO_printf(bio_err," -tlsextdebug  - hex dump of all TLS extensions received\n");
542         BIO_printf(bio_err," -no_ticket    - disable use of RFC4507bis session tickets\n");
543         BIO_printf(bio_err," -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n");
544 # ifndef OPENSSL_NO_NEXTPROTONEG
545         BIO_printf(bio_err," -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
546 # endif
547         BIO_printf(bio_err," -use_srtp profiles - Offer SRTP key management with a colon-separated profile list");
548 #endif
549         BIO_printf(bio_err," -keymatexport label   - Export keying material using label\n");
550         BIO_printf(bio_err," -keymatexportlen len  - Export len bytes of keying material (default 20)\n");
551         }
552
553 static int local_argc=0;
554 static char **local_argv;
555
556 #ifdef CHARSET_EBCDIC
557 static int ebcdic_new(BIO *bi);
558 static int ebcdic_free(BIO *a);
559 static int ebcdic_read(BIO *b, char *out, int outl);
560 static int ebcdic_write(BIO *b, const char *in, int inl);
561 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
562 static int ebcdic_gets(BIO *bp, char *buf, int size);
563 static int ebcdic_puts(BIO *bp, const char *str);
564
565 #define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
566 static BIO_METHOD methods_ebcdic=
567         {
568         BIO_TYPE_EBCDIC_FILTER,
569         "EBCDIC/ASCII filter",
570         ebcdic_write,
571         ebcdic_read,
572         ebcdic_puts,
573         ebcdic_gets,
574         ebcdic_ctrl,
575         ebcdic_new,
576         ebcdic_free,
577         };
578
579 typedef struct
580 {
581         size_t  alloced;
582         char    buff[1];
583 } EBCDIC_OUTBUFF;
584
585 BIO_METHOD *BIO_f_ebcdic_filter()
586 {
587         return(&methods_ebcdic);
588 }
589
590 static int ebcdic_new(BIO *bi)
591 {
592         EBCDIC_OUTBUFF *wbuf;
593
594         wbuf = (EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
595         wbuf->alloced = 1024;
596         wbuf->buff[0] = '\0';
597
598         bi->ptr=(char *)wbuf;
599         bi->init=1;
600         bi->flags=0;
601         return(1);
602 }
603
604 static int ebcdic_free(BIO *a)
605 {
606         if (a == NULL) return(0);
607         if (a->ptr != NULL)
608                 OPENSSL_free(a->ptr);
609         a->ptr=NULL;
610         a->init=0;
611         a->flags=0;
612         return(1);
613 }
614         
615 static int ebcdic_read(BIO *b, char *out, int outl)
616 {
617         int ret=0;
618
619         if (out == NULL || outl == 0) return(0);
620         if (b->next_bio == NULL) return(0);
621
622         ret=BIO_read(b->next_bio,out,outl);
623         if (ret > 0)
624                 ascii2ebcdic(out,out,ret);
625         return(ret);
626 }
627
628 static int ebcdic_write(BIO *b, const char *in, int inl)
629 {
630         EBCDIC_OUTBUFF *wbuf;
631         int ret=0;
632         int num;
633         unsigned char n;
634
635         if ((in == NULL) || (inl <= 0)) return(0);
636         if (b->next_bio == NULL) return(0);
637
638         wbuf=(EBCDIC_OUTBUFF *)b->ptr;
639
640         if (inl > (num = wbuf->alloced))
641         {
642                 num = num + num;  /* double the size */
643                 if (num < inl)
644                         num = inl;
645                 OPENSSL_free(wbuf);
646                 wbuf=(EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
647
648                 wbuf->alloced = num;
649                 wbuf->buff[0] = '\0';
650
651                 b->ptr=(char *)wbuf;
652         }
653
654         ebcdic2ascii(wbuf->buff, in, inl);
655
656         ret=BIO_write(b->next_bio, wbuf->buff, inl);
657
658         return(ret);
659 }
660
661 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
662 {
663         long ret;
664
665         if (b->next_bio == NULL) return(0);
666         switch (cmd)
667         {
668         case BIO_CTRL_DUP:
669                 ret=0L;
670                 break;
671         default:
672                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
673                 break;
674         }
675         return(ret);
676 }
677
678 static int ebcdic_gets(BIO *bp, char *buf, int size)
679 {
680         int i, ret=0;
681         if (bp->next_bio == NULL) return(0);
682 /*      return(BIO_gets(bp->next_bio,buf,size));*/
683         for (i=0; i<size-1; ++i)
684         {
685                 ret = ebcdic_read(bp,&buf[i],1);
686                 if (ret <= 0)
687                         break;
688                 else if (buf[i] == '\n')
689                 {
690                         ++i;
691                         break;
692                 }
693         }
694         if (i < size)
695                 buf[i] = '\0';
696         return (ret < 0 && i == 0) ? ret : i;
697 }
698
699 static int ebcdic_puts(BIO *bp, const char *str)
700 {
701         if (bp->next_bio == NULL) return(0);
702         return ebcdic_write(bp, str, strlen(str));
703 }
704 #endif
705
706 #ifndef OPENSSL_NO_TLSEXT
707
708 /* This is a context that we pass to callbacks */
709 typedef struct tlsextctx_st {
710    char * servername;
711    BIO * biodebug;
712    int extension_error;
713 } tlsextctx;
714
715
716 static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
717         {
718         tlsextctx * p = (tlsextctx *) arg;
719         const char * servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
720         if (servername && p->biodebug) 
721                 BIO_printf(p->biodebug,"Hostname in TLS extension: \"%s\"\n",servername);
722         
723         if (!p->servername)
724                 return SSL_TLSEXT_ERR_NOACK;
725         
726         if (servername)
727                 {
728                 if (strcmp(servername,p->servername)) 
729                         return p->extension_error;
730                 if (ctx2)
731                         {
732                         BIO_printf(p->biodebug,"Switching server context.\n");
733                         SSL_set_SSL_CTX(s,ctx2);
734                         }     
735                 }
736         return SSL_TLSEXT_ERR_OK;
737 }
738
739 /* Structure passed to cert status callback */
740
741 typedef struct tlsextstatusctx_st {
742    /* Default responder to use */
743    char *host, *path, *port;
744    int use_ssl;
745    int timeout;
746    BIO *err;
747    int verbose;
748 } tlsextstatusctx;
749
750 static tlsextstatusctx tlscstatp = {NULL, NULL, NULL, 0, -1, NULL, 0};
751
752 /* Certificate Status callback. This is called when a client includes a
753  * certificate status request extension.
754  *
755  * This is a simplified version. It examines certificates each time and
756  * makes one OCSP responder query for each request.
757  *
758  * A full version would store details such as the OCSP certificate IDs and
759  * minimise the number of OCSP responses by caching them until they were
760  * considered "expired".
761  */
762
763 static int cert_status_cb(SSL *s, void *arg)
764         {
765         tlsextstatusctx *srctx = arg;
766         BIO *err = srctx->err;
767         char *host, *port, *path;
768         int use_ssl;
769         unsigned char *rspder = NULL;
770         int rspderlen;
771         STACK_OF(OPENSSL_STRING) *aia = NULL;
772         X509 *x = NULL;
773         X509_STORE_CTX inctx;
774         X509_OBJECT obj;
775         OCSP_REQUEST *req = NULL;
776         OCSP_RESPONSE *resp = NULL;
777         OCSP_CERTID *id = NULL;
778         STACK_OF(X509_EXTENSION) *exts;
779         int ret = SSL_TLSEXT_ERR_NOACK;
780         int i;
781 #if 0
782 STACK_OF(OCSP_RESPID) *ids;
783 SSL_get_tlsext_status_ids(s, &ids);
784 BIO_printf(err, "cert_status: received %d ids\n", sk_OCSP_RESPID_num(ids));
785 #endif
786         if (srctx->verbose)
787                 BIO_puts(err, "cert_status: callback called\n");
788         /* Build up OCSP query from server certificate */
789         x = SSL_get_certificate(s);
790         aia = X509_get1_ocsp(x);
791         if (aia)
792                 {
793                 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
794                         &host, &port, &path, &use_ssl))
795                         {
796                         BIO_puts(err, "cert_status: can't parse AIA URL\n");
797                         goto err;
798                         }
799                 if (srctx->verbose)
800                         BIO_printf(err, "cert_status: AIA URL: %s\n",
801                                         sk_OPENSSL_STRING_value(aia, 0));
802                 }
803         else
804                 {
805                 if (!srctx->host)
806                         {
807                         BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n");
808                         goto done;
809                         }
810                 host = srctx->host;
811                 path = srctx->path;
812                 port = srctx->port;
813                 use_ssl = srctx->use_ssl;
814                 }
815                 
816         if (!X509_STORE_CTX_init(&inctx,
817                                 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
818                                 NULL, NULL))
819                 goto err;
820         if (X509_STORE_get_by_subject(&inctx,X509_LU_X509,
821                                 X509_get_issuer_name(x),&obj) <= 0)
822                 {
823                 BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
824                 X509_STORE_CTX_cleanup(&inctx);
825                 goto done;
826                 }
827         req = OCSP_REQUEST_new();
828         if (!req)
829                 goto err;
830         id = OCSP_cert_to_id(NULL, x, obj.data.x509);
831         X509_free(obj.data.x509);
832         X509_STORE_CTX_cleanup(&inctx);
833         if (!id)
834                 goto err;
835         if (!OCSP_request_add0_id(req, id))
836                 goto err;
837         id = NULL;
838         /* Add any extensions to the request */
839         SSL_get_tlsext_status_exts(s, &exts);
840         for (i = 0; i < sk_X509_EXTENSION_num(exts); i++)
841                 {
842                 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
843                 if (!OCSP_REQUEST_add_ext(req, ext, -1))
844                         goto err;
845                 }
846         resp = process_responder(err, req, host, path, port, use_ssl, NULL,
847                                         srctx->timeout);
848         if (!resp)
849                 {
850                 BIO_puts(err, "cert_status: error querying responder\n");
851                 goto done;
852                 }
853         rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
854         if (rspderlen <= 0)
855                 goto err;
856         SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
857         if (srctx->verbose)
858                 {
859                 BIO_puts(err, "cert_status: ocsp response sent:\n");
860                 OCSP_RESPONSE_print(err, resp, 2);
861                 }
862         ret = SSL_TLSEXT_ERR_OK;
863         done:
864         if (ret != SSL_TLSEXT_ERR_OK)
865                 ERR_print_errors(err);
866         if (aia)
867                 {
868                 OPENSSL_free(host);
869                 OPENSSL_free(path);
870                 OPENSSL_free(port);
871                 X509_email_free(aia);
872                 }
873         if (id)
874                 OCSP_CERTID_free(id);
875         if (req)
876                 OCSP_REQUEST_free(req);
877         if (resp)
878                 OCSP_RESPONSE_free(resp);
879         return ret;
880         err:
881         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
882         goto done;
883         }
884
885 # ifndef OPENSSL_NO_NEXTPROTONEG
886 /* This is the context that we pass to next_proto_cb */
887 typedef struct tlsextnextprotoctx_st {
888         unsigned char *data;
889         unsigned int len;
890 } tlsextnextprotoctx;
891
892 static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg)
893         {
894         tlsextnextprotoctx *next_proto = arg;
895
896         *data = next_proto->data;
897         *len = next_proto->len;
898
899         return SSL_TLSEXT_ERR_OK;
900         }
901 # endif  /* ndef OPENSSL_NO_NEXTPROTONEG */
902
903
904 #endif
905
906 int MAIN(int, char **);
907
908 #ifndef OPENSSL_NO_JPAKE
909 static char *jpake_secret = NULL;
910 #endif
911 static char *srtp_profiles = NULL;
912
913 int MAIN(int argc, char *argv[])
914         {
915         X509_VERIFY_PARAM *vpm = NULL;
916         int badarg = 0;
917         short port=PORT;
918         char *CApath=NULL,*CAfile=NULL;
919         unsigned char *context = NULL;
920         char *dhfile = NULL;
921 #ifndef OPENSSL_NO_ECDH
922         char *named_curve = NULL;
923 #endif
924         int badop=0,bugs=0;
925         int ret=1;
926         int off=0;
927         int no_tmp_rsa=0,no_dhe=0,no_ecdhe=0,nocert=0;
928         int state=0;
929         const SSL_METHOD *meth=NULL;
930         int socket_type=SOCK_STREAM;
931         ENGINE *e=NULL;
932         char *inrand=NULL;
933         int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
934         char *passarg = NULL, *pass = NULL;
935         char *dpassarg = NULL, *dpass = NULL;
936         int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
937         X509 *s_cert = NULL, *s_dcert = NULL;
938         EVP_PKEY *s_key = NULL, *s_dkey = NULL;
939         int no_cache = 0;
940 #ifndef OPENSSL_NO_TLSEXT
941         EVP_PKEY *s_key2 = NULL;
942         X509 *s_cert2 = NULL;
943         tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING};
944 # ifndef OPENSSL_NO_NEXTPROTONEG
945         const char *next_proto_neg_in = NULL;
946         tlsextnextprotoctx next_proto;
947 # endif
948 #endif
949 #ifndef OPENSSL_NO_PSK
950         /* by default do not send a PSK identity hint */
951         static char *psk_identity_hint=NULL;
952 #endif
953 #ifndef OPENSSL_NO_SRP
954         char *srpuserseed = NULL;
955         char *srp_verifier_file = NULL;
956         srpsrvparm p;
957 #endif
958 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
959         meth=SSLv23_server_method();
960 #elif !defined(OPENSSL_NO_SSL3)
961         meth=SSLv3_server_method();
962 #elif !defined(OPENSSL_NO_SSL2)
963         meth=SSLv2_server_method();
964 #elif !defined(OPENSSL_NO_TLS1)
965         meth=TLSv1_server_method();
966 #else
967   /*  #error no SSL version enabled */
968 #endif
969
970         local_argc=argc;
971         local_argv=argv;
972
973         apps_startup();
974 #ifdef MONOLITH
975         s_server_init();
976 #endif
977
978         if (bio_err == NULL)
979                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
980
981         if (!load_config(bio_err, NULL))
982                 goto end;
983
984         verify_depth=0;
985 #ifdef FIONBIO
986         s_nbio=0;
987 #endif
988         s_nbio_test=0;
989
990         argc--;
991         argv++;
992
993         while (argc >= 1)
994                 {
995                 if      ((strcmp(*argv,"-port") == 0) ||
996                          (strcmp(*argv,"-accept") == 0))
997                         {
998                         if (--argc < 1) goto bad;
999                         if (!extract_port(*(++argv),&port))
1000                                 goto bad;
1001                         }
1002                 else if (strcmp(*argv,"-verify") == 0)
1003                         {
1004                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
1005                         if (--argc < 1) goto bad;
1006                         verify_depth=atoi(*(++argv));
1007                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
1008                         }
1009                 else if (strcmp(*argv,"-Verify") == 0)
1010                         {
1011                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
1012                                 SSL_VERIFY_CLIENT_ONCE;
1013                         if (--argc < 1) goto bad;
1014                         verify_depth=atoi(*(++argv));
1015                         BIO_printf(bio_err,"verify depth is %d, must return a certificate\n",verify_depth);
1016                         }
1017                 else if (strcmp(*argv,"-context") == 0)
1018                         {
1019                         if (--argc < 1) goto bad;
1020                         context= (unsigned char *)*(++argv);
1021                         }
1022                 else if (strcmp(*argv,"-cert") == 0)
1023                         {
1024                         if (--argc < 1) goto bad;
1025                         s_cert_file= *(++argv);
1026                         }
1027                 else if (strcmp(*argv,"-certform") == 0)
1028                         {
1029                         if (--argc < 1) goto bad;
1030                         s_cert_format = str2fmt(*(++argv));
1031                         }
1032                 else if (strcmp(*argv,"-key") == 0)
1033                         {
1034                         if (--argc < 1) goto bad;
1035                         s_key_file= *(++argv);
1036                         }
1037                 else if (strcmp(*argv,"-keyform") == 0)
1038                         {
1039                         if (--argc < 1) goto bad;
1040                         s_key_format = str2fmt(*(++argv));
1041                         }
1042                 else if (strcmp(*argv,"-pass") == 0)
1043                         {
1044                         if (--argc < 1) goto bad;
1045                         passarg = *(++argv);
1046                         }
1047                 else if (strcmp(*argv,"-dhparam") == 0)
1048                         {
1049                         if (--argc < 1) goto bad;
1050                         dhfile = *(++argv);
1051                         }
1052 #ifndef OPENSSL_NO_ECDH         
1053                 else if (strcmp(*argv,"-named_curve") == 0)
1054                         {
1055                         if (--argc < 1) goto bad;
1056                         named_curve = *(++argv);
1057                         }
1058 #endif
1059                 else if (strcmp(*argv,"-dcertform") == 0)
1060                         {
1061                         if (--argc < 1) goto bad;
1062                         s_dcert_format = str2fmt(*(++argv));
1063                         }
1064                 else if (strcmp(*argv,"-dcert") == 0)
1065                         {
1066                         if (--argc < 1) goto bad;
1067                         s_dcert_file= *(++argv);
1068                         }
1069                 else if (strcmp(*argv,"-dkeyform") == 0)
1070                         {
1071                         if (--argc < 1) goto bad;
1072                         s_dkey_format = str2fmt(*(++argv));
1073                         }
1074                 else if (strcmp(*argv,"-dpass") == 0)
1075                         {
1076                         if (--argc < 1) goto bad;
1077                         dpassarg = *(++argv);
1078                         }
1079                 else if (strcmp(*argv,"-dkey") == 0)
1080                         {
1081                         if (--argc < 1) goto bad;
1082                         s_dkey_file= *(++argv);
1083                         }
1084                 else if (strcmp(*argv,"-nocert") == 0)
1085                         {
1086                         nocert=1;
1087                         }
1088                 else if (strcmp(*argv,"-CApath") == 0)
1089                         {
1090                         if (--argc < 1) goto bad;
1091                         CApath= *(++argv);
1092                         }
1093                 else if (strcmp(*argv,"-no_cache") == 0)
1094                         no_cache = 1;
1095                 else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm))
1096                         {
1097                         if (badarg)
1098                                 goto bad;
1099                         continue;
1100                         }
1101                 else if (strcmp(*argv,"-verify_return_error") == 0)
1102                         verify_return_error = 1;
1103                 else if (strcmp(*argv,"-serverpref") == 0)
1104                         { off|=SSL_OP_CIPHER_SERVER_PREFERENCE; }
1105                 else if (strcmp(*argv,"-legacy_renegotiation") == 0)
1106                         off|=SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1107                 else if (strcmp(*argv,"-cipher") == 0)
1108                         {
1109                         if (--argc < 1) goto bad;
1110                         cipher= *(++argv);
1111                         }
1112                 else if (strcmp(*argv,"-CAfile") == 0)
1113                         {
1114                         if (--argc < 1) goto bad;
1115                         CAfile= *(++argv);
1116                         }
1117 #ifdef FIONBIO  
1118                 else if (strcmp(*argv,"-nbio") == 0)
1119                         { s_nbio=1; }
1120 #endif
1121                 else if (strcmp(*argv,"-nbio_test") == 0)
1122                         {
1123 #ifdef FIONBIO  
1124                         s_nbio=1;
1125 #endif
1126                         s_nbio_test=1;
1127                         }
1128                 else if (strcmp(*argv,"-debug") == 0)
1129                         { s_debug=1; }
1130 #ifndef OPENSSL_NO_TLSEXT
1131                 else if (strcmp(*argv,"-tlsextdebug") == 0)
1132                         s_tlsextdebug=1;
1133                 else if (strcmp(*argv,"-status") == 0)
1134                         s_tlsextstatus=1;
1135                 else if (strcmp(*argv,"-status_verbose") == 0)
1136                         {
1137                         s_tlsextstatus=1;
1138                         tlscstatp.verbose = 1;
1139                         }
1140                 else if (!strcmp(*argv, "-status_timeout"))
1141                         {
1142                         s_tlsextstatus=1;
1143                         if (--argc < 1) goto bad;
1144                         tlscstatp.timeout = atoi(*(++argv));
1145                         }
1146                 else if (!strcmp(*argv, "-status_url"))
1147                         {
1148                         s_tlsextstatus=1;
1149                         if (--argc < 1) goto bad;
1150                         if (!OCSP_parse_url(*(++argv),
1151                                         &tlscstatp.host,
1152                                         &tlscstatp.port,
1153                                         &tlscstatp.path,
1154                                         &tlscstatp.use_ssl))
1155                                 {
1156                                 BIO_printf(bio_err, "Error parsing URL\n");
1157                                 goto bad;
1158                                 }
1159                         }
1160 #endif
1161                 else if (strcmp(*argv,"-msg") == 0)
1162                         { s_msg=1; }
1163                 else if (strcmp(*argv,"-hack") == 0)
1164                         { hack=1; }
1165                 else if (strcmp(*argv,"-state") == 0)
1166                         { state=1; }
1167                 else if (strcmp(*argv,"-crlf") == 0)
1168                         { s_crlf=1; }
1169                 else if (strcmp(*argv,"-quiet") == 0)
1170                         { s_quiet=1; }
1171                 else if (strcmp(*argv,"-bugs") == 0)
1172                         { bugs=1; }
1173                 else if (strcmp(*argv,"-no_tmp_rsa") == 0)
1174                         { no_tmp_rsa=1; }
1175                 else if (strcmp(*argv,"-no_dhe") == 0)
1176                         { no_dhe=1; }
1177                 else if (strcmp(*argv,"-no_ecdhe") == 0)
1178                         { no_ecdhe=1; }
1179 #ifndef OPENSSL_NO_PSK
1180                 else if (strcmp(*argv,"-psk_hint") == 0)
1181                         {
1182                         if (--argc < 1) goto bad;
1183                         psk_identity_hint= *(++argv);
1184                         }
1185                 else if (strcmp(*argv,"-psk") == 0)
1186                         {
1187                         size_t i;
1188
1189                         if (--argc < 1) goto bad;
1190                         psk_key=*(++argv);
1191                         for (i=0; i<strlen(psk_key); i++)
1192                                 {
1193                                 if (isxdigit((int)psk_key[i]))
1194                                         continue;
1195                                 BIO_printf(bio_err,"Not a hex number '%s'\n",*argv);
1196                                 goto bad;
1197                                 }
1198                         }
1199 #endif
1200 #ifndef OPENSSL_NO_SRP
1201                 else if (strcmp(*argv, "-srpvfile") == 0)
1202                         {
1203                         if (--argc < 1) goto bad;
1204                         srp_verifier_file = *(++argv);
1205                         meth=TLSv1_server_method();
1206                         }
1207                 else if (strcmp(*argv, "-srpuserseed") == 0)
1208                         {
1209                         if (--argc < 1) goto bad;
1210                         srpuserseed = *(++argv);
1211                         meth=TLSv1_server_method();
1212                         }
1213 #endif
1214                 else if (strcmp(*argv,"-www") == 0)
1215                         { www=1; }
1216                 else if (strcmp(*argv,"-WWW") == 0)
1217                         { www=2; }
1218                 else if (strcmp(*argv,"-HTTP") == 0)
1219                         { www=3; }
1220                 else if (strcmp(*argv,"-no_ssl2") == 0)
1221                         { off|=SSL_OP_NO_SSLv2; }
1222                 else if (strcmp(*argv,"-no_ssl3") == 0)
1223                         { off|=SSL_OP_NO_SSLv3; }
1224                 else if (strcmp(*argv,"-no_tls1") == 0)
1225                         { off|=SSL_OP_NO_TLSv1; }
1226                 else if (strcmp(*argv,"-no_tls1_1") == 0)
1227                         { off|=SSL_OP_NO_TLSv1_1; }
1228                 else if (strcmp(*argv,"-no_tls1_2") == 0)
1229                         { off|=SSL_OP_NO_TLSv1_2; }
1230                 else if (strcmp(*argv,"-no_comp") == 0)
1231                         { off|=SSL_OP_NO_COMPRESSION; }
1232 #ifndef OPENSSL_NO_TLSEXT
1233                 else if (strcmp(*argv,"-no_ticket") == 0)
1234                         { off|=SSL_OP_NO_TICKET; }
1235 #endif
1236 #ifndef OPENSSL_NO_SSL2
1237                 else if (strcmp(*argv,"-ssl2") == 0)
1238                         { meth=SSLv2_server_method(); }
1239 #endif
1240 #ifndef OPENSSL_NO_SSL3
1241                 else if (strcmp(*argv,"-ssl3") == 0)
1242                         { meth=SSLv3_server_method(); }
1243 #endif
1244 #ifndef OPENSSL_NO_TLS1
1245                 else if (strcmp(*argv,"-tls1") == 0)
1246                         { meth=TLSv1_server_method(); }
1247                 else if (strcmp(*argv,"-tls1_1") == 0)
1248                         { meth=TLSv1_1_server_method(); }
1249                 else if (strcmp(*argv,"-tls1_2") == 0)
1250                         { meth=TLSv1_2_server_method(); }
1251 #endif
1252 #ifndef OPENSSL_NO_DTLS1
1253                 else if (strcmp(*argv,"-dtls1") == 0)
1254                         { 
1255                         meth=DTLSv1_server_method();
1256                         socket_type = SOCK_DGRAM;
1257                         }
1258                 else if (strcmp(*argv,"-timeout") == 0)
1259                         enable_timeouts = 1;
1260                 else if (strcmp(*argv,"-mtu") == 0)
1261                         {
1262                         if (--argc < 1) goto bad;
1263                         socket_mtu = atol(*(++argv));
1264                         }
1265                 else if (strcmp(*argv, "-chain") == 0)
1266                         cert_chain = 1;
1267 #endif
1268                 else if (strcmp(*argv, "-id_prefix") == 0)
1269                         {
1270                         if (--argc < 1) goto bad;
1271                         session_id_prefix = *(++argv);
1272                         }
1273 #ifndef OPENSSL_NO_ENGINE
1274                 else if (strcmp(*argv,"-engine") == 0)
1275                         {
1276                         if (--argc < 1) goto bad;
1277                         engine_id= *(++argv);
1278                         }
1279 #endif
1280                 else if (strcmp(*argv,"-rand") == 0)
1281                         {
1282                         if (--argc < 1) goto bad;
1283                         inrand= *(++argv);
1284                         }
1285 #ifndef OPENSSL_NO_TLSEXT
1286                 else if (strcmp(*argv,"-servername") == 0)
1287                         {
1288                         if (--argc < 1) goto bad;
1289                         tlsextcbp.servername= *(++argv);
1290                         }
1291                 else if (strcmp(*argv,"-servername_fatal") == 0)
1292                         { tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; }
1293                 else if (strcmp(*argv,"-cert2") == 0)
1294                         {
1295                         if (--argc < 1) goto bad;
1296                         s_cert_file2= *(++argv);
1297                         }
1298                 else if (strcmp(*argv,"-key2") == 0)
1299                         {
1300                         if (--argc < 1) goto bad;
1301                         s_key_file2= *(++argv);
1302                         }
1303 # ifndef OPENSSL_NO_NEXTPROTONEG
1304                 else if (strcmp(*argv,"-nextprotoneg") == 0)
1305                         {
1306                         if (--argc < 1) goto bad;
1307                         next_proto_neg_in = *(++argv);
1308                         }
1309 # endif
1310 #endif
1311 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1312                 else if (strcmp(*argv,"-jpake") == 0)
1313                         {
1314                         if (--argc < 1) goto bad;
1315                         jpake_secret = *(++argv);
1316                         }
1317 #endif
1318                 else if (strcmp(*argv,"-use_srtp") == 0)
1319                         {
1320                         if (--argc < 1) goto bad;
1321                         srtp_profiles = *(++argv);
1322                         }
1323                 else if (strcmp(*argv,"-keymatexport") == 0)
1324                         {
1325                         if (--argc < 1) goto bad;
1326                         keymatexportlabel= *(++argv);
1327                         }
1328                 else if (strcmp(*argv,"-keymatexportlen") == 0)
1329                         {
1330                         if (--argc < 1) goto bad;
1331                         keymatexportlen=atoi(*(++argv));
1332                         if (keymatexportlen == 0) goto bad;
1333                         }
1334                 else
1335                         {
1336                         BIO_printf(bio_err,"unknown option %s\n",*argv);
1337                         badop=1;
1338                         break;
1339                         }
1340                 argc--;
1341                 argv++;
1342                 }
1343         if (badop)
1344                 {
1345 bad:
1346                 sv_usage();
1347                 goto end;
1348                 }
1349
1350 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1351         if (jpake_secret)
1352                 {
1353                 if (psk_key)
1354                         {
1355                         BIO_printf(bio_err,
1356                                    "Can't use JPAKE and PSK together\n");
1357                         goto end;
1358                         }
1359                 psk_identity = "JPAKE";
1360                 if (cipher)
1361                         {
1362                         BIO_printf(bio_err, "JPAKE sets cipher to PSK\n");
1363                         goto end;
1364                         }
1365                 cipher = "PSK";
1366                 }
1367
1368 #endif
1369
1370         SSL_load_error_strings();
1371         OpenSSL_add_ssl_algorithms();
1372
1373 #ifndef OPENSSL_NO_ENGINE
1374         e = setup_engine(bio_err, engine_id, 1);
1375 #endif
1376
1377         if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass))
1378                 {
1379                 BIO_printf(bio_err, "Error getting password\n");
1380                 goto end;
1381                 }
1382
1383
1384         if (s_key_file == NULL)
1385                 s_key_file = s_cert_file;
1386 #ifndef OPENSSL_NO_TLSEXT
1387         if (s_key_file2 == NULL)
1388                 s_key_file2 = s_cert_file2;
1389 #endif
1390
1391         if (nocert == 0)
1392                 {
1393                 s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e,
1394                        "server certificate private key file");
1395                 if (!s_key)
1396                         {
1397                         ERR_print_errors(bio_err);
1398                         goto end;
1399                         }
1400
1401                 s_cert = load_cert(bio_err,s_cert_file,s_cert_format,
1402                         NULL, e, "server certificate file");
1403
1404                 if (!s_cert)
1405                         {
1406                         ERR_print_errors(bio_err);
1407                         goto end;
1408                         }
1409
1410 #ifndef OPENSSL_NO_TLSEXT
1411                 if (tlsextcbp.servername) 
1412                         {
1413                         s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e,
1414                                 "second server certificate private key file");
1415                         if (!s_key2)
1416                                 {
1417                                 ERR_print_errors(bio_err);
1418                                 goto end;
1419                                 }
1420                         
1421                         s_cert2 = load_cert(bio_err,s_cert_file2,s_cert_format,
1422                                 NULL, e, "second server certificate file");
1423                         
1424                         if (!s_cert2)
1425                                 {
1426                                 ERR_print_errors(bio_err);
1427                                 goto end;
1428                                 }
1429                         }
1430
1431 # ifndef OPENSSL_NO_NEXTPROTONEG
1432                 if (next_proto_neg_in)
1433                         {
1434                         unsigned short len;
1435                         next_proto.data = next_protos_parse(&len,
1436                                 next_proto_neg_in);
1437                         if (next_proto.data == NULL)
1438                                 goto end;
1439                         next_proto.len = len;
1440                         }
1441                 else
1442                         {
1443                         next_proto.data = NULL;
1444                         }
1445 # endif
1446 #endif
1447                 }
1448
1449
1450         if (s_dcert_file)
1451                 {
1452
1453                 if (s_dkey_file == NULL)
1454                         s_dkey_file = s_dcert_file;
1455
1456                 s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
1457                                 0, dpass, e,
1458                                "second certificate private key file");
1459                 if (!s_dkey)
1460                         {
1461                         ERR_print_errors(bio_err);
1462                         goto end;
1463                         }
1464
1465                 s_dcert = load_cert(bio_err,s_dcert_file,s_dcert_format,
1466                                 NULL, e, "second server certificate file");
1467
1468                 if (!s_dcert)
1469                         {
1470                         ERR_print_errors(bio_err);
1471                         goto end;
1472                         }
1473
1474                 }
1475
1476         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
1477                 && !RAND_status())
1478                 {
1479                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
1480                 }
1481         if (inrand != NULL)
1482                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
1483                         app_RAND_load_files(inrand));
1484
1485         if (bio_s_out == NULL)
1486                 {
1487                 if (s_quiet && !s_debug && !s_msg)
1488                         {
1489                         bio_s_out=BIO_new(BIO_s_null());
1490                         }
1491                 else
1492                         {
1493                         if (bio_s_out == NULL)
1494                                 bio_s_out=BIO_new_fp(stdout,BIO_NOCLOSE);
1495                         }
1496                 }
1497
1498 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1499         if (nocert)
1500 #endif
1501                 {
1502                 s_cert_file=NULL;
1503                 s_key_file=NULL;
1504                 s_dcert_file=NULL;
1505                 s_dkey_file=NULL;
1506 #ifndef OPENSSL_NO_TLSEXT
1507                 s_cert_file2=NULL;
1508                 s_key_file2=NULL;
1509 #endif
1510                 }
1511
1512         ctx=SSL_CTX_new(meth);
1513         if (ctx == NULL)
1514                 {
1515                 ERR_print_errors(bio_err);
1516                 goto end;
1517                 }
1518         if (session_id_prefix)
1519                 {
1520                 if(strlen(session_id_prefix) >= 32)
1521                         BIO_printf(bio_err,
1522 "warning: id_prefix is too long, only one new session will be possible\n");
1523                 else if(strlen(session_id_prefix) >= 16)
1524                         BIO_printf(bio_err,
1525 "warning: id_prefix is too long if you use SSLv2\n");
1526                 if(!SSL_CTX_set_generate_session_id(ctx, generate_session_id))
1527                         {
1528                         BIO_printf(bio_err,"error setting 'id_prefix'\n");
1529                         ERR_print_errors(bio_err);
1530                         goto end;
1531                         }
1532                 BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1533                 }
1534         SSL_CTX_set_quiet_shutdown(ctx,1);
1535         if (bugs) SSL_CTX_set_options(ctx,SSL_OP_ALL);
1536         if (hack) SSL_CTX_set_options(ctx,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1537         SSL_CTX_set_options(ctx,off);
1538         /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1539          * Setting read ahead solves this problem.
1540          */
1541         if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);
1542
1543         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
1544         if (no_cache)
1545                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1546         else
1547                 SSL_CTX_sess_set_cache_size(ctx,128);
1548
1549         if (srtp_profiles != NULL)
1550                 SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
1551
1552 #if 0
1553         if (cipher == NULL) cipher=getenv("SSL_CIPHER");
1554 #endif
1555
1556 #if 0
1557         if (s_cert_file == NULL)
1558                 {
1559                 BIO_printf(bio_err,"You must specify a certificate file for the server to use\n");
1560                 goto end;
1561                 }
1562 #endif
1563
1564         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
1565                 (!SSL_CTX_set_default_verify_paths(ctx)))
1566                 {
1567                 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
1568                 ERR_print_errors(bio_err);
1569                 /* goto end; */
1570                 }
1571         if (vpm)
1572                 SSL_CTX_set1_param(ctx, vpm);
1573
1574 #ifndef OPENSSL_NO_TLSEXT
1575         if (s_cert2)
1576                 {
1577                 ctx2=SSL_CTX_new(meth);
1578                 if (ctx2 == NULL)
1579                         {
1580                         ERR_print_errors(bio_err);
1581                         goto end;
1582                         }
1583                 }
1584         
1585         if (ctx2)
1586                 {
1587                 BIO_printf(bio_s_out,"Setting secondary ctx parameters\n");
1588
1589                 if (session_id_prefix)
1590                         {
1591                         if(strlen(session_id_prefix) >= 32)
1592                                 BIO_printf(bio_err,
1593                                         "warning: id_prefix is too long, only one new session will be possible\n");
1594                         else if(strlen(session_id_prefix) >= 16)
1595                                 BIO_printf(bio_err,
1596                                         "warning: id_prefix is too long if you use SSLv2\n");
1597                         if(!SSL_CTX_set_generate_session_id(ctx2, generate_session_id))
1598                                 {
1599                                 BIO_printf(bio_err,"error setting 'id_prefix'\n");
1600                                 ERR_print_errors(bio_err);
1601                                 goto end;
1602                                 }
1603                         BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1604                         }
1605                 SSL_CTX_set_quiet_shutdown(ctx2,1);
1606                 if (bugs) SSL_CTX_set_options(ctx2,SSL_OP_ALL);
1607                 if (hack) SSL_CTX_set_options(ctx2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1608                 SSL_CTX_set_options(ctx2,off);
1609                 /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1610                  * Setting read ahead solves this problem.
1611                  */
1612                 if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx2, 1);
1613
1614                 if (state) SSL_CTX_set_info_callback(ctx2,apps_ssl_info_callback);
1615
1616                 if (no_cache)
1617                         SSL_CTX_set_session_cache_mode(ctx2,SSL_SESS_CACHE_OFF);
1618                 else
1619                         SSL_CTX_sess_set_cache_size(ctx2,128);
1620
1621                 if ((!SSL_CTX_load_verify_locations(ctx2,CAfile,CApath)) ||
1622                         (!SSL_CTX_set_default_verify_paths(ctx2)))
1623                         {
1624                         ERR_print_errors(bio_err);
1625                         }
1626                 if (vpm)
1627                         SSL_CTX_set1_param(ctx2, vpm);
1628                 }
1629
1630 # ifndef OPENSSL_NO_NEXTPROTONEG
1631         if (next_proto.data)
1632                 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto);
1633 # endif
1634 #endif 
1635
1636 #ifndef OPENSSL_NO_DH
1637         if (!no_dhe)
1638                 {
1639                 DH *dh=NULL;
1640
1641                 if (dhfile)
1642                         dh = load_dh_param(dhfile);
1643                 else if (s_cert_file)
1644                         dh = load_dh_param(s_cert_file);
1645
1646                 if (dh != NULL)
1647                         {
1648                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1649                         }
1650                 else
1651                         {
1652                         BIO_printf(bio_s_out,"Using default temp DH parameters\n");
1653                         dh=get_dh512();
1654                         }
1655                 (void)BIO_flush(bio_s_out);
1656
1657                 SSL_CTX_set_tmp_dh(ctx,dh);
1658 #ifndef OPENSSL_NO_TLSEXT
1659                 if (ctx2)
1660                         {
1661                         if (!dhfile)
1662                                 { 
1663                                 DH *dh2=load_dh_param(s_cert_file2);
1664                                 if (dh2 != NULL)
1665                                         {
1666                                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1667                                         (void)BIO_flush(bio_s_out);
1668
1669                                         DH_free(dh);
1670                                         dh = dh2;
1671                                         }
1672                                 }
1673                         SSL_CTX_set_tmp_dh(ctx2,dh);
1674                         }
1675 #endif
1676                 DH_free(dh);
1677                 }
1678 #endif
1679
1680 #ifndef OPENSSL_NO_ECDH
1681         if (!no_ecdhe)
1682                 {
1683                 EC_KEY *ecdh=NULL;
1684
1685                 if (named_curve)
1686                         {
1687                         int nid = OBJ_sn2nid(named_curve);
1688
1689                         if (nid == 0)
1690                                 {
1691                                 BIO_printf(bio_err, "unknown curve name (%s)\n", 
1692                                         named_curve);
1693                                 goto end;
1694                                 }
1695                         ecdh = EC_KEY_new_by_curve_name(nid);
1696                         if (ecdh == NULL)
1697                                 {
1698                                 BIO_printf(bio_err, "unable to create curve (%s)\n", 
1699                                         named_curve);
1700                                 goto end;
1701                                 }
1702                         }
1703
1704                 if (ecdh != NULL)
1705                         {
1706                         BIO_printf(bio_s_out,"Setting temp ECDH parameters\n");
1707                         }
1708                 else
1709                         {
1710                         BIO_printf(bio_s_out,"Using default temp ECDH parameters\n");
1711                         ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1712                         if (ecdh == NULL) 
1713                                 {
1714                                 BIO_printf(bio_err, "unable to create curve (nistp256)\n");
1715                                 goto end;
1716                                 }
1717                         }
1718                 (void)BIO_flush(bio_s_out);
1719
1720                 SSL_CTX_set_tmp_ecdh(ctx,ecdh);
1721 #ifndef OPENSSL_NO_TLSEXT
1722                 if (ctx2) 
1723                         SSL_CTX_set_tmp_ecdh(ctx2,ecdh);
1724 #endif
1725                 EC_KEY_free(ecdh);
1726                 }
1727 #endif
1728         
1729         if (!set_cert_key_stuff(ctx,s_cert,s_key))
1730                 goto end;
1731 #ifndef OPENSSL_NO_TLSEXT
1732         if (ctx2 && !set_cert_key_stuff(ctx2,s_cert2,s_key2))
1733                 goto end; 
1734 #endif
1735         if (s_dcert != NULL)
1736                 {
1737                 if (!set_cert_key_stuff(ctx,s_dcert,s_dkey))
1738                         goto end;
1739                 }
1740
1741 #ifndef OPENSSL_NO_RSA
1742 #if 1
1743         if (!no_tmp_rsa)
1744                 {
1745                 SSL_CTX_set_tmp_rsa_callback(ctx,tmp_rsa_cb);
1746 #ifndef OPENSSL_NO_TLSEXT
1747                 if (ctx2) 
1748                         SSL_CTX_set_tmp_rsa_callback(ctx2,tmp_rsa_cb);
1749 #endif          
1750                 }
1751 #else
1752         if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx))
1753                 {
1754                 RSA *rsa;
1755
1756                 BIO_printf(bio_s_out,"Generating temp (512 bit) RSA key...");
1757                 BIO_flush(bio_s_out);
1758
1759                 rsa=RSA_generate_key(512,RSA_F4,NULL);
1760
1761                 if (!SSL_CTX_set_tmp_rsa(ctx,rsa))
1762                         {
1763                         ERR_print_errors(bio_err);
1764                         goto end;
1765                         }
1766 #ifndef OPENSSL_NO_TLSEXT
1767                         if (ctx2)
1768                                 {
1769                                 if (!SSL_CTX_set_tmp_rsa(ctx2,rsa))
1770                                         {
1771                                         ERR_print_errors(bio_err);
1772                                         goto end;
1773                                         }
1774                                 }
1775 #endif
1776                 RSA_free(rsa);
1777                 BIO_printf(bio_s_out,"\n");
1778                 }
1779 #endif
1780 #endif
1781
1782 #ifndef OPENSSL_NO_PSK
1783 #ifdef OPENSSL_NO_JPAKE
1784         if (psk_key != NULL)
1785 #else
1786         if (psk_key != NULL || jpake_secret)
1787 #endif
1788                 {
1789                 if (s_debug)
1790                         BIO_printf(bio_s_out, "PSK key given or JPAKE in use, setting server callback\n");
1791                 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
1792                 }
1793
1794         if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint))
1795                 {
1796                 BIO_printf(bio_err,"error setting PSK identity hint to context\n");
1797                 ERR_print_errors(bio_err);
1798                 goto end;
1799                 }
1800 #endif
1801
1802         if (cipher != NULL)
1803                 {
1804                 if(!SSL_CTX_set_cipher_list(ctx,cipher))
1805                         {
1806                         BIO_printf(bio_err,"error setting cipher list\n");
1807                         ERR_print_errors(bio_err);
1808                         goto end;
1809                         }
1810 #ifndef OPENSSL_NO_TLSEXT
1811                 if (ctx2 && !SSL_CTX_set_cipher_list(ctx2,cipher))
1812                         {
1813                         BIO_printf(bio_err,"error setting cipher list\n");
1814                         ERR_print_errors(bio_err);
1815                         goto end;
1816                         }
1817 #endif
1818                 }
1819         SSL_CTX_set_verify(ctx,s_server_verify,verify_callback);
1820         SSL_CTX_set_session_id_context(ctx,(void*)&s_server_session_id_context,
1821                 sizeof s_server_session_id_context);
1822
1823         /* Set DTLS cookie generation and verification callbacks */
1824         SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1825         SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1826
1827 #ifndef OPENSSL_NO_TLSEXT
1828         if (ctx2)
1829                 {
1830                 SSL_CTX_set_verify(ctx2,s_server_verify,verify_callback);
1831                 SSL_CTX_set_session_id_context(ctx2,(void*)&s_server_session_id_context,
1832                         sizeof s_server_session_id_context);
1833
1834                 tlsextcbp.biodebug = bio_s_out;
1835                 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1836                 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1837                 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1838                 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1839                 }
1840 #endif
1841
1842 #ifndef OPENSSL_NO_SRP
1843         if (srp_verifier_file != NULL)
1844                 {
1845                 p.vb = SRP_VBASE_new(srpuserseed);
1846                 if ((ret = SRP_VBASE_init(p.vb, srp_verifier_file)) != SRP_NO_ERROR)
1847                         {
1848                         BIO_printf(bio_err,
1849                                    "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
1850                                    srp_verifier_file, ret);
1851                                 goto end;
1852                         }
1853                 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE,verify_callback);
1854                 SSL_CTX_set_srp_cb_arg(ctx, &p);                        
1855                 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
1856                 }
1857         else
1858 #endif
1859         if (CAfile != NULL)
1860                 {
1861                 SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));
1862 #ifndef OPENSSL_NO_TLSEXT
1863                 if (ctx2) 
1864                         SSL_CTX_set_client_CA_list(ctx2,SSL_load_client_CA_file(CAfile));
1865 #endif
1866                 }
1867
1868         BIO_printf(bio_s_out,"ACCEPT\n");
1869         (void)BIO_flush(bio_s_out);
1870         if (www)
1871                 do_server(port,socket_type,&accept_socket,www_body, context);
1872         else
1873                 do_server(port,socket_type,&accept_socket,sv_body, context);
1874         print_stats(bio_s_out,ctx);
1875         ret=0;
1876 end:
1877         if (ctx != NULL) SSL_CTX_free(ctx);
1878         if (s_cert)
1879                 X509_free(s_cert);
1880         if (s_dcert)
1881                 X509_free(s_dcert);
1882         if (s_key)
1883                 EVP_PKEY_free(s_key);
1884         if (s_dkey)
1885                 EVP_PKEY_free(s_dkey);
1886         if (pass)
1887                 OPENSSL_free(pass);
1888         if (dpass)
1889                 OPENSSL_free(dpass);
1890 #ifndef OPENSSL_NO_TLSEXT
1891         if (ctx2 != NULL) SSL_CTX_free(ctx2);
1892         if (s_cert2)
1893                 X509_free(s_cert2);
1894         if (s_key2)
1895                 EVP_PKEY_free(s_key2);
1896 #endif
1897         if (bio_s_out != NULL)
1898                 {
1899         BIO_free(bio_s_out);
1900                 bio_s_out=NULL;
1901                 }
1902         apps_shutdown();
1903         OPENSSL_EXIT(ret);
1904         }
1905
1906 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
1907         {
1908         BIO_printf(bio,"%4ld items in the session cache\n",
1909                 SSL_CTX_sess_number(ssl_ctx));
1910         BIO_printf(bio,"%4ld client connects (SSL_connect())\n",
1911                 SSL_CTX_sess_connect(ssl_ctx));
1912         BIO_printf(bio,"%4ld client renegotiates (SSL_connect())\n",
1913                 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1914         BIO_printf(bio,"%4ld client connects that finished\n",
1915                 SSL_CTX_sess_connect_good(ssl_ctx));
1916         BIO_printf(bio,"%4ld server accepts (SSL_accept())\n",
1917                 SSL_CTX_sess_accept(ssl_ctx));
1918         BIO_printf(bio,"%4ld server renegotiates (SSL_accept())\n",
1919                 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1920         BIO_printf(bio,"%4ld server accepts that finished\n",
1921                 SSL_CTX_sess_accept_good(ssl_ctx));
1922         BIO_printf(bio,"%4ld session cache hits\n",SSL_CTX_sess_hits(ssl_ctx));
1923         BIO_printf(bio,"%4ld session cache misses\n",SSL_CTX_sess_misses(ssl_ctx));
1924         BIO_printf(bio,"%4ld session cache timeouts\n",SSL_CTX_sess_timeouts(ssl_ctx));
1925         BIO_printf(bio,"%4ld callback cache hits\n",SSL_CTX_sess_cb_hits(ssl_ctx));
1926         BIO_printf(bio,"%4ld cache full overflows (%ld allowed)\n",
1927                 SSL_CTX_sess_cache_full(ssl_ctx),
1928                 SSL_CTX_sess_get_cache_size(ssl_ctx));
1929         }
1930
1931 static int sv_body(char *hostname, int s, unsigned char *context)
1932         {
1933         char *buf=NULL;
1934         fd_set readfds;
1935         int ret=1,width;
1936         int k,i;
1937         unsigned long l;
1938         SSL *con=NULL;
1939         BIO *sbio;
1940 #ifndef OPENSSL_NO_KRB5
1941         KSSL_CTX *kctx;
1942 #endif
1943         struct timeval timeout;
1944 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
1945         struct timeval tv;
1946 #else
1947         struct timeval *timeoutp;
1948 #endif
1949
1950         if ((buf=OPENSSL_malloc(bufsize)) == NULL)
1951                 {
1952                 BIO_printf(bio_err,"out of memory\n");
1953                 goto err;
1954                 }
1955 #ifdef FIONBIO  
1956         if (s_nbio)
1957                 {
1958                 unsigned long sl=1;
1959
1960                 if (!s_quiet)
1961                         BIO_printf(bio_err,"turning on non blocking io\n");
1962                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1963                         ERR_print_errors(bio_err);
1964                 }
1965 #endif
1966
1967         if (con == NULL) {
1968                 con=SSL_new(ctx);
1969 #ifndef OPENSSL_NO_TLSEXT
1970         if (s_tlsextdebug)
1971                 {
1972                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1973                 SSL_set_tlsext_debug_arg(con, bio_s_out);
1974                 }
1975         if (s_tlsextstatus)
1976                 {
1977                 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1978                 tlscstatp.err = bio_err;
1979                 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1980                 }
1981 #endif
1982 #ifndef OPENSSL_NO_KRB5
1983                 if ((kctx = kssl_ctx_new()) != NULL)
1984                         {
1985                         SSL_set0_kssl_ctx(con, kctx);
1986                         kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
1987                         kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
1988                         }
1989 #endif  /* OPENSSL_NO_KRB5 */
1990                 if(context)
1991                       SSL_set_session_id_context(con, context,
1992                                                  strlen((char *)context));
1993         }
1994         SSL_clear(con);
1995 #if 0
1996 #ifdef TLSEXT_TYPE_opaque_prf_input
1997         SSL_set_tlsext_opaque_prf_input(con, "Test server", 11);
1998 #endif
1999 #endif
2000
2001         if (SSL_version(con) == DTLS1_VERSION)
2002                 {
2003
2004                 sbio=BIO_new_dgram(s,BIO_NOCLOSE);
2005
2006                 if (enable_timeouts)
2007                         {
2008                         timeout.tv_sec = 0;
2009                         timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2010                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2011                         
2012                         timeout.tv_sec = 0;
2013                         timeout.tv_usec = DGRAM_SND_TIMEOUT;
2014                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2015                         }
2016
2017                 if (socket_mtu > 28)
2018                         {
2019                         SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2020                         SSL_set_mtu(con, socket_mtu - 28);
2021                         }
2022                 else
2023                         /* want to do MTU discovery */
2024                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2025
2026         /* turn on cookie exchange */
2027         SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2028                 }
2029         else
2030                 sbio=BIO_new_socket(s,BIO_NOCLOSE);
2031
2032         if (s_nbio_test)
2033                 {
2034                 BIO *test;
2035
2036                 test=BIO_new(BIO_f_nbio_test());
2037                 sbio=BIO_push(test,sbio);
2038                 }
2039 #ifndef OPENSSL_NO_JPAKE
2040         if(jpake_secret)
2041                 jpake_server_auth(bio_s_out, sbio, jpake_secret);
2042 #endif
2043
2044         SSL_set_bio(con,sbio,sbio);
2045         SSL_set_accept_state(con);
2046         /* SSL_set_fd(con,s); */
2047
2048         if (s_debug)
2049                 {
2050                 SSL_set_debug(con, 1);
2051                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2052                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2053                 }
2054         if (s_msg)
2055                 {
2056                 SSL_set_msg_callback(con, msg_cb);
2057                 SSL_set_msg_callback_arg(con, bio_s_out);
2058                 }
2059 #ifndef OPENSSL_NO_TLSEXT
2060         if (s_tlsextdebug)
2061                 {
2062                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2063                 SSL_set_tlsext_debug_arg(con, bio_s_out);
2064                 }
2065 #endif
2066
2067         width=s+1;
2068         for (;;)
2069                 {
2070                 int read_from_terminal;
2071                 int read_from_sslcon;
2072
2073                 read_from_terminal = 0;
2074                 read_from_sslcon = SSL_pending(con);
2075
2076                 if (!read_from_sslcon)
2077                         {
2078                         FD_ZERO(&readfds);
2079 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined(OPENSSL_SYS_BEOS_R5)
2080                         openssl_fdset(fileno(stdin),&readfds);
2081 #endif
2082                         openssl_fdset(s,&readfds);
2083                         /* Note: under VMS with SOCKETSHR the second parameter is
2084                          * currently of type (int *) whereas under other systems
2085                          * it is (void *) if you don't have a cast it will choke
2086                          * the compiler: if you do have a cast then you can either
2087                          * go for (int *) or (void *).
2088                          */
2089 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
2090                         /* Under DOS (non-djgpp) and Windows we can't select on stdin: only
2091                          * on sockets. As a workaround we timeout the select every
2092                          * second and check for any keypress. In a proper Windows
2093                          * application we wouldn't do this because it is inefficient.
2094                          */
2095                         tv.tv_sec = 1;
2096                         tv.tv_usec = 0;
2097                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2098                         if((i < 0) || (!i && !_kbhit() ) )continue;
2099                         if(_kbhit())
2100                                 read_from_terminal = 1;
2101 #elif defined(OPENSSL_SYS_BEOS_R5)
2102                         /* Under BeOS-R5 the situation is similar to DOS */
2103                         tv.tv_sec = 1;
2104                         tv.tv_usec = 0;
2105                         (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
2106                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2107                         if ((i < 0) || (!i && read(fileno(stdin), buf, 0) < 0))
2108                                 continue;
2109                         if (read(fileno(stdin), buf, 0) >= 0)
2110                                 read_from_terminal = 1;
2111                         (void)fcntl(fileno(stdin), F_SETFL, 0);
2112 #else
2113                         if ((SSL_version(con) == DTLS1_VERSION) &&
2114                                 DTLSv1_get_timeout(con, &timeout))
2115                                 timeoutp = &timeout;
2116                         else
2117                                 timeoutp = NULL;
2118
2119                         i=select(width,(void *)&readfds,NULL,NULL,timeoutp);
2120
2121                         if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0)
2122                                 {
2123                                 BIO_printf(bio_err,"TIMEOUT occured\n");
2124                                 }
2125
2126                         if (i <= 0) continue;
2127                         if (FD_ISSET(fileno(stdin),&readfds))
2128                                 read_from_terminal = 1;
2129 #endif
2130                         if (FD_ISSET(s,&readfds))
2131                                 read_from_sslcon = 1;
2132                         }
2133                 if (read_from_terminal)
2134                         {
2135                         if (s_crlf)
2136                                 {
2137                                 int j, lf_num;
2138
2139                                 i=raw_read_stdin(buf, bufsize/2);
2140                                 lf_num = 0;
2141                                 /* both loops are skipped when i <= 0 */
2142                                 for (j = 0; j < i; j++)
2143                                         if (buf[j] == '\n')
2144                                                 lf_num++;
2145                                 for (j = i-1; j >= 0; j--)
2146                                         {
2147                                         buf[j+lf_num] = buf[j];
2148                                         if (buf[j] == '\n')
2149                                                 {
2150                                                 lf_num--;
2151                                                 i++;
2152                                                 buf[j+lf_num] = '\r';
2153                                                 }
2154                                         }
2155                                 assert(lf_num == 0);
2156                                 }
2157                         else
2158                                 i=raw_read_stdin(buf,bufsize);
2159                         if (!s_quiet)
2160                                 {
2161                                 if ((i <= 0) || (buf[0] == 'Q'))
2162                                         {
2163                                         BIO_printf(bio_s_out,"DONE\n");
2164                                         SHUTDOWN(s);
2165                                         close_accept_socket();
2166                                         ret= -11;
2167                                         goto err;
2168                                         }
2169                                 if ((i <= 0) || (buf[0] == 'q'))
2170                                         {
2171                                         BIO_printf(bio_s_out,"DONE\n");
2172                                         if (SSL_version(con) != DTLS1_VERSION)
2173                         SHUTDOWN(s);
2174         /*                              close_accept_socket();
2175                                         ret= -11;*/
2176                                         goto err;
2177                                         }
2178
2179                                 if ((buf[0] == 'r') && 
2180                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2181                                         {
2182                                         SSL_renegotiate(con);
2183                                         i=SSL_do_handshake(con);
2184                                         printf("SSL_do_handshake -> %d\n",i);
2185                                         i=0; /*13; */
2186                                         continue;
2187                                         /* strcpy(buf,"server side RE-NEGOTIATE\n"); */
2188                                         }
2189                                 if ((buf[0] == 'R') &&
2190                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2191                                         {
2192                                         SSL_set_verify(con,
2193                                                 SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,NULL);
2194                                         SSL_renegotiate(con);
2195                                         i=SSL_do_handshake(con);
2196                                         printf("SSL_do_handshake -> %d\n",i);
2197                                         i=0; /* 13; */
2198                                         continue;
2199                                         /* strcpy(buf,"server side RE-NEGOTIATE asking for client cert\n"); */
2200                                         }
2201                                 if (buf[0] == 'P')
2202                                         {
2203                                         static const char *str="Lets print some clear text\n";
2204                                         BIO_write(SSL_get_wbio(con),str,strlen(str));
2205                                         }
2206                                 if (buf[0] == 'S')
2207                                         {
2208                                         print_stats(bio_s_out,SSL_get_SSL_CTX(con));
2209                                         }
2210                                 }
2211 #ifdef CHARSET_EBCDIC
2212                         ebcdic2ascii(buf,buf,i);
2213 #endif
2214                         l=k=0;
2215                         for (;;)
2216                                 {
2217                                 /* should do a select for the write */
2218 #ifdef RENEG
2219 { static count=0; if (++count == 100) { count=0; SSL_renegotiate(con); } }
2220 #endif
2221                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
2222                                 switch (SSL_get_error(con,k))
2223                                         {
2224                                 case SSL_ERROR_NONE:
2225                                         break;
2226                                 case SSL_ERROR_WANT_WRITE:
2227                                 case SSL_ERROR_WANT_READ:
2228                                 case SSL_ERROR_WANT_X509_LOOKUP:
2229                                         BIO_printf(bio_s_out,"Write BLOCK\n");
2230                                         break;
2231                                 case SSL_ERROR_SYSCALL:
2232                                 case SSL_ERROR_SSL:
2233                                         BIO_printf(bio_s_out,"ERROR\n");
2234                                         ERR_print_errors(bio_err);
2235                                         ret=1;
2236                                         goto err;
2237                                         /* break; */
2238                                 case SSL_ERROR_ZERO_RETURN:
2239                                         BIO_printf(bio_s_out,"DONE\n");
2240                                         ret=1;
2241                                         goto err;
2242                                         }
2243                                 l+=k;
2244                                 i-=k;
2245                                 if (i <= 0) break;
2246                                 }
2247                         }
2248                 if (read_from_sslcon)
2249                         {
2250                         if (!SSL_is_init_finished(con))
2251                                 {
2252                                 i=init_ssl_connection(con);
2253                                 
2254                                 if (i < 0)
2255                                         {
2256                                         ret=0;
2257                                         goto err;
2258                                         }
2259                                 else if (i == 0)
2260                                         {
2261                                         ret=1;
2262                                         goto err;
2263                                         }
2264                                 }
2265                         else
2266                                 {
2267 again:  
2268                                 i=SSL_read(con,(char *)buf,bufsize);
2269                                 switch (SSL_get_error(con,i))
2270                                         {
2271                                 case SSL_ERROR_NONE:
2272 #ifdef CHARSET_EBCDIC
2273                                         ascii2ebcdic(buf,buf,i);
2274 #endif
2275                                         raw_write_stdout(buf,
2276                                                 (unsigned int)i);
2277                                         if (SSL_pending(con)) goto again;
2278                                         break;
2279                                 case SSL_ERROR_WANT_WRITE:
2280                                 case SSL_ERROR_WANT_READ:
2281                                 case SSL_ERROR_WANT_X509_LOOKUP:
2282                                         BIO_printf(bio_s_out,"Read BLOCK\n");
2283                                         break;
2284                                 case SSL_ERROR_SYSCALL:
2285                                 case SSL_ERROR_SSL:
2286                                         BIO_printf(bio_s_out,"ERROR\n");
2287                                         ERR_print_errors(bio_err);
2288                                         ret=1;
2289                                         goto err;
2290                                 case SSL_ERROR_ZERO_RETURN:
2291                                         BIO_printf(bio_s_out,"DONE\n");
2292                                         ret=1;
2293                                         goto err;
2294                                         }
2295                                 }
2296                         }
2297                 }
2298 err:
2299         if (con != NULL)
2300                 {
2301                 BIO_printf(bio_s_out,"shutting down SSL\n");
2302 #if 1
2303                 SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
2304 #else
2305                 SSL_shutdown(con);
2306 #endif
2307                 SSL_free(con);
2308                 }
2309         BIO_printf(bio_s_out,"CONNECTION CLOSED\n");
2310         if (buf != NULL)
2311                 {
2312                 OPENSSL_cleanse(buf,bufsize);
2313                 OPENSSL_free(buf);
2314                 }
2315         if (ret >= 0)
2316                 BIO_printf(bio_s_out,"ACCEPT\n");
2317         return(ret);
2318         }
2319
2320 static void close_accept_socket(void)
2321         {
2322         BIO_printf(bio_err,"shutdown accept socket\n");
2323         if (accept_socket >= 0)
2324                 {
2325                 SHUTDOWN2(accept_socket);
2326                 }
2327         }
2328
2329 static int init_ssl_connection(SSL *con)
2330         {
2331         int i;
2332         const char *str;
2333         X509 *peer;
2334         long verify_error;
2335         MS_STATIC char buf[BUFSIZ];
2336 #ifndef OPENSSL_NO_KRB5
2337         char *client_princ;
2338 #endif
2339 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2340         const unsigned char *next_proto_neg;
2341         unsigned next_proto_neg_len;
2342 #endif
2343         unsigned char *exportedkeymat;
2344
2345
2346         if ((i=SSL_accept(con)) <= 0)
2347                 {
2348                 if (BIO_sock_should_retry(i))
2349                         {
2350                         BIO_printf(bio_s_out,"DELAY\n");
2351                         return(1);
2352                         }
2353
2354                 BIO_printf(bio_err,"ERROR\n");
2355                 verify_error=SSL_get_verify_result(con);
2356                 if (verify_error != X509_V_OK)
2357                         {
2358                         BIO_printf(bio_err,"verify error:%s\n",
2359                                 X509_verify_cert_error_string(verify_error));
2360                         }
2361                 else
2362                         ERR_print_errors(bio_err);
2363                 return(0);
2364                 }
2365
2366         PEM_write_bio_SSL_SESSION(bio_s_out,SSL_get_session(con));
2367
2368         peer=SSL_get_peer_certificate(con);
2369         if (peer != NULL)
2370                 {
2371                 BIO_printf(bio_s_out,"Client certificate\n");
2372                 PEM_write_bio_X509(bio_s_out,peer);
2373                 X509_NAME_oneline(X509_get_subject_name(peer),buf,sizeof buf);
2374                 BIO_printf(bio_s_out,"subject=%s\n",buf);
2375                 X509_NAME_oneline(X509_get_issuer_name(peer),buf,sizeof buf);
2376                 BIO_printf(bio_s_out,"issuer=%s\n",buf);
2377                 X509_free(peer);
2378                 }
2379
2380         if (SSL_get_shared_ciphers(con,buf,sizeof buf) != NULL)
2381                 BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf);
2382         str=SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2383         BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)");
2384 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2385         SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2386         if (next_proto_neg)
2387                 {
2388                 BIO_printf(bio_s_out,"NEXTPROTO is ");
2389                 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2390                 BIO_printf(bio_s_out, "\n");
2391                 }
2392 #endif
2393         {
2394         SRTP_PROTECTION_PROFILE *srtp_profile
2395           = SSL_get_selected_srtp_profile(con);
2396
2397         if(srtp_profile)
2398                 BIO_printf(bio_s_out,"SRTP Extension negotiated, profile=%s\n",
2399                            srtp_profile->name);
2400         }
2401         if (SSL_cache_hit(con)) BIO_printf(bio_s_out,"Reused session-id\n");
2402         if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) &
2403                 TLS1_FLAGS_TLS_PADDING_BUG)
2404                 BIO_printf(bio_s_out,
2405                            "Peer has incorrect TLSv1 block padding\n");
2406 #ifndef OPENSSL_NO_KRB5
2407         client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
2408         if (client_princ != NULL)
2409                 {
2410                 BIO_printf(bio_s_out,"Kerberos peer principal is %s\n",
2411                                                                 client_princ);
2412                 }
2413 #endif /* OPENSSL_NO_KRB5 */
2414         BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2415                       SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2416         if (keymatexportlabel != NULL) {
2417                 BIO_printf(bio_s_out, "Keying material exporter:\n");
2418                 BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
2419                 BIO_printf(bio_s_out, "    Length: %i bytes\n",
2420                            keymatexportlen);
2421                 exportedkeymat = OPENSSL_malloc(keymatexportlen);
2422                 if (exportedkeymat != NULL) {
2423                         i = SSL_export_keying_material(con, exportedkeymat,
2424                                                        keymatexportlen,
2425                                                        keymatexportlabel,
2426                                                      strlen(keymatexportlabel),
2427                                                        NULL, 0, 0);
2428                         if (i != keymatexportlen) {
2429                                 BIO_printf(bio_s_out,
2430                                            "    Error: return value %i\n", i);
2431                         } else {
2432                                 BIO_printf(bio_s_out, "    Keying material: ");
2433                                 for (i=0; i<keymatexportlen; i++)
2434                                         BIO_printf(bio_s_out, "%02X",
2435                                                    exportedkeymat[i]);
2436                                 BIO_printf(bio_s_out, "\n");
2437                         }
2438                         OPENSSL_free(exportedkeymat);
2439                 }
2440         }
2441
2442         return(1);
2443         }
2444
2445 #ifndef OPENSSL_NO_DH
2446 static DH *load_dh_param(const char *dhfile)
2447         {
2448         DH *ret=NULL;
2449         BIO *bio;
2450
2451         if ((bio=BIO_new_file(dhfile,"r")) == NULL)
2452                 goto err;
2453         ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
2454 err:
2455         if (bio != NULL) BIO_free(bio);
2456         return(ret);
2457         }
2458 #endif
2459 #ifndef OPENSSL_NO_KRB5
2460         char *client_princ;
2461 #endif
2462
2463 #if 0
2464 static int load_CA(SSL_CTX *ctx, char *file)
2465         {
2466         FILE *in;
2467         X509 *x=NULL;
2468
2469         if ((in=fopen(file,"r")) == NULL)
2470                 return(0);
2471
2472         for (;;)
2473                 {
2474                 if (PEM_read_X509(in,&x,NULL) == NULL)
2475                         break;
2476                 SSL_CTX_add_client_CA(ctx,x);
2477                 }
2478         if (x != NULL) X509_free(x);
2479         fclose(in);
2480         return(1);
2481         }
2482 #endif
2483
2484 static int www_body(char *hostname, int s, unsigned char *context)
2485         {
2486         char *buf=NULL;
2487         int ret=1;
2488         int i,j,k,dot;
2489         SSL *con;
2490         const SSL_CIPHER *c;
2491         BIO *io,*ssl_bio,*sbio;
2492 #ifndef OPENSSL_NO_KRB5
2493         KSSL_CTX *kctx;
2494 #endif
2495
2496         buf=OPENSSL_malloc(bufsize);
2497         if (buf == NULL) return(0);
2498         io=BIO_new(BIO_f_buffer());
2499         ssl_bio=BIO_new(BIO_f_ssl());
2500         if ((io == NULL) || (ssl_bio == NULL)) goto err;
2501
2502 #ifdef FIONBIO  
2503         if (s_nbio)
2504                 {
2505                 unsigned long sl=1;
2506
2507                 if (!s_quiet)
2508                         BIO_printf(bio_err,"turning on non blocking io\n");
2509                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
2510                         ERR_print_errors(bio_err);
2511                 }
2512 #endif
2513
2514         /* lets make the output buffer a reasonable size */
2515         if (!BIO_set_write_buffer_size(io,bufsize)) goto err;
2516
2517         if ((con=SSL_new(ctx)) == NULL) goto err;
2518 #ifndef OPENSSL_NO_TLSEXT
2519                 if (s_tlsextdebug)
2520                         {
2521                         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2522                         SSL_set_tlsext_debug_arg(con, bio_s_out);
2523                         }
2524 #endif
2525 #ifndef OPENSSL_NO_KRB5
2526         if ((kctx = kssl_ctx_new()) != NULL)
2527                 {
2528                 kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
2529                 kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
2530                 }
2531 #endif  /* OPENSSL_NO_KRB5 */
2532         if(context) SSL_set_session_id_context(con, context,
2533                                                strlen((char *)context));
2534
2535         sbio=BIO_new_socket(s,BIO_NOCLOSE);
2536         if (s_nbio_test)
2537                 {
2538                 BIO *test;
2539
2540                 test=BIO_new(BIO_f_nbio_test());
2541                 sbio=BIO_push(test,sbio);
2542                 }
2543         SSL_set_bio(con,sbio,sbio);
2544         SSL_set_accept_state(con);
2545
2546         /* SSL_set_fd(con,s); */
2547         BIO_set_ssl(ssl_bio,con,BIO_CLOSE);
2548         BIO_push(io,ssl_bio);
2549 #ifdef CHARSET_EBCDIC
2550         io = BIO_push(BIO_new(BIO_f_ebcdic_filter()),io);
2551 #endif
2552
2553         if (s_debug)
2554                 {
2555                 SSL_set_debug(con, 1);
2556                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2557                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2558                 }
2559         if (s_msg)
2560                 {
2561                 SSL_set_msg_callback(con, msg_cb);
2562                 SSL_set_msg_callback_arg(con, bio_s_out);
2563                 }
2564
2565         for (;;)
2566                 {
2567                 if (hack)
2568                         {
2569                         i=SSL_accept(con);
2570
2571                         switch (SSL_get_error(con,i))
2572                                 {
2573                         case SSL_ERROR_NONE:
2574                                 break;
2575                         case SSL_ERROR_WANT_WRITE:
2576                         case SSL_ERROR_WANT_READ:
2577                         case SSL_ERROR_WANT_X509_LOOKUP:
2578                                 continue;
2579                         case SSL_ERROR_SYSCALL:
2580                         case SSL_ERROR_SSL:
2581                         case SSL_ERROR_ZERO_RETURN:
2582                                 ret=1;
2583                                 goto err;
2584                                 /* break; */
2585                                 }
2586
2587                         SSL_renegotiate(con);
2588                         SSL_write(con,NULL,0);
2589                         }
2590
2591                 i=BIO_gets(io,buf,bufsize-1);
2592                 if (i < 0) /* error */
2593                         {
2594                         if (!BIO_should_retry(io))
2595                                 {
2596                                 if (!s_quiet)
2597                                         ERR_print_errors(bio_err);
2598                                 goto err;
2599                                 }
2600                         else
2601                                 {
2602                                 BIO_printf(bio_s_out,"read R BLOCK\n");
2603 #if defined(OPENSSL_SYS_NETWARE)
2604             delay(1000);
2605 #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
2606                                 sleep(1);
2607 #endif
2608                                 continue;
2609                                 }
2610                         }
2611                 else if (i == 0) /* end of input */
2612                         {
2613                         ret=1;
2614                         goto end;
2615                         }
2616
2617                 /* else we have data */
2618                 if (    ((www == 1) && (strncmp("GET ",buf,4) == 0)) ||
2619                         ((www == 2) && (strncmp("GET /stats ",buf,10) == 0)))
2620                         {
2621                         char *p;
2622                         X509 *peer;
2623                         STACK_OF(SSL_CIPHER) *sk;
2624                         static const char *space="                          ";
2625
2626                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2627                         BIO_puts(io,"<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2628                         BIO_puts(io,"<pre>\n");
2629 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
2630                         BIO_puts(io,"\n");
2631                         for (i=0; i<local_argc; i++)
2632                                 {
2633                                 BIO_puts(io,local_argv[i]);
2634                                 BIO_write(io," ",1);
2635                                 }
2636                         BIO_puts(io,"\n");
2637
2638                         /* The following is evil and should not really
2639                          * be done */
2640                         BIO_printf(io,"Ciphers supported in s_server binary\n");
2641                         sk=SSL_get_ciphers(con);
2642                         j=sk_SSL_CIPHER_num(sk);
2643                         for (i=0; i<j; i++)
2644                                 {
2645                                 c=sk_SSL_CIPHER_value(sk,i);
2646                                 BIO_printf(io,"%-11s:%-25s",
2647                                         SSL_CIPHER_get_version(c),
2648                                         SSL_CIPHER_get_name(c));
2649                                 if ((((i+1)%2) == 0) && (i+1 != j))
2650                                         BIO_puts(io,"\n");
2651                                 }
2652                         BIO_puts(io,"\n");
2653                         p=SSL_get_shared_ciphers(con,buf,bufsize);
2654                         if (p != NULL)
2655                                 {
2656                                 BIO_printf(io,"---\nCiphers common between both SSL end points:\n");
2657                                 j=i=0;
2658                                 while (*p)
2659                                         {
2660                                         if (*p == ':')
2661                                                 {
2662                                                 BIO_write(io,space,26-j);
2663                                                 i++;
2664                                                 j=0;
2665                                                 BIO_write(io,((i%3)?" ":"\n"),1);
2666                                                 }
2667                                         else
2668                                                 {
2669                                                 BIO_write(io,p,1);
2670                                                 j++;
2671                                                 }
2672                                         p++;
2673                                         }
2674                                 BIO_puts(io,"\n");
2675                                 }
2676                         BIO_printf(io,(SSL_cache_hit(con)
2677                                 ?"---\nReused, "
2678                                 :"---\nNew, "));
2679                         c=SSL_get_current_cipher(con);
2680                         BIO_printf(io,"%s, Cipher is %s\n",
2681                                 SSL_CIPHER_get_version(c),
2682                                 SSL_CIPHER_get_name(c));
2683                         SSL_SESSION_print(io,SSL_get_session(con));
2684                         BIO_printf(io,"---\n");
2685                         print_stats(io,SSL_get_SSL_CTX(con));
2686                         BIO_printf(io,"---\n");
2687                         peer=SSL_get_peer_certificate(con);
2688                         if (peer != NULL)
2689                                 {
2690                                 BIO_printf(io,"Client certificate\n");
2691                                 X509_print(io,peer);
2692                                 PEM_write_bio_X509(io,peer);
2693                                 }
2694                         else
2695                                 BIO_puts(io,"no client certificate available\n");
2696                         BIO_puts(io,"</BODY></HTML>\r\n\r\n");
2697                         break;
2698                         }
2699                 else if ((www == 2 || www == 3)
2700                          && (strncmp("GET /",buf,5) == 0))
2701                         {
2702                         BIO *file;
2703                         char *p,*e;
2704                         static const char *text="HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
2705
2706                         /* skip the '/' */
2707                         p= &(buf[5]);
2708
2709                         dot = 1;
2710                         for (e=p; *e != '\0'; e++)
2711                                 {
2712                                 if (e[0] == ' ')
2713                                         break;
2714
2715                                 switch (dot)
2716                                         {
2717                                 case 1:
2718                                         dot = (e[0] == '.') ? 2 : 0;
2719                                         break;
2720                                 case 2:
2721                                         dot = (e[0] == '.') ? 3 : 0;
2722                                         break;
2723                                 case 3:
2724                                         dot = (e[0] == '/') ? -1 : 0;
2725                                         break;
2726                                         }
2727                                 if (dot == 0)
2728                                         dot = (e[0] == '/') ? 1 : 0;
2729                                 }
2730                         dot = (dot == 3) || (dot == -1); /* filename contains ".." component */
2731
2732                         if (*e == '\0')
2733                                 {
2734                                 BIO_puts(io,text);
2735                                 BIO_printf(io,"'%s' is an invalid file name\r\n",p);
2736                                 break;
2737                                 }
2738                         *e='\0';
2739
2740                         if (dot)
2741                                 {
2742                                 BIO_puts(io,text);
2743                                 BIO_printf(io,"'%s' contains '..' reference\r\n",p);
2744                                 break;
2745                                 }
2746
2747                         if (*p == '/')
2748                                 {
2749                                 BIO_puts(io,text);
2750                                 BIO_printf(io,"'%s' is an invalid path\r\n",p);
2751                                 break;
2752                                 }
2753
2754 #if 0
2755                         /* append if a directory lookup */
2756                         if (e[-1] == '/')
2757                                 strcat(p,"index.html");
2758 #endif
2759
2760                         /* if a directory, do the index thang */
2761                         if (app_isdir(p)>0)
2762                                 {
2763 #if 0 /* must check buffer size */
2764                                 strcat(p,"/index.html");
2765 #else
2766                                 BIO_puts(io,text);
2767                                 BIO_printf(io,"'%s' is a directory\r\n",p);
2768                                 break;
2769 #endif
2770                                 }
2771
2772                         if ((file=BIO_new_file(p,"r")) == NULL)
2773                                 {
2774                                 BIO_puts(io,text);
2775                                 BIO_printf(io,"Error opening '%s'\r\n",p);
2776                                 ERR_print_errors(io);
2777                                 break;
2778                                 }
2779
2780                         if (!s_quiet)
2781                                 BIO_printf(bio_err,"FILE:%s\n",p);
2782
2783                         if (www == 2)
2784                                 {
2785                                 i=strlen(p);
2786                                 if (    ((i > 5) && (strcmp(&(p[i-5]),".html") == 0)) ||
2787                                         ((i > 4) && (strcmp(&(p[i-4]),".php") == 0)) ||
2788                                         ((i > 4) && (strcmp(&(p[i-4]),".htm") == 0)))
2789                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2790                                 else
2791                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2792                                 }
2793                         /* send the file */
2794                         for (;;)
2795                                 {
2796                                 i=BIO_read(file,buf,bufsize);
2797                                 if (i <= 0) break;
2798
2799 #ifdef RENEG
2800                                 total_bytes+=i;
2801                                 fprintf(stderr,"%d\n",i);
2802                                 if (total_bytes > 3*1024)
2803                                         {
2804                                         total_bytes=0;
2805                                         fprintf(stderr,"RENEGOTIATE\n");
2806                                         SSL_renegotiate(con);
2807                                         }
2808 #endif
2809
2810                                 for (j=0; j<i; )
2811                                         {
2812 #ifdef RENEG
2813 { static count=0; if (++count == 13) { SSL_renegotiate(con); } }
2814 #endif
2815                                         k=BIO_write(io,&(buf[j]),i-j);
2816                                         if (k <= 0)
2817                                                 {
2818                                                 if (!BIO_should_retry(io))
2819                                                         goto write_error;
2820                                                 else
2821                                                         {
2822                                                         BIO_printf(bio_s_out,"rwrite W BLOCK\n");
2823                                                         }
2824                                                 }
2825                                         else
2826                                                 {
2827                                                 j+=k;
2828                                                 }
2829                                         }
2830                                 }
2831 write_error:
2832                         BIO_free(file);
2833                         break;
2834                         }
2835                 }
2836
2837         for (;;)
2838                 {
2839                 i=(int)BIO_flush(io);
2840                 if (i <= 0)
2841                         {
2842                         if (!BIO_should_retry(io))
2843                                 break;
2844                         }
2845                 else
2846                         break;
2847                 }
2848 end:
2849 #if 1
2850         /* make sure we re-use sessions */
2851         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
2852 #else
2853         /* This kills performance */
2854 /*      SSL_shutdown(con); A shutdown gets sent in the
2855  *      BIO_free_all(io) procession */
2856 #endif
2857
2858 err:
2859
2860         if (ret >= 0)
2861                 BIO_printf(bio_s_out,"ACCEPT\n");
2862
2863         if (buf != NULL) OPENSSL_free(buf);
2864         if (io != NULL) BIO_free_all(io);
2865 /*      if (ssl_bio != NULL) BIO_free(ssl_bio);*/
2866         return(ret);
2867         }
2868
2869 #ifndef OPENSSL_NO_RSA
2870 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
2871         {
2872         BIGNUM *bn = NULL;
2873         static RSA *rsa_tmp=NULL;
2874
2875         if (!rsa_tmp && ((bn = BN_new()) == NULL))
2876                 BIO_printf(bio_err,"Allocation error in generating RSA key\n");
2877         if (!rsa_tmp && bn)
2878                 {
2879                 if (!s_quiet)
2880                         {
2881                         BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
2882                         (void)BIO_flush(bio_err);
2883                         }
2884                 if(!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
2885                                 !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL))
2886                         {
2887                         if(rsa_tmp) RSA_free(rsa_tmp);
2888                         rsa_tmp = NULL;
2889                         }
2890                 if (!s_quiet)
2891                         {
2892                         BIO_printf(bio_err,"\n");
2893                         (void)BIO_flush(bio_err);
2894                         }
2895                 BN_free(bn);
2896                 }
2897         return(rsa_tmp);
2898         }
2899 #endif
2900
2901 #define MAX_SESSION_ID_ATTEMPTS 10
2902 static int generate_session_id(const SSL *ssl, unsigned char *id,
2903                                 unsigned int *id_len)
2904         {
2905         unsigned int count = 0;
2906         do      {
2907                 RAND_pseudo_bytes(id, *id_len);
2908                 /* Prefix the session_id with the required prefix. NB: If our
2909                  * prefix is too long, clip it - but there will be worse effects
2910                  * anyway, eg. the server could only possibly create 1 session
2911                  * ID (ie. the prefix!) so all future session negotiations will
2912                  * fail due to conflicts. */
2913                 memcpy(id, session_id_prefix,
2914                         (strlen(session_id_prefix) < *id_len) ?
2915                         strlen(session_id_prefix) : *id_len);
2916                 }
2917         while(SSL_has_matching_session_id(ssl, id, *id_len) &&
2918                 (++count < MAX_SESSION_ID_ATTEMPTS));
2919         if(count >= MAX_SESSION_ID_ATTEMPTS)
2920                 return 0;
2921         return 1;
2922         }