[BACK]Return to s_server.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / openssl

Annotation of src/usr.bin/openssl/s_server.c, Revision 1.20

1.20    ! doug        1: /* $OpenBSD: s_server.c,v 1.19 2015/10/06 03:29:49 deraadt Exp $ */
1.1       jsing       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 <sys/types.h>
                    150: #include <sys/socket.h>
                    151:
                    152: #include <assert.h>
                    153: #include <ctype.h>
                    154: #include <stdio.h>
                    155: #include <stdlib.h>
                    156: #include <limits.h>
                    157: #include <string.h>
                    158: #include <unistd.h>
1.7       deraadt   159: #include <poll.h>
1.1       jsing     160:
                    161: #include "apps.h"
                    162:
                    163: #include <openssl/bn.h>
                    164: #include <openssl/err.h>
                    165: #include <openssl/lhash.h>
                    166: #include <openssl/ocsp.h>
                    167: #include <openssl/pem.h>
                    168: #include <openssl/ssl.h>
                    169: #include <openssl/x509.h>
                    170:
                    171: #ifndef OPENSSL_NO_DH
                    172: #include <openssl/dh.h>
                    173: #endif
                    174:
                    175: #include <openssl/rsa.h>
                    176:
                    177: #include "s_apps.h"
                    178: #include "timeouts.h"
                    179:
                    180: static int sv_body(char *hostname, int s, unsigned char *context);
                    181: static int www_body(char *hostname, int s, unsigned char *context);
                    182: static void close_accept_socket(void);
                    183: static void sv_usage(void);
                    184: static int init_ssl_connection(SSL * s);
                    185: static void print_stats(BIO * bp, SSL_CTX * ctx);
                    186: static int
                    187: generate_session_id(const SSL * ssl, unsigned char *id,
                    188:     unsigned int *id_len);
                    189: #ifndef OPENSSL_NO_DH
                    190: static DH *load_dh_param(const char *dhfile);
                    191: #endif
                    192:
                    193: static void s_server_init(void);
                    194:
                    195: /* static int load_CA(SSL_CTX *ctx, char *file);*/
                    196:
                    197: #define BUFSIZZ        16*1024
                    198: static int bufsize = BUFSIZZ;
                    199: static int accept_socket = -1;
                    200:
                    201: #define TEST_CERT      "server.pem"
                    202: #define TEST_CERT2     "server2.pem"
                    203:
                    204: static char *cipher = NULL;
                    205: static int s_server_verify = SSL_VERIFY_NONE;
                    206: static int s_server_session_id_context = 1;    /* anything will do */
                    207: static const char *s_cert_file = TEST_CERT, *s_key_file = NULL;
                    208: static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
                    209: static char *s_dcert_file = NULL, *s_dkey_file = NULL;
                    210: static int s_nbio = 0;
                    211: static int s_nbio_test = 0;
                    212: int s_crlf = 0;
                    213: static SSL_CTX *ctx = NULL;
                    214: static SSL_CTX *ctx2 = NULL;
                    215: static int www = 0;
                    216:
                    217: static BIO *bio_s_out = NULL;
                    218: static int s_debug = 0;
                    219: static int s_tlsextdebug = 0;
                    220: static int s_tlsextstatus = 0;
                    221: static int cert_status_cb(SSL * s, void *arg);
                    222: static int s_msg = 0;
                    223: static int s_quiet = 0;
                    224:
                    225: static char *keymatexportlabel = NULL;
                    226: static int keymatexportlen = 20;
                    227:
                    228: static const char *session_id_prefix = NULL;
                    229:
                    230: static int enable_timeouts = 0;
                    231: static long socket_mtu;
                    232: #ifndef OPENSSL_NO_DTLS1
                    233: static int cert_chain = 0;
                    234: #endif
                    235:
                    236:
                    237:
                    238:
                    239: static void
                    240: s_server_init(void)
                    241: {
                    242:        accept_socket = -1;
                    243:        cipher = NULL;
                    244:        s_server_verify = SSL_VERIFY_NONE;
                    245:        s_dcert_file = NULL;
                    246:        s_dkey_file = NULL;
                    247:        s_cert_file = TEST_CERT;
                    248:        s_key_file = NULL;
                    249:        s_cert_file2 = TEST_CERT2;
                    250:        s_key_file2 = NULL;
                    251:        ctx2 = NULL;
                    252:        s_nbio = 0;
                    253:        s_nbio_test = 0;
                    254:        ctx = NULL;
                    255:        www = 0;
                    256:
                    257:        bio_s_out = NULL;
                    258:        s_debug = 0;
                    259:        s_msg = 0;
                    260:        s_quiet = 0;
                    261: }
                    262:
                    263: static void
                    264: sv_usage(void)
                    265: {
                    266:        BIO_printf(bio_err, "usage: s_server [args ...]\n");
                    267:        BIO_printf(bio_err, "\n");
                    268:        BIO_printf(bio_err, " -accept arg   - port to accept on (default is %d)\n", PORT);
                    269:        BIO_printf(bio_err, " -context arg  - set session ID context\n");
                    270:        BIO_printf(bio_err, " -verify arg   - turn on peer certificate verification\n");
                    271:        BIO_printf(bio_err, " -Verify arg   - turn on peer certificate verification, must have a cert.\n");
                    272:        BIO_printf(bio_err, " -cert arg     - certificate file to use\n");
                    273:        BIO_printf(bio_err, "                 (default is %s)\n", TEST_CERT);
                    274:        BIO_printf(bio_err, " -crl_check    - check the peer certificate has not been revoked by its CA.\n" \
                    275:            "                 The CRL(s) are appended to the certificate file\n");
                    276:        BIO_printf(bio_err, " -crl_check_all - check the peer certificate has not been revoked by its CA\n" \
                    277:            "                 or any other CRL in the CA chain. CRL(s) are appended to the\n" \
                    278:            "                 the certificate file.\n");
                    279:        BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n");
                    280:        BIO_printf(bio_err, " -key arg      - Private Key file to use, in cert file if\n");
                    281:        BIO_printf(bio_err, "                 not specified (default is %s)\n", TEST_CERT);
1.17      bcook     282:        BIO_printf(bio_err, " -keyform arg  - key format (PEM or DER) PEM default\n");
1.1       jsing     283:        BIO_printf(bio_err, " -pass arg     - private key file pass phrase source\n");
                    284:        BIO_printf(bio_err, " -dcert arg    - second certificate file to use (usually for DSA)\n");
                    285:        BIO_printf(bio_err, " -dcertform x  - second certificate format (PEM or DER) PEM default\n");
                    286:        BIO_printf(bio_err, " -dkey arg     - second private key file to use (usually for DSA)\n");
1.17      bcook     287:        BIO_printf(bio_err, " -dkeyform arg - second key format (PEM or DER) PEM default\n");
1.1       jsing     288:        BIO_printf(bio_err, " -dpass arg    - second private key file pass phrase source\n");
                    289:        BIO_printf(bio_err, " -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
                    290:        BIO_printf(bio_err, "                 or a default set of parameters is used\n");
                    291:        BIO_printf(bio_err, " -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
                    292:            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
                    293:            "                 (default is nistp256).\n");
                    294:        BIO_printf(bio_err, " -nbio         - Run with non-blocking IO\n");
                    295:        BIO_printf(bio_err, " -nbio_test    - test with the non-blocking test bio\n");
                    296:        BIO_printf(bio_err, " -crlf         - convert LF from terminal into CRLF\n");
                    297:        BIO_printf(bio_err, " -debug        - Print more output\n");
                    298:        BIO_printf(bio_err, " -msg          - Show protocol messages\n");
                    299:        BIO_printf(bio_err, " -state        - Print the SSL states\n");
                    300:        BIO_printf(bio_err, " -CApath arg   - PEM format directory of CA's\n");
                    301:        BIO_printf(bio_err, " -CAfile arg   - PEM format file of CA's\n");
                    302:        BIO_printf(bio_err, " -nocert       - Don't use any certificates (Anon-DH)\n");
                    303:        BIO_printf(bio_err, " -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
                    304:        BIO_printf(bio_err, " -serverpref   - Use server's cipher preferences\n");
                    305:        BIO_printf(bio_err, " -quiet        - Inhibit printing of session and certificate information\n");
                    306:        BIO_printf(bio_err, " -tls1_2       - Just talk TLSv1.2\n");
                    307:        BIO_printf(bio_err, " -tls1_1       - Just talk TLSv1.1\n");
                    308:        BIO_printf(bio_err, " -tls1         - Just talk TLSv1\n");
                    309:        BIO_printf(bio_err, " -dtls1        - Just talk DTLSv1\n");
                    310:        BIO_printf(bio_err, " -timeout      - Enable timeouts\n");
                    311:        BIO_printf(bio_err, " -mtu          - Set link layer MTU\n");
                    312:        BIO_printf(bio_err, " -chain        - Read a certificate chain\n");
                    313:        BIO_printf(bio_err, " -no_ssl2      - Just disable SSLv2\n");
                    314:        BIO_printf(bio_err, " -no_ssl3      - Just disable SSLv3\n");
                    315:        BIO_printf(bio_err, " -no_tls1      - Just disable TLSv1\n");
                    316:        BIO_printf(bio_err, " -no_tls1_1    - Just disable TLSv1.1\n");
                    317:        BIO_printf(bio_err, " -no_tls1_2    - Just disable TLSv1.2\n");
                    318: #ifndef OPENSSL_NO_DH
                    319:        BIO_printf(bio_err, " -no_dhe       - Disable ephemeral DH\n");
                    320: #endif
                    321:        BIO_printf(bio_err, " -no_ecdhe     - Disable ephemeral ECDH\n");
                    322:        BIO_printf(bio_err, " -bugs         - Turn on SSL bug compatibility\n");
                    323:        BIO_printf(bio_err, " -www          - Respond to a 'GET /' with a status page\n");
                    324:        BIO_printf(bio_err, " -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
                    325:        BIO_printf(bio_err, " -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
                    326:        BIO_printf(bio_err, "                 with the assumption it contains a complete HTTP response.\n");
                    327:        BIO_printf(bio_err, " -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
                    328:        BIO_printf(bio_err, " -servername host - servername for HostName TLS extension\n");
                    329:        BIO_printf(bio_err, " -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
                    330:        BIO_printf(bio_err, " -cert2 arg    - certificate file to use for servername\n");
                    331:        BIO_printf(bio_err, "                 (default is %s)\n", TEST_CERT2);
                    332:        BIO_printf(bio_err, " -key2 arg     - Private Key file to use for servername, in cert file if\n");
                    333:        BIO_printf(bio_err, "                 not specified (default is %s)\n", TEST_CERT2);
                    334:        BIO_printf(bio_err, " -tlsextdebug  - hex dump of all TLS extensions received\n");
                    335:        BIO_printf(bio_err, " -no_ticket    - disable use of RFC4507bis session tickets\n");
                    336:        BIO_printf(bio_err, " -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
1.8       jsing     337:        BIO_printf(bio_err," -alpn arg  - set the advertised protocols for the ALPN extension (comma-separated list)\n");
1.1       jsing     338: #ifndef OPENSSL_NO_SRTP
                    339:        BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
                    340: #endif
                    341:        BIO_printf(bio_err, " -keymatexport label   - Export keying material using label\n");
                    342:        BIO_printf(bio_err, " -keymatexportlen len  - Export len bytes of keying material (default 20)\n");
                    343: }
                    344:
                    345: static int local_argc = 0;
                    346: static char **local_argv;
                    347:
                    348:
                    349: /* This is a context that we pass to callbacks */
                    350: typedef struct tlsextctx_st {
                    351:        char *servername;
                    352:        BIO *biodebug;
                    353:        int extension_error;
                    354: } tlsextctx;
                    355:
                    356:
                    357: static int
                    358: ssl_servername_cb(SSL * s, int *ad, void *arg)
                    359: {
                    360:        tlsextctx *p = (tlsextctx *) arg;
                    361:        const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
                    362:        if (servername && p->biodebug)
                    363:                BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n", servername);
                    364:
                    365:        if (!p->servername)
                    366:                return SSL_TLSEXT_ERR_NOACK;
                    367:
                    368:        if (servername) {
                    369:                if (strcmp(servername, p->servername))
                    370:                        return p->extension_error;
                    371:                if (ctx2) {
                    372:                        BIO_printf(p->biodebug, "Switching server context.\n");
                    373:                        SSL_set_SSL_CTX(s, ctx2);
                    374:                }
                    375:        }
                    376:        return SSL_TLSEXT_ERR_OK;
                    377: }
                    378:
                    379: /* Structure passed to cert status callback */
                    380:
                    381: typedef struct tlsextstatusctx_st {
                    382:        /* Default responder to use */
                    383:        char *host, *path, *port;
                    384:        int use_ssl;
                    385:        int timeout;
                    386:        BIO *err;
                    387:        int verbose;
                    388: } tlsextstatusctx;
                    389:
                    390: static tlsextstatusctx tlscstatp = {NULL, NULL, NULL, 0, -1, NULL, 0};
                    391:
                    392: /* Certificate Status callback. This is called when a client includes a
                    393:  * certificate status request extension.
                    394:  *
                    395:  * This is a simplified version. It examines certificates each time and
                    396:  * makes one OCSP responder query for each request.
                    397:  *
                    398:  * A full version would store details such as the OCSP certificate IDs and
                    399:  * minimise the number of OCSP responses by caching them until they were
                    400:  * considered "expired".
                    401:  */
                    402:
                    403: static int
                    404: cert_status_cb(SSL * s, void *arg)
                    405: {
                    406:        tlsextstatusctx *srctx = arg;
                    407:        BIO *err = srctx->err;
                    408:        char *host, *port, *path;
                    409:        int use_ssl;
                    410:        unsigned char *rspder = NULL;
                    411:        int rspderlen;
                    412:        STACK_OF(OPENSSL_STRING) * aia = NULL;
                    413:        X509 *x = NULL;
                    414:        X509_STORE_CTX inctx;
                    415:        X509_OBJECT obj;
                    416:        OCSP_REQUEST *req = NULL;
                    417:        OCSP_RESPONSE *resp = NULL;
                    418:        OCSP_CERTID *id = NULL;
                    419:        STACK_OF(X509_EXTENSION) * exts;
                    420:        int ret = SSL_TLSEXT_ERR_NOACK;
                    421:        int i;
                    422:
                    423:        if (srctx->verbose)
                    424:                BIO_puts(err, "cert_status: callback called\n");
                    425:        /* Build up OCSP query from server certificate */
                    426:        x = SSL_get_certificate(s);
                    427:        aia = X509_get1_ocsp(x);
                    428:        if (aia) {
                    429:                if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
                    430:                        &host, &port, &path, &use_ssl)) {
                    431:                        BIO_puts(err, "cert_status: can't parse AIA URL\n");
                    432:                        goto err;
                    433:                }
                    434:                if (srctx->verbose)
                    435:                        BIO_printf(err, "cert_status: AIA URL: %s\n",
                    436:                            sk_OPENSSL_STRING_value(aia, 0));
                    437:        } else {
                    438:                if (!srctx->host) {
                    439:                        BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n");
                    440:                        goto done;
                    441:                }
                    442:                host = srctx->host;
                    443:                path = srctx->path;
                    444:                port = srctx->port;
                    445:                use_ssl = srctx->use_ssl;
                    446:        }
                    447:
                    448:        if (!X509_STORE_CTX_init(&inctx,
                    449:                SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
                    450:                NULL, NULL))
                    451:                goto err;
                    452:        if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
                    453:                X509_get_issuer_name(x), &obj) <= 0) {
                    454:                BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
                    455:                X509_STORE_CTX_cleanup(&inctx);
                    456:                goto done;
                    457:        }
                    458:        req = OCSP_REQUEST_new();
                    459:        if (!req)
                    460:                goto err;
                    461:        id = OCSP_cert_to_id(NULL, x, obj.data.x509);
                    462:        X509_free(obj.data.x509);
                    463:        X509_STORE_CTX_cleanup(&inctx);
                    464:        if (!id)
                    465:                goto err;
                    466:        if (!OCSP_request_add0_id(req, id))
                    467:                goto err;
                    468:        id = NULL;
                    469:        /* Add any extensions to the request */
                    470:        SSL_get_tlsext_status_exts(s, &exts);
                    471:        for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
                    472:                X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
                    473:                if (!OCSP_REQUEST_add_ext(req, ext, -1))
                    474:                        goto err;
                    475:        }
                    476:        resp = process_responder(err, req, host, path, port, use_ssl, NULL,
                    477:            srctx->timeout);
                    478:        if (!resp) {
                    479:                BIO_puts(err, "cert_status: error querying responder\n");
                    480:                goto done;
                    481:        }
                    482:        rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
                    483:        if (rspderlen <= 0)
                    484:                goto err;
                    485:        SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
                    486:        if (srctx->verbose) {
                    487:                BIO_puts(err, "cert_status: ocsp response sent:\n");
                    488:                OCSP_RESPONSE_print(err, resp, 2);
                    489:        }
                    490:        ret = SSL_TLSEXT_ERR_OK;
                    491: done:
                    492:        if (ret != SSL_TLSEXT_ERR_OK)
                    493:                ERR_print_errors(err);
                    494:        if (aia) {
                    495:                free(host);
                    496:                free(path);
                    497:                free(port);
                    498:                X509_email_free(aia);
                    499:        }
                    500:        if (id)
                    501:                OCSP_CERTID_free(id);
                    502:        if (req)
                    503:                OCSP_REQUEST_free(req);
                    504:        if (resp)
                    505:                OCSP_RESPONSE_free(resp);
                    506:        return ret;
                    507: err:
                    508:        ret = SSL_TLSEXT_ERR_ALERT_FATAL;
                    509:        goto done;
                    510: }
                    511:
                    512: /* This is the context that we pass to next_proto_cb */
                    513: typedef struct tlsextnextprotoctx_st {
                    514:        unsigned char *data;
                    515:        unsigned int len;
                    516: } tlsextnextprotoctx;
                    517:
                    518: static int
                    519: next_proto_cb(SSL * s, const unsigned char **data, unsigned int *len, void *arg)
                    520: {
                    521:        tlsextnextprotoctx *next_proto = arg;
                    522:
                    523:        *data = next_proto->data;
                    524:        *len = next_proto->len;
                    525:
                    526:        return SSL_TLSEXT_ERR_OK;
                    527: }
                    528:
                    529:
1.8       jsing     530: /* This the context that we pass to alpn_cb */
                    531: typedef struct tlsextalpnctx_st {
                    532:        unsigned char *data;
                    533:        unsigned short len;
                    534: } tlsextalpnctx;
                    535:
                    536: static int
                    537: alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,
                    538:     const unsigned char *in, unsigned int inlen, void *arg)
                    539: {
                    540:        tlsextalpnctx *alpn_ctx = arg;
                    541:
                    542:        if (!s_quiet) {
                    543:                /* We can assume that in is syntactically valid. */
                    544:                unsigned i;
                    545:
                    546:                BIO_printf(bio_s_out,
                    547:                    "ALPN protocols advertised by the client: ");
                    548:                for (i = 0; i < inlen; ) {
                    549:                        if (i)
                    550:                                BIO_write(bio_s_out, ", ", 2);
                    551:                        BIO_write(bio_s_out, &in[i + 1], in[i]);
                    552:                        i += in[i] + 1;
                    553:                }
                    554:                BIO_write(bio_s_out, "\n", 1);
                    555:        }
                    556:
                    557:        if (SSL_select_next_proto((unsigned char**)out, outlen, alpn_ctx->data,
                    558:            alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED)
                    559:                return (SSL_TLSEXT_ERR_NOACK);
                    560:
                    561:        if (!s_quiet) {
                    562:                BIO_printf(bio_s_out, "ALPN protocols selected: ");
                    563:                BIO_write(bio_s_out, *out, *outlen);
                    564:                BIO_write(bio_s_out, "\n", 1);
                    565:        }
                    566:
                    567:        return (SSL_TLSEXT_ERR_OK);
                    568: }
1.1       jsing     569:
                    570: #ifndef OPENSSL_NO_SRTP
                    571: static char *srtp_profiles = NULL;
                    572: #endif
                    573:
                    574: int
                    575: s_server_main(int argc, char *argv[])
                    576: {
                    577:        X509_VERIFY_PARAM *vpm = NULL;
                    578:        int badarg = 0;
                    579:        short port = PORT;
                    580:        char *CApath = NULL, *CAfile = NULL;
                    581:        unsigned char *context = NULL;
                    582:        char *dhfile = NULL;
                    583:        char *named_curve = NULL;
                    584:        int badop = 0, bugs = 0;
                    585:        int ret = 1;
                    586:        int off = 0;
1.5       jsing     587:        int no_dhe = 0, no_ecdhe = 0, nocert = 0;
1.1       jsing     588:        int state = 0;
                    589:        const SSL_METHOD *meth = NULL;
                    590:        int socket_type = SOCK_STREAM;
                    591:        int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
                    592:        char *passarg = NULL, *pass = NULL;
                    593:        char *dpassarg = NULL, *dpass = NULL;
                    594:        int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
                    595:        X509 *s_cert = NULL, *s_dcert = NULL;
                    596:        EVP_PKEY *s_key = NULL, *s_dkey = NULL;
                    597:        int no_cache = 0;
                    598:        const char *errstr = NULL;
                    599:        EVP_PKEY *s_key2 = NULL;
                    600:        X509 *s_cert2 = NULL;
                    601:        tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING};
                    602:        const char *next_proto_neg_in = NULL;
1.8       jsing     603:        tlsextnextprotoctx next_proto = { NULL, 0 };
                    604:        const char *alpn_in = NULL;
                    605:        tlsextalpnctx alpn_ctx = { NULL, 0 };
1.20    ! doug      606:
        !           607:        if (single_execution) {
        !           608:                if (pledge("stdio inet rpath", NULL) == -1)
        !           609:                        perror("pledge");
        !           610:        }
        !           611:
1.1       jsing     612:        meth = SSLv23_server_method();
                    613:
                    614:        local_argc = argc;
                    615:        local_argv = argv;
                    616:
                    617:        s_server_init();
                    618:
                    619:        verify_depth = 0;
                    620:        s_nbio = 0;
                    621:        s_nbio_test = 0;
                    622:
                    623:        argc--;
                    624:        argv++;
                    625:
                    626:        while (argc >= 1) {
                    627:                if ((strcmp(*argv, "-port") == 0) ||
                    628:                    (strcmp(*argv, "-accept") == 0)) {
                    629:                        if (--argc < 1)
                    630:                                goto bad;
                    631:                        if (!extract_port(*(++argv), &port))
                    632:                                goto bad;
                    633:                } else if (strcmp(*argv, "-verify") == 0) {
                    634:                        s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
                    635:                        if (--argc < 1)
                    636:                                goto bad;
                    637:                        verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
                    638:                        if (errstr)
                    639:                                goto bad;
                    640:                        BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
                    641:                } else if (strcmp(*argv, "-Verify") == 0) {
                    642:                        s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
                    643:                            SSL_VERIFY_CLIENT_ONCE;
                    644:                        if (--argc < 1)
                    645:                                goto bad;
                    646:                        verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
                    647:                        if (errstr)
                    648:                                goto bad;
                    649:                        BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_depth);
                    650:                } else if (strcmp(*argv, "-context") == 0) {
                    651:                        if (--argc < 1)
                    652:                                goto bad;
                    653:                        context = (unsigned char *) *(++argv);
                    654:                } else if (strcmp(*argv, "-cert") == 0) {
                    655:                        if (--argc < 1)
                    656:                                goto bad;
                    657:                        s_cert_file = *(++argv);
                    658:                } else if (strcmp(*argv, "-certform") == 0) {
                    659:                        if (--argc < 1)
                    660:                                goto bad;
                    661:                        s_cert_format = str2fmt(*(++argv));
                    662:                } else if (strcmp(*argv, "-key") == 0) {
                    663:                        if (--argc < 1)
                    664:                                goto bad;
                    665:                        s_key_file = *(++argv);
                    666:                } else if (strcmp(*argv, "-keyform") == 0) {
                    667:                        if (--argc < 1)
                    668:                                goto bad;
                    669:                        s_key_format = str2fmt(*(++argv));
                    670:                } else if (strcmp(*argv, "-pass") == 0) {
                    671:                        if (--argc < 1)
                    672:                                goto bad;
                    673:                        passarg = *(++argv);
                    674:                } else if (strcmp(*argv, "-dhparam") == 0) {
                    675:                        if (--argc < 1)
                    676:                                goto bad;
                    677:                        dhfile = *(++argv);
                    678:                }
                    679:                else if (strcmp(*argv, "-named_curve") == 0) {
                    680:                        if (--argc < 1)
                    681:                                goto bad;
                    682:                        named_curve = *(++argv);
                    683:                }
                    684:                else if (strcmp(*argv, "-dcertform") == 0) {
                    685:                        if (--argc < 1)
                    686:                                goto bad;
                    687:                        s_dcert_format = str2fmt(*(++argv));
                    688:                } else if (strcmp(*argv, "-dcert") == 0) {
                    689:                        if (--argc < 1)
                    690:                                goto bad;
                    691:                        s_dcert_file = *(++argv);
                    692:                } else if (strcmp(*argv, "-dkeyform") == 0) {
                    693:                        if (--argc < 1)
                    694:                                goto bad;
                    695:                        s_dkey_format = str2fmt(*(++argv));
                    696:                } else if (strcmp(*argv, "-dpass") == 0) {
                    697:                        if (--argc < 1)
                    698:                                goto bad;
                    699:                        dpassarg = *(++argv);
                    700:                } else if (strcmp(*argv, "-dkey") == 0) {
                    701:                        if (--argc < 1)
                    702:                                goto bad;
                    703:                        s_dkey_file = *(++argv);
                    704:                } else if (strcmp(*argv, "-nocert") == 0) {
                    705:                        nocert = 1;
                    706:                } else if (strcmp(*argv, "-CApath") == 0) {
                    707:                        if (--argc < 1)
                    708:                                goto bad;
                    709:                        CApath = *(++argv);
                    710:                } else if (strcmp(*argv, "-no_cache") == 0)
                    711:                        no_cache = 1;
                    712:                else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
                    713:                        if (badarg)
                    714:                                goto bad;
                    715:                        continue;
                    716:                } else if (strcmp(*argv, "-verify_return_error") == 0)
                    717:                        verify_return_error = 1;
                    718:                else if (strcmp(*argv, "-serverpref") == 0) {
                    719:                        off |= SSL_OP_CIPHER_SERVER_PREFERENCE;
                    720:                } else if (strcmp(*argv, "-legacy_renegotiation") == 0)
                    721:                        ; /* no-op */
                    722:                else if (strcmp(*argv, "-cipher") == 0) {
                    723:                        if (--argc < 1)
                    724:                                goto bad;
                    725:                        cipher = *(++argv);
                    726:                } else if (strcmp(*argv, "-CAfile") == 0) {
                    727:                        if (--argc < 1)
                    728:                                goto bad;
                    729:                        CAfile = *(++argv);
                    730:                }
                    731:                else if (strcmp(*argv, "-nbio") == 0) {
                    732:                        s_nbio = 1;
                    733:                }
                    734:                else if (strcmp(*argv, "-nbio_test") == 0) {
                    735:                        s_nbio = 1;
                    736:                        s_nbio_test = 1;
                    737:                } else if (strcmp(*argv, "-debug") == 0) {
                    738:                        s_debug = 1;
                    739:                }
                    740:                else if (strcmp(*argv, "-tlsextdebug") == 0)
                    741:                        s_tlsextdebug = 1;
                    742:                else if (strcmp(*argv, "-status") == 0)
                    743:                        s_tlsextstatus = 1;
                    744:                else if (strcmp(*argv, "-status_verbose") == 0) {
                    745:                        s_tlsextstatus = 1;
                    746:                        tlscstatp.verbose = 1;
                    747:                } else if (!strcmp(*argv, "-status_timeout")) {
                    748:                        s_tlsextstatus = 1;
                    749:                        if (--argc < 1)
                    750:                                goto bad;
                    751:                        tlscstatp.timeout = strtonum(*(++argv), 0, INT_MAX, &errstr);
                    752:                        if (errstr)
                    753:                                goto bad;
                    754:                } else if (!strcmp(*argv, "-status_url")) {
                    755:                        s_tlsextstatus = 1;
                    756:                        if (--argc < 1)
                    757:                                goto bad;
                    758:                        if (!OCSP_parse_url(*(++argv),
                    759:                                &tlscstatp.host,
                    760:                                &tlscstatp.port,
                    761:                                &tlscstatp.path,
                    762:                                &tlscstatp.use_ssl)) {
                    763:                                BIO_printf(bio_err, "Error parsing URL\n");
                    764:                                goto bad;
                    765:                        }
                    766:                }
                    767:                else if (strcmp(*argv, "-msg") == 0) {
                    768:                        s_msg = 1;
                    769:                } else if (strcmp(*argv, "-state") == 0) {
                    770:                        state = 1;
                    771:                } else if (strcmp(*argv, "-crlf") == 0) {
                    772:                        s_crlf = 1;
                    773:                } else if (strcmp(*argv, "-quiet") == 0) {
                    774:                        s_quiet = 1;
                    775:                } else if (strcmp(*argv, "-bugs") == 0) {
                    776:                        bugs = 1;
                    777:                } else if (strcmp(*argv, "-no_tmp_rsa") == 0) {
1.5       jsing     778:                        /* No-op. */
1.1       jsing     779:                } else if (strcmp(*argv, "-no_dhe") == 0) {
                    780:                        no_dhe = 1;
                    781:                } else if (strcmp(*argv, "-no_ecdhe") == 0) {
                    782:                        no_ecdhe = 1;
1.5       jsing     783:                } else if (strcmp(*argv, "-www") == 0) {
1.1       jsing     784:                        www = 1;
                    785:                } else if (strcmp(*argv, "-WWW") == 0) {
                    786:                        www = 2;
                    787:                } else if (strcmp(*argv, "-HTTP") == 0) {
                    788:                        www = 3;
                    789:                } else if (strcmp(*argv, "-no_ssl2") == 0) {
                    790:                        off |= SSL_OP_NO_SSLv2;
                    791:                } else if (strcmp(*argv, "-no_ssl3") == 0) {
                    792:                        off |= SSL_OP_NO_SSLv3;
                    793:                } else if (strcmp(*argv, "-no_tls1") == 0) {
                    794:                        off |= SSL_OP_NO_TLSv1;
                    795:                } else if (strcmp(*argv, "-no_tls1_1") == 0) {
                    796:                        off |= SSL_OP_NO_TLSv1_1;
                    797:                } else if (strcmp(*argv, "-no_tls1_2") == 0) {
                    798:                        off |= SSL_OP_NO_TLSv1_2;
                    799:                } else if (strcmp(*argv, "-no_comp") == 0) {
                    800:                        off |= SSL_OP_NO_COMPRESSION;
1.13      doug      801:                } else if (strcmp(*argv, "-no_ticket") == 0) {
1.1       jsing     802:                        off |= SSL_OP_NO_TICKET;
                    803:                } else if (strcmp(*argv, "-tls1") == 0) {
                    804:                        meth = TLSv1_server_method();
                    805:                } else if (strcmp(*argv, "-tls1_1") == 0) {
                    806:                        meth = TLSv1_1_server_method();
                    807:                } else if (strcmp(*argv, "-tls1_2") == 0) {
                    808:                        meth = TLSv1_2_server_method();
                    809:                }
                    810: #ifndef OPENSSL_NO_DTLS1
                    811:                else if (strcmp(*argv, "-dtls1") == 0) {
                    812:                        meth = DTLSv1_server_method();
                    813:                        socket_type = SOCK_DGRAM;
                    814:                } else if (strcmp(*argv, "-timeout") == 0)
                    815:                        enable_timeouts = 1;
                    816:                else if (strcmp(*argv, "-mtu") == 0) {
                    817:                        if (--argc < 1)
                    818:                                goto bad;
                    819:                        socket_mtu = strtonum(*(++argv), 0, LONG_MAX, &errstr);
                    820:                        if (errstr)
                    821:                                goto bad;
                    822:                } else if (strcmp(*argv, "-chain") == 0)
                    823:                        cert_chain = 1;
                    824: #endif
                    825:                else if (strcmp(*argv, "-id_prefix") == 0) {
                    826:                        if (--argc < 1)
                    827:                                goto bad;
                    828:                        session_id_prefix = *(++argv);
                    829:                }
                    830:                else if (strcmp(*argv, "-servername") == 0) {
                    831:                        if (--argc < 1)
                    832:                                goto bad;
                    833:                        tlsextcbp.servername = *(++argv);
                    834:                } else if (strcmp(*argv, "-servername_fatal") == 0) {
                    835:                        tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
                    836:                } else if (strcmp(*argv, "-cert2") == 0) {
                    837:                        if (--argc < 1)
                    838:                                goto bad;
                    839:                        s_cert_file2 = *(++argv);
                    840:                } else if (strcmp(*argv, "-key2") == 0) {
                    841:                        if (--argc < 1)
                    842:                                goto bad;
                    843:                        s_key_file2 = *(++argv);
                    844:                }
                    845:                else if (strcmp(*argv, "-nextprotoneg") == 0) {
                    846:                        if (--argc < 1)
                    847:                                goto bad;
                    848:                        next_proto_neg_in = *(++argv);
                    849:                }
1.8       jsing     850:                else if (strcmp(*argv,"-alpn") == 0) {
                    851:                        if (--argc < 1)
                    852:                                goto bad;
                    853:                        alpn_in = *(++argv);
                    854:                }
1.1       jsing     855: #ifndef OPENSSL_NO_SRTP
                    856:                else if (strcmp(*argv, "-use_srtp") == 0) {
                    857:                        if (--argc < 1)
                    858:                                goto bad;
                    859:                        srtp_profiles = *(++argv);
                    860:                }
                    861: #endif
                    862:                else if (strcmp(*argv, "-keymatexport") == 0) {
                    863:                        if (--argc < 1)
                    864:                                goto bad;
                    865:                        keymatexportlabel = *(++argv);
                    866:                } else if (strcmp(*argv, "-keymatexportlen") == 0) {
                    867:                        if (--argc < 1)
                    868:                                goto bad;
                    869:                        keymatexportlen = strtonum(*(++argv), 1, INT_MAX, &errstr);
                    870:                        if (errstr)
                    871:                                goto bad;
                    872:                } else {
                    873:                        BIO_printf(bio_err, "unknown option %s\n", *argv);
                    874:                        badop = 1;
                    875:                        break;
                    876:                }
                    877:                argc--;
                    878:                argv++;
                    879:        }
                    880:        if (badop) {
                    881: bad:
                    882:                if (errstr)
                    883:                        BIO_printf(bio_err, "invalid argument %s: %s\n",
                    884:                            *argv, errstr);
                    885:                else
                    886:                        sv_usage();
                    887:                goto end;
                    888:        }
                    889:
                    890:        if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass)) {
                    891:                BIO_printf(bio_err, "Error getting password\n");
                    892:                goto end;
                    893:        }
                    894:        if (s_key_file == NULL)
                    895:                s_key_file = s_cert_file;
                    896:        if (s_key_file2 == NULL)
                    897:                s_key_file2 = s_cert_file2;
                    898:
                    899:        if (nocert == 0) {
1.17      bcook     900:                s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass,
1.1       jsing     901:                    "server certificate private key file");
                    902:                if (!s_key) {
                    903:                        ERR_print_errors(bio_err);
                    904:                        goto end;
                    905:                }
                    906:                s_cert = load_cert(bio_err, s_cert_file, s_cert_format,
1.17      bcook     907:                    NULL, "server certificate file");
1.1       jsing     908:
                    909:                if (!s_cert) {
                    910:                        ERR_print_errors(bio_err);
                    911:                        goto end;
                    912:                }
                    913:                if (tlsextcbp.servername) {
1.17      bcook     914:                        s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass,
1.1       jsing     915:                            "second server certificate private key file");
                    916:                        if (!s_key2) {
                    917:                                ERR_print_errors(bio_err);
                    918:                                goto end;
                    919:                        }
                    920:                        s_cert2 = load_cert(bio_err, s_cert_file2, s_cert_format,
1.17      bcook     921:                            NULL, "second server certificate file");
1.1       jsing     922:
                    923:                        if (!s_cert2) {
                    924:                                ERR_print_errors(bio_err);
                    925:                                goto end;
                    926:                        }
                    927:                }
                    928:        }
                    929:        if (next_proto_neg_in) {
                    930:                unsigned short len;
                    931:                next_proto.data = next_protos_parse(&len, next_proto_neg_in);
                    932:                if (next_proto.data == NULL)
                    933:                        goto end;
                    934:                next_proto.len = len;
                    935:        } else {
                    936:                next_proto.data = NULL;
                    937:        }
1.8       jsing     938:        alpn_ctx.data = NULL;
                    939:        if (alpn_in) {
                    940:                unsigned short len;
                    941:                alpn_ctx.data = next_protos_parse(&len, alpn_in);
                    942:                if (alpn_ctx.data == NULL)
                    943:                        goto end;
                    944:                alpn_ctx.len = len;
                    945:        }
1.1       jsing     946:
                    947:        if (s_dcert_file) {
                    948:
                    949:                if (s_dkey_file == NULL)
                    950:                        s_dkey_file = s_dcert_file;
                    951:
                    952:                s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
1.17      bcook     953:                    0, dpass, "second certificate private key file");
1.1       jsing     954:                if (!s_dkey) {
                    955:                        ERR_print_errors(bio_err);
                    956:                        goto end;
                    957:                }
                    958:                s_dcert = load_cert(bio_err, s_dcert_file, s_dcert_format,
1.17      bcook     959:                    NULL, "second server certificate file");
1.1       jsing     960:
                    961:                if (!s_dcert) {
                    962:                        ERR_print_errors(bio_err);
                    963:                        goto end;
                    964:                }
                    965:        }
                    966:        if (bio_s_out == NULL) {
                    967:                if (s_quiet && !s_debug && !s_msg) {
                    968:                        bio_s_out = BIO_new(BIO_s_null());
                    969:                } else {
                    970:                        if (bio_s_out == NULL)
                    971:                                bio_s_out = BIO_new_fp(stdout, BIO_NOCLOSE);
                    972:                }
                    973:        }
1.8       jsing     974:        if (nocert) {
1.1       jsing     975:                s_cert_file = NULL;
                    976:                s_key_file = NULL;
                    977:                s_dcert_file = NULL;
                    978:                s_dkey_file = NULL;
                    979:                s_cert_file2 = NULL;
                    980:                s_key_file2 = NULL;
                    981:        }
                    982:        ctx = SSL_CTX_new(meth);
                    983:        if (ctx == NULL) {
                    984:                ERR_print_errors(bio_err);
                    985:                goto end;
                    986:        }
                    987:        if (session_id_prefix) {
                    988:                if (strlen(session_id_prefix) >= 32)
                    989:                        BIO_printf(bio_err,
                    990:                            "warning: id_prefix is too long, only one new session will be possible\n");
                    991:                else if (strlen(session_id_prefix) >= 16)
                    992:                        BIO_printf(bio_err,
                    993:                            "warning: id_prefix is too long if you use SSLv2\n");
                    994:                if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
                    995:                        BIO_printf(bio_err, "error setting 'id_prefix'\n");
                    996:                        ERR_print_errors(bio_err);
                    997:                        goto end;
                    998:                }
                    999:                BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
                   1000:        }
                   1001:        SSL_CTX_set_quiet_shutdown(ctx, 1);
                   1002:        if (bugs)
                   1003:                SSL_CTX_set_options(ctx, SSL_OP_ALL);
                   1004:        SSL_CTX_set_options(ctx, off);
                   1005:        /*
                   1006:         * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
                   1007:         * read ahead solves this problem.
                   1008:         */
                   1009:        if (socket_type == SOCK_DGRAM)
                   1010:                SSL_CTX_set_read_ahead(ctx, 1);
                   1011:
                   1012:        if (state)
                   1013:                SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
                   1014:        if (no_cache)
                   1015:                SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
                   1016:        else
                   1017:                SSL_CTX_sess_set_cache_size(ctx, 128);
                   1018:
                   1019: #ifndef OPENSSL_NO_SRTP
                   1020:        if (srtp_profiles != NULL)
                   1021:                SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
                   1022: #endif
                   1023:
                   1024:
                   1025:        if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) ||
                   1026:            (!SSL_CTX_set_default_verify_paths(ctx))) {
                   1027:                /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
                   1028:                ERR_print_errors(bio_err);
                   1029:                /* goto end; */
                   1030:        }
                   1031:        if (vpm)
                   1032:                SSL_CTX_set1_param(ctx, vpm);
                   1033:
                   1034:        if (s_cert2) {
                   1035:                ctx2 = SSL_CTX_new(meth);
                   1036:                if (ctx2 == NULL) {
                   1037:                        ERR_print_errors(bio_err);
                   1038:                        goto end;
                   1039:                }
                   1040:        }
                   1041:        if (ctx2) {
                   1042:                BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
                   1043:
                   1044:                if (session_id_prefix) {
                   1045:                        if (strlen(session_id_prefix) >= 32)
                   1046:                                BIO_printf(bio_err,
                   1047:                                    "warning: id_prefix is too long, only one new session will be possible\n");
                   1048:                        else if (strlen(session_id_prefix) >= 16)
                   1049:                                BIO_printf(bio_err,
                   1050:                                    "warning: id_prefix is too long if you use SSLv2\n");
                   1051:                        if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
                   1052:                                BIO_printf(bio_err, "error setting 'id_prefix'\n");
                   1053:                                ERR_print_errors(bio_err);
                   1054:                                goto end;
                   1055:                        }
                   1056:                        BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
                   1057:                }
                   1058:                SSL_CTX_set_quiet_shutdown(ctx2, 1);
                   1059:                if (bugs)
                   1060:                        SSL_CTX_set_options(ctx2, SSL_OP_ALL);
                   1061:                SSL_CTX_set_options(ctx2, off);
                   1062:                /*
                   1063:                 * DTLS: partial reads end up discarding unread UDP bytes :-(
                   1064:                 * Setting read ahead solves this problem.
                   1065:                 */
                   1066:                if (socket_type == SOCK_DGRAM)
                   1067:                        SSL_CTX_set_read_ahead(ctx2, 1);
                   1068:
                   1069:                if (state)
                   1070:                        SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
                   1071:
                   1072:                if (no_cache)
                   1073:                        SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
                   1074:                else
                   1075:                        SSL_CTX_sess_set_cache_size(ctx2, 128);
                   1076:
                   1077:                if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) ||
                   1078:                    (!SSL_CTX_set_default_verify_paths(ctx2))) {
                   1079:                        ERR_print_errors(bio_err);
                   1080:                }
                   1081:                if (vpm)
                   1082:                        SSL_CTX_set1_param(ctx2, vpm);
                   1083:        }
                   1084:        if (next_proto.data)
                   1085:                SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto);
1.8       jsing    1086:        if (alpn_ctx.data)
                   1087:                SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1.1       jsing    1088:
                   1089: #ifndef OPENSSL_NO_DH
                   1090:        if (!no_dhe) {
                   1091:                DH *dh = NULL;
                   1092:
                   1093:                if (dhfile)
                   1094:                        dh = load_dh_param(dhfile);
                   1095:                else if (s_cert_file)
                   1096:                        dh = load_dh_param(s_cert_file);
                   1097:
1.4       jsing    1098:                if (dh != NULL)
1.1       jsing    1099:                        BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1.4       jsing    1100:                else
                   1101:                        BIO_printf(bio_s_out, "Using auto DH parameters\n");
                   1102:                (void) BIO_flush(bio_s_out);
                   1103:
                   1104:                if (dh == NULL)
                   1105:                        SSL_CTX_set_dh_auto(ctx, 1);
                   1106:                else if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
                   1107:                        BIO_printf(bio_err,
                   1108:                            "Error setting temp DH parameters\n");
                   1109:                        ERR_print_errors(bio_err);
                   1110:                        DH_free(dh);
                   1111:                        goto end;
1.1       jsing    1112:                }
                   1113:
                   1114:                if (ctx2) {
                   1115:                        if (!dhfile) {
1.14      doug     1116:                                DH *dh2 = NULL;
                   1117:
                   1118:                                if (s_cert_file2 != NULL)
                   1119:                                        dh2 = load_dh_param(s_cert_file2);
1.1       jsing    1120:                                if (dh2 != NULL) {
                   1121:                                        BIO_printf(bio_s_out, "Setting temp DH parameters\n");
                   1122:                                        (void) BIO_flush(bio_s_out);
                   1123:
                   1124:                                        DH_free(dh);
                   1125:                                        dh = dh2;
                   1126:                                }
                   1127:                        }
1.4       jsing    1128:                        if (dh == NULL)
                   1129:                                SSL_CTX_set_dh_auto(ctx2, 1);
                   1130:                        else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) {
                   1131:                                BIO_printf(bio_err,
                   1132:                                    "Error setting temp DH parameters\n");
                   1133:                                ERR_print_errors(bio_err);
                   1134:                                DH_free(dh);
                   1135:                                goto end;
                   1136:                        }
1.1       jsing    1137:                }
                   1138:                DH_free(dh);
                   1139:        }
                   1140: #endif
                   1141:
                   1142:        if (!no_ecdhe) {
                   1143:                EC_KEY *ecdh = NULL;
                   1144:
                   1145:                if (named_curve) {
                   1146:                        int nid = OBJ_sn2nid(named_curve);
                   1147:
                   1148:                        if (nid == 0) {
                   1149:                                BIO_printf(bio_err, "unknown curve name (%s)\n",
                   1150:                                    named_curve);
                   1151:                                goto end;
                   1152:                        }
                   1153:                        ecdh = EC_KEY_new_by_curve_name(nid);
                   1154:                        if (ecdh == NULL) {
                   1155:                                BIO_printf(bio_err, "unable to create curve (%s)\n",
                   1156:                                    named_curve);
                   1157:                                goto end;
                   1158:                        }
                   1159:                }
                   1160:                if (ecdh != NULL) {
                   1161:                        BIO_printf(bio_s_out, "Setting temp ECDH parameters\n");
                   1162:                } else {
                   1163:                        BIO_printf(bio_s_out, "Using default temp ECDH parameters\n");
                   1164:                        ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
                   1165:                        if (ecdh == NULL) {
                   1166:                                BIO_printf(bio_err, "unable to create curve (nistp256)\n");
                   1167:                                goto end;
                   1168:                        }
                   1169:                }
                   1170:                (void) BIO_flush(bio_s_out);
                   1171:
                   1172:                SSL_CTX_set_tmp_ecdh(ctx, ecdh);
                   1173:                if (ctx2)
                   1174:                        SSL_CTX_set_tmp_ecdh(ctx2, ecdh);
                   1175:                EC_KEY_free(ecdh);
                   1176:        }
                   1177:
                   1178:        if (!set_cert_key_stuff(ctx, s_cert, s_key))
                   1179:                goto end;
                   1180:        if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2))
                   1181:                goto end;
                   1182:        if (s_dcert != NULL) {
                   1183:                if (!set_cert_key_stuff(ctx, s_dcert, s_dkey))
                   1184:                        goto end;
                   1185:        }
                   1186:
                   1187:        if (cipher != NULL) {
                   1188:                if (!SSL_CTX_set_cipher_list(ctx, cipher)) {
                   1189:                        BIO_printf(bio_err, "error setting cipher list\n");
                   1190:                        ERR_print_errors(bio_err);
                   1191:                        goto end;
                   1192:                }
                   1193:                if (ctx2 && !SSL_CTX_set_cipher_list(ctx2, cipher)) {
                   1194:                        BIO_printf(bio_err, "error setting cipher list\n");
                   1195:                        ERR_print_errors(bio_err);
                   1196:                        goto end;
                   1197:                }
                   1198:        }
                   1199:        SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
                   1200:        SSL_CTX_set_session_id_context(ctx, (void *) &s_server_session_id_context,
                   1201:            sizeof s_server_session_id_context);
                   1202:
                   1203:        /* Set DTLS cookie generation and verification callbacks */
                   1204:        SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
                   1205:        SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
                   1206:
                   1207:        if (ctx2) {
                   1208:                SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
                   1209:                SSL_CTX_set_session_id_context(ctx2, (void *) &s_server_session_id_context,
                   1210:                    sizeof s_server_session_id_context);
                   1211:
                   1212:                tlsextcbp.biodebug = bio_s_out;
                   1213:                SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
                   1214:                SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
                   1215:                SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
                   1216:                SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
                   1217:        }
                   1218:
                   1219:        if (CAfile != NULL) {
                   1220:                SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
                   1221:                if (ctx2)
                   1222:                        SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
                   1223:        }
                   1224:        BIO_printf(bio_s_out, "ACCEPT\n");
                   1225:        (void) BIO_flush(bio_s_out);
                   1226:        if (www)
                   1227:                do_server(port, socket_type, &accept_socket, www_body, context);
                   1228:        else
                   1229:                do_server(port, socket_type, &accept_socket, sv_body, context);
                   1230:        print_stats(bio_s_out, ctx);
                   1231:        ret = 0;
                   1232: end:
                   1233:        if (ctx != NULL)
                   1234:                SSL_CTX_free(ctx);
                   1235:        if (s_cert)
                   1236:                X509_free(s_cert);
                   1237:        if (s_dcert)
                   1238:                X509_free(s_dcert);
                   1239:        if (s_key)
                   1240:                EVP_PKEY_free(s_key);
                   1241:        if (s_dkey)
                   1242:                EVP_PKEY_free(s_dkey);
                   1243:        free(pass);
                   1244:        free(dpass);
                   1245:        if (vpm)
                   1246:                X509_VERIFY_PARAM_free(vpm);
                   1247:        free(tlscstatp.host);
                   1248:        free(tlscstatp.port);
                   1249:        free(tlscstatp.path);
                   1250:        if (ctx2 != NULL)
                   1251:                SSL_CTX_free(ctx2);
                   1252:        if (s_cert2)
                   1253:                X509_free(s_cert2);
                   1254:        if (s_key2)
                   1255:                EVP_PKEY_free(s_key2);
1.8       jsing    1256:        free(next_proto.data);
                   1257:        free(alpn_ctx.data);
1.1       jsing    1258:        if (bio_s_out != NULL) {
                   1259:                BIO_free(bio_s_out);
                   1260:                bio_s_out = NULL;
                   1261:        }
                   1262:
                   1263:        return (ret);
                   1264: }
                   1265:
                   1266: static void
                   1267: print_stats(BIO * bio, SSL_CTX * ssl_ctx)
                   1268: {
                   1269:        BIO_printf(bio, "%4ld items in the session cache\n",
                   1270:            SSL_CTX_sess_number(ssl_ctx));
                   1271:        BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
                   1272:            SSL_CTX_sess_connect(ssl_ctx));
                   1273:        BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
                   1274:            SSL_CTX_sess_connect_renegotiate(ssl_ctx));
                   1275:        BIO_printf(bio, "%4ld client connects that finished\n",
                   1276:            SSL_CTX_sess_connect_good(ssl_ctx));
                   1277:        BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
                   1278:            SSL_CTX_sess_accept(ssl_ctx));
                   1279:        BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
                   1280:            SSL_CTX_sess_accept_renegotiate(ssl_ctx));
                   1281:        BIO_printf(bio, "%4ld server accepts that finished\n",
                   1282:            SSL_CTX_sess_accept_good(ssl_ctx));
                   1283:        BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
                   1284:        BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx));
                   1285:        BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx));
                   1286:        BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx));
                   1287:        BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
                   1288:            SSL_CTX_sess_cache_full(ssl_ctx),
                   1289:            SSL_CTX_sess_get_cache_size(ssl_ctx));
                   1290: }
                   1291:
                   1292: static int
                   1293: sv_body(char *hostname, int s, unsigned char *context)
                   1294: {
                   1295:        char *buf = NULL;
1.7       deraadt  1296:        int ret = 1;
1.1       jsing    1297:        int k, i;
                   1298:        unsigned long l;
                   1299:        SSL *con = NULL;
                   1300:        BIO *sbio;
                   1301:        struct timeval timeout;
                   1302:
                   1303:        if ((buf = malloc(bufsize)) == NULL) {
                   1304:                BIO_printf(bio_err, "out of memory\n");
                   1305:                goto err;
                   1306:        }
                   1307:        if (s_nbio) {
                   1308:                if (!s_quiet)
                   1309:                        BIO_printf(bio_err, "turning on non blocking io\n");
1.2       bcook    1310:                if (!BIO_socket_nbio(s, 1))
1.1       jsing    1311:                        ERR_print_errors(bio_err);
                   1312:        }
                   1313:
                   1314:        if (con == NULL) {
                   1315:                con = SSL_new(ctx);
                   1316:                if (s_tlsextdebug) {
                   1317:                        SSL_set_tlsext_debug_callback(con, tlsext_cb);
                   1318:                        SSL_set_tlsext_debug_arg(con, bio_s_out);
                   1319:                }
                   1320:                if (s_tlsextstatus) {
                   1321:                        SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
                   1322:                        tlscstatp.err = bio_err;
                   1323:                        SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
                   1324:                }
                   1325:                if (context)
                   1326:                        SSL_set_session_id_context(con, context,
                   1327:                            strlen((char *) context));
                   1328:        }
                   1329:        SSL_clear(con);
                   1330:
                   1331:        if (SSL_version(con) == DTLS1_VERSION) {
                   1332:
                   1333:                sbio = BIO_new_dgram(s, BIO_NOCLOSE);
                   1334:
                   1335:                if (enable_timeouts) {
                   1336:                        timeout.tv_sec = 0;
                   1337:                        timeout.tv_usec = DGRAM_RCV_TIMEOUT;
                   1338:                        BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
                   1339:
                   1340:                        timeout.tv_sec = 0;
                   1341:                        timeout.tv_usec = DGRAM_SND_TIMEOUT;
                   1342:                        BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
                   1343:                }
                   1344:                if (socket_mtu > 28) {
                   1345:                        SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
                   1346:                        SSL_set_mtu(con, socket_mtu - 28);
                   1347:                } else
                   1348:                        /* want to do MTU discovery */
                   1349:                        BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
                   1350:
                   1351:                /* turn on cookie exchange */
                   1352:                SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
                   1353:        } else
                   1354:                sbio = BIO_new_socket(s, BIO_NOCLOSE);
                   1355:
                   1356:        if (s_nbio_test) {
                   1357:                BIO *test;
                   1358:
                   1359:                test = BIO_new(BIO_f_nbio_test());
                   1360:                sbio = BIO_push(test, sbio);
                   1361:        }
                   1362:
                   1363:        SSL_set_bio(con, sbio, sbio);
                   1364:        SSL_set_accept_state(con);
                   1365:        /* SSL_set_fd(con,s); */
                   1366:
                   1367:        if (s_debug) {
                   1368:                SSL_set_debug(con, 1);
                   1369:                BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
                   1370:                BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
                   1371:        }
                   1372:        if (s_msg) {
                   1373:                SSL_set_msg_callback(con, msg_cb);
                   1374:                SSL_set_msg_callback_arg(con, bio_s_out);
                   1375:        }
                   1376:        if (s_tlsextdebug) {
                   1377:                SSL_set_tlsext_debug_callback(con, tlsext_cb);
                   1378:                SSL_set_tlsext_debug_arg(con, bio_s_out);
                   1379:        }
                   1380:
                   1381:        for (;;) {
                   1382:                int read_from_terminal;
                   1383:                int read_from_sslcon;
1.7       deraadt  1384:                struct pollfd pfd[2];
                   1385:                int ptimeout;
1.1       jsing    1386:
                   1387:                read_from_terminal = 0;
                   1388:                read_from_sslcon = SSL_pending(con);
                   1389:
                   1390:                if (!read_from_sslcon) {
1.7       deraadt  1391:                        pfd[0].fd = fileno(stdin);
                   1392:                        pfd[0].events = POLLIN;
                   1393:                        pfd[1].fd = s;
                   1394:                        pfd[1].events = POLLIN;
                   1395:
1.1       jsing    1396:                        if ((SSL_version(con) == DTLS1_VERSION) &&
                   1397:                            DTLSv1_get_timeout(con, &timeout))
1.7       deraadt  1398:                                ptimeout = timeout.tv_sec * 1000 +
                   1399:                                    timeout.tv_usec / 1000;
1.1       jsing    1400:                        else
1.7       deraadt  1401:                                ptimeout = -1;
1.1       jsing    1402:
1.7       deraadt  1403:                        i = poll(pfd, 2, ptimeout);
1.1       jsing    1404:
                   1405:                        if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) {
                   1406:                                BIO_printf(bio_err, "TIMEOUT occured\n");
                   1407:                        }
                   1408:                        if (i <= 0)
                   1409:                                continue;
1.7       deraadt  1410:                        if (pfd[0].revents) {
                   1411:                                if ((pfd[0].revents & (POLLERR|POLLNVAL)))
                   1412:                                        continue;
1.1       jsing    1413:                                read_from_terminal = 1;
1.7       deraadt  1414:                        }
                   1415:                        if (pfd[1].revents) {
                   1416:                                if ((pfd[1].revents & (POLLERR|POLLNVAL)))
                   1417:                                        continue;
1.1       jsing    1418:                                read_from_sslcon = 1;
1.7       deraadt  1419:                        }
1.1       jsing    1420:                }
                   1421:                if (read_from_terminal) {
                   1422:                        if (s_crlf) {
                   1423:                                int j, lf_num;
                   1424:
                   1425:                                i = read(fileno(stdin), buf, bufsize / 2);
                   1426:                                lf_num = 0;
                   1427:                                /* both loops are skipped when i <= 0 */
                   1428:                                for (j = 0; j < i; j++)
                   1429:                                        if (buf[j] == '\n')
                   1430:                                                lf_num++;
                   1431:                                for (j = i - 1; j >= 0; j--) {
                   1432:                                        buf[j + lf_num] = buf[j];
                   1433:                                        if (buf[j] == '\n') {
                   1434:                                                lf_num--;
                   1435:                                                i++;
                   1436:                                                buf[j + lf_num] = '\r';
                   1437:                                        }
                   1438:                                }
                   1439:                                assert(lf_num == 0);
                   1440:                        } else
                   1441:                                i = read(fileno(stdin), buf, bufsize);
                   1442:                        if (!s_quiet) {
                   1443:                                if ((i <= 0) || (buf[0] == 'Q')) {
                   1444:                                        BIO_printf(bio_s_out, "DONE\n");
                   1445:                                        shutdown(s, SHUT_RD);
                   1446:                                        close(s);
                   1447:                                        close_accept_socket();
                   1448:                                        ret = -11;
                   1449:                                        goto err;
                   1450:                                }
                   1451:                                if ((i <= 0) || (buf[0] == 'q')) {
                   1452:                                        BIO_printf(bio_s_out, "DONE\n");
                   1453:                                        if (SSL_version(con) != DTLS1_VERSION) {
                   1454:                                                shutdown(s, SHUT_RD);
                   1455:                                                close(s);
                   1456:                                        }
                   1457:                                        /*
                   1458:                                         * close_accept_socket(); ret= -11;
                   1459:                                         */
                   1460:                                        goto err;
                   1461:                                }
                   1462:                                if ((buf[0] == 'r') &&
                   1463:                                    ((buf[1] == '\n') || (buf[1] == '\r'))) {
                   1464:                                        SSL_renegotiate(con);
                   1465:                                        i = SSL_do_handshake(con);
                   1466:                                        printf("SSL_do_handshake -> %d\n", i);
                   1467:                                        i = 0;  /* 13; */
                   1468:                                        continue;
                   1469:                                        /*
                   1470:                                         * RE-NEGOTIATE\n");
                   1471:                                         */
                   1472:                                }
                   1473:                                if ((buf[0] == 'R') &&
                   1474:                                    ((buf[1] == '\n') || (buf[1] == '\r'))) {
                   1475:                                        SSL_set_verify(con,
                   1476:                                            SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
                   1477:                                        SSL_renegotiate(con);
                   1478:                                        i = SSL_do_handshake(con);
                   1479:                                        printf("SSL_do_handshake -> %d\n", i);
                   1480:                                        i = 0;  /* 13; */
                   1481:                                        continue;
                   1482:                                        /*
                   1483:                                         * RE-NEGOTIATE asking for client
                   1484:                                         * cert\n");
                   1485:                                         */
                   1486:                                }
                   1487:                                if (buf[0] == 'P') {
                   1488:                                        static const char *str = "Lets print some clear text\n";
                   1489:                                        BIO_write(SSL_get_wbio(con), str, strlen(str));
                   1490:                                }
                   1491:                                if (buf[0] == 'S') {
                   1492:                                        print_stats(bio_s_out, SSL_get_SSL_CTX(con));
                   1493:                                }
                   1494:                        }
                   1495:                        l = k = 0;
                   1496:                        for (;;) {
                   1497:                                /* should do a select for the write */
                   1498: #ifdef RENEG
                   1499:                                {
                   1500:                                        static count = 0;
                   1501:                                        if (++count == 100) {
                   1502:                                                count = 0;
                   1503:                                                SSL_renegotiate(con);
                   1504:                                        }
                   1505:                                }
                   1506: #endif
                   1507:                                k = SSL_write(con, &(buf[l]), (unsigned int) i);
                   1508:                                switch (SSL_get_error(con, k)) {
                   1509:                                case SSL_ERROR_NONE:
                   1510:                                        break;
                   1511:                                case SSL_ERROR_WANT_WRITE:
                   1512:                                case SSL_ERROR_WANT_READ:
                   1513:                                case SSL_ERROR_WANT_X509_LOOKUP:
                   1514:                                        BIO_printf(bio_s_out, "Write BLOCK\n");
                   1515:                                        break;
                   1516:                                case SSL_ERROR_SYSCALL:
                   1517:                                case SSL_ERROR_SSL:
                   1518:                                        BIO_printf(bio_s_out, "ERROR\n");
                   1519:                                        ERR_print_errors(bio_err);
                   1520:                                        ret = 1;
                   1521:                                        goto err;
                   1522:                                        /* break; */
                   1523:                                case SSL_ERROR_ZERO_RETURN:
                   1524:                                        BIO_printf(bio_s_out, "DONE\n");
                   1525:                                        ret = 1;
                   1526:                                        goto err;
                   1527:                                }
                   1528:                                l += k;
                   1529:                                i -= k;
                   1530:                                if (i <= 0)
                   1531:                                        break;
                   1532:                        }
                   1533:                }
                   1534:                if (read_from_sslcon) {
                   1535:                        if (!SSL_is_init_finished(con)) {
                   1536:                                i = init_ssl_connection(con);
                   1537:
                   1538:                                if (i < 0) {
                   1539:                                        ret = 0;
                   1540:                                        goto err;
                   1541:                                } else if (i == 0) {
                   1542:                                        ret = 1;
                   1543:                                        goto err;
                   1544:                                }
                   1545:                        } else {
                   1546:                again:
                   1547:                                i = SSL_read(con, (char *) buf, bufsize);
                   1548:                                switch (SSL_get_error(con, i)) {
                   1549:                                case SSL_ERROR_NONE: {
                   1550:                                                int len, n;
                   1551:                                                for (len = 0; len < i;) {
                   1552:                                                        do {
                   1553:                                                                n = write(fileno(stdout), buf + len, i - len);
                   1554:                                                        } while (n == -1 && errno == EINTR);
                   1555:
                   1556:                                                        if (n < 0) {
                   1557:                                                                BIO_printf(bio_s_out, "ERROR\n");
                   1558:                                                                goto err;
                   1559:                                                        }
                   1560:                                                        len += n;
                   1561:                                                }
                   1562:                                        }
                   1563:                                        if (SSL_pending(con))
                   1564:                                                goto again;
                   1565:                                        break;
                   1566:                                case SSL_ERROR_WANT_WRITE:
                   1567:                                case SSL_ERROR_WANT_READ:
                   1568:                                        BIO_printf(bio_s_out, "Read BLOCK\n");
                   1569:                                        break;
                   1570:                                case SSL_ERROR_SYSCALL:
                   1571:                                case SSL_ERROR_SSL:
                   1572:                                        BIO_printf(bio_s_out, "ERROR\n");
                   1573:                                        ERR_print_errors(bio_err);
                   1574:                                        ret = 1;
                   1575:                                        goto err;
                   1576:                                case SSL_ERROR_ZERO_RETURN:
                   1577:                                        BIO_printf(bio_s_out, "DONE\n");
                   1578:                                        ret = 1;
                   1579:                                        goto err;
                   1580:                                }
                   1581:                        }
                   1582:                }
                   1583:        }
                   1584: err:
                   1585:        if (con != NULL) {
                   1586:                BIO_printf(bio_s_out, "shutting down SSL\n");
                   1587:                SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
                   1588:                SSL_free(con);
                   1589:        }
                   1590:        BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
                   1591:        if (buf != NULL) {
1.16      jsing    1592:                explicit_bzero(buf, bufsize);
1.1       jsing    1593:                free(buf);
                   1594:        }
                   1595:        if (ret >= 0)
                   1596:                BIO_printf(bio_s_out, "ACCEPT\n");
                   1597:        return (ret);
                   1598: }
                   1599:
                   1600: static void
                   1601: close_accept_socket(void)
                   1602: {
                   1603:        BIO_printf(bio_err, "shutdown accept socket\n");
                   1604:        if (accept_socket >= 0) {
                   1605:                shutdown(accept_socket, SHUT_RDWR);
                   1606:                close(accept_socket);
                   1607:        }
                   1608: }
                   1609:
                   1610: static int
                   1611: init_ssl_connection(SSL * con)
                   1612: {
                   1613:        int i;
                   1614:        const char *str;
                   1615:        X509 *peer;
                   1616:        long verify_error;
                   1617:        char buf[BUFSIZ];
                   1618:        const unsigned char *next_proto_neg;
                   1619:        unsigned next_proto_neg_len;
                   1620:        unsigned char *exportedkeymat;
                   1621:
                   1622:        i = SSL_accept(con);
                   1623:        if (i <= 0) {
                   1624:                if (BIO_sock_should_retry(i)) {
                   1625:                        BIO_printf(bio_s_out, "DELAY\n");
                   1626:                        return (1);
                   1627:                }
                   1628:                BIO_printf(bio_err, "ERROR\n");
                   1629:                verify_error = SSL_get_verify_result(con);
                   1630:                if (verify_error != X509_V_OK) {
                   1631:                        BIO_printf(bio_err, "verify error:%s\n",
                   1632:                            X509_verify_cert_error_string(verify_error));
                   1633:                } else
                   1634:                        ERR_print_errors(bio_err);
                   1635:                return (0);
                   1636:        }
                   1637:        PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
                   1638:
                   1639:        peer = SSL_get_peer_certificate(con);
                   1640:        if (peer != NULL) {
                   1641:                BIO_printf(bio_s_out, "Client certificate\n");
                   1642:                PEM_write_bio_X509(bio_s_out, peer);
                   1643:                X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
                   1644:                BIO_printf(bio_s_out, "subject=%s\n", buf);
                   1645:                X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
                   1646:                BIO_printf(bio_s_out, "issuer=%s\n", buf);
                   1647:                X509_free(peer);
                   1648:        }
                   1649:        if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
                   1650:                BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
                   1651:        str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
                   1652:        BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
                   1653:
                   1654:        SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
                   1655:        if (next_proto_neg) {
                   1656:                BIO_printf(bio_s_out, "NEXTPROTO is ");
                   1657:                BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
                   1658:                BIO_printf(bio_s_out, "\n");
                   1659:        }
                   1660: #ifndef OPENSSL_NO_SRTP
                   1661:        {
                   1662:                SRTP_PROTECTION_PROFILE *srtp_profile
                   1663:                = SSL_get_selected_srtp_profile(con);
                   1664:
                   1665:                if (srtp_profile)
                   1666:                        BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
                   1667:                            srtp_profile->name);
                   1668:        }
                   1669: #endif
                   1670:        if (SSL_cache_hit(con))
                   1671:                BIO_printf(bio_s_out, "Reused session-id\n");
                   1672:        BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
                   1673:            SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
                   1674:        if (keymatexportlabel != NULL) {
                   1675:                BIO_printf(bio_s_out, "Keying material exporter:\n");
                   1676:                BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
                   1677:                BIO_printf(bio_s_out, "    Length: %i bytes\n",
                   1678:                    keymatexportlen);
                   1679:                exportedkeymat = malloc(keymatexportlen);
                   1680:                if (exportedkeymat != NULL) {
                   1681:                        if (!SSL_export_keying_material(con, exportedkeymat,
                   1682:                                keymatexportlen,
                   1683:                                keymatexportlabel,
                   1684:                                strlen(keymatexportlabel),
                   1685:                                NULL, 0, 0)) {
                   1686:                                BIO_printf(bio_s_out, "    Error\n");
                   1687:                        } else {
                   1688:                                BIO_printf(bio_s_out, "    Keying material: ");
                   1689:                                for (i = 0; i < keymatexportlen; i++)
                   1690:                                        BIO_printf(bio_s_out, "%02X",
                   1691:                                            exportedkeymat[i]);
                   1692:                                BIO_printf(bio_s_out, "\n");
                   1693:                        }
                   1694:                        free(exportedkeymat);
                   1695:                }
                   1696:        }
                   1697:        return (1);
                   1698: }
                   1699:
                   1700: #ifndef OPENSSL_NO_DH
                   1701: static DH *
                   1702: load_dh_param(const char *dhfile)
                   1703: {
                   1704:        DH *ret = NULL;
                   1705:        BIO *bio;
                   1706:
                   1707:        if ((bio = BIO_new_file(dhfile, "r")) == NULL)
                   1708:                goto err;
                   1709:        ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
                   1710: err:
                   1711:        BIO_free(bio);
                   1712:        return (ret);
                   1713: }
                   1714: #endif
                   1715:
                   1716: static int
                   1717: www_body(char *hostname, int s, unsigned char *context)
                   1718: {
                   1719:        char *buf = NULL;
                   1720:        int ret = 1;
                   1721:        int i, j, k, dot;
                   1722:        SSL *con;
                   1723:        const SSL_CIPHER *c;
                   1724:        BIO *io, *ssl_bio, *sbio;
                   1725:
                   1726:        buf = malloc(bufsize);
                   1727:        if (buf == NULL)
                   1728:                return (0);
                   1729:        io = BIO_new(BIO_f_buffer());
                   1730:        ssl_bio = BIO_new(BIO_f_ssl());
                   1731:        if ((io == NULL) || (ssl_bio == NULL))
                   1732:                goto err;
                   1733:
                   1734:        if (s_nbio) {
                   1735:                if (!s_quiet)
                   1736:                        BIO_printf(bio_err, "turning on non blocking io\n");
1.2       bcook    1737:                if (!BIO_socket_nbio(s, 1))
1.1       jsing    1738:                        ERR_print_errors(bio_err);
                   1739:        }
                   1740:
                   1741:        /* lets make the output buffer a reasonable size */
                   1742:        if (!BIO_set_write_buffer_size(io, bufsize))
                   1743:                goto err;
                   1744:
                   1745:        if ((con = SSL_new(ctx)) == NULL)
                   1746:                goto err;
                   1747:        if (s_tlsextdebug) {
                   1748:                SSL_set_tlsext_debug_callback(con, tlsext_cb);
                   1749:                SSL_set_tlsext_debug_arg(con, bio_s_out);
                   1750:        }
                   1751:        if (context)
                   1752:                SSL_set_session_id_context(con, context,
                   1753:                    strlen((char *) context));
                   1754:
                   1755:        sbio = BIO_new_socket(s, BIO_NOCLOSE);
                   1756:        if (s_nbio_test) {
                   1757:                BIO *test;
                   1758:
                   1759:                test = BIO_new(BIO_f_nbio_test());
                   1760:                sbio = BIO_push(test, sbio);
                   1761:        }
                   1762:        SSL_set_bio(con, sbio, sbio);
                   1763:        SSL_set_accept_state(con);
                   1764:
                   1765:        /* SSL_set_fd(con,s); */
                   1766:        BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
                   1767:        BIO_push(io, ssl_bio);
                   1768:
                   1769:        if (s_debug) {
                   1770:                SSL_set_debug(con, 1);
                   1771:                BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
                   1772:                BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
                   1773:        }
                   1774:        if (s_msg) {
                   1775:                SSL_set_msg_callback(con, msg_cb);
                   1776:                SSL_set_msg_callback_arg(con, bio_s_out);
                   1777:        }
                   1778:        for (;;) {
                   1779:                i = BIO_gets(io, buf, bufsize - 1);
                   1780:                if (i < 0) {    /* error */
                   1781:                        if (!BIO_should_retry(io)) {
                   1782:                                if (!s_quiet)
                   1783:                                        ERR_print_errors(bio_err);
                   1784:                                goto err;
                   1785:                        } else {
                   1786:                                BIO_printf(bio_s_out, "read R BLOCK\n");
                   1787:                                sleep(1);
                   1788:                                continue;
                   1789:                        }
                   1790:                } else if (i == 0) {    /* end of input */
                   1791:                        ret = 1;
                   1792:                        goto end;
                   1793:                }
                   1794:                /* else we have data */
                   1795:                if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
                   1796:                    ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
                   1797:                        char *p;
                   1798:                        X509 *peer;
                   1799:                        STACK_OF(SSL_CIPHER) * sk;
                   1800:                        static const char *space = "                          ";
                   1801:
                   1802:                        BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
                   1803:                        BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
                   1804:                        BIO_puts(io, "<pre>\n");
                   1805: /*                     BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
                   1806:                        BIO_puts(io, "\n");
                   1807:                        for (i = 0; i < local_argc; i++) {
                   1808:                                BIO_puts(io, local_argv[i]);
                   1809:                                BIO_write(io, " ", 1);
                   1810:                        }
                   1811:                        BIO_puts(io, "\n");
                   1812:
                   1813:                        BIO_printf(io,
                   1814:                            "Secure Renegotiation IS%s supported\n",
                   1815:                            SSL_get_secure_renegotiation_support(con) ?
                   1816:                            "" : " NOT");
                   1817:
                   1818:                        /*
                   1819:                         * The following is evil and should not really be
                   1820:                         * done
                   1821:                         */
                   1822:                        BIO_printf(io, "Ciphers supported in s_server binary\n");
                   1823:                        sk = SSL_get_ciphers(con);
                   1824:                        j = sk_SSL_CIPHER_num(sk);
                   1825:                        for (i = 0; i < j; i++) {
                   1826:                                c = sk_SSL_CIPHER_value(sk, i);
                   1827:                                BIO_printf(io, "%-11s:%-25s",
                   1828:                                    SSL_CIPHER_get_version(c),
                   1829:                                    SSL_CIPHER_get_name(c));
                   1830:                                if ((((i + 1) % 2) == 0) && (i + 1 != j))
                   1831:                                        BIO_puts(io, "\n");
                   1832:                        }
                   1833:                        BIO_puts(io, "\n");
                   1834:                        p = SSL_get_shared_ciphers(con, buf, bufsize);
                   1835:                        if (p != NULL) {
                   1836:                                BIO_printf(io, "---\nCiphers common between both SSL end points:\n");
                   1837:                                j = i = 0;
                   1838:                                while (*p) {
                   1839:                                        if (*p == ':') {
                   1840:                                                BIO_write(io, space, 26 - j);
                   1841:                                                i++;
                   1842:                                                j = 0;
                   1843:                                                BIO_write(io, ((i % 3) ? " " : "\n"), 1);
                   1844:                                        } else {
                   1845:                                                BIO_write(io, p, 1);
                   1846:                                                j++;
                   1847:                                        }
                   1848:                                        p++;
                   1849:                                }
                   1850:                                BIO_puts(io, "\n");
                   1851:                        }
                   1852:                        BIO_printf(io, (SSL_cache_hit(con)
                   1853:                                ? "---\nReused, "
                   1854:                                : "---\nNew, "));
                   1855:                        c = SSL_get_current_cipher(con);
                   1856:                        BIO_printf(io, "%s, Cipher is %s\n",
                   1857:                            SSL_CIPHER_get_version(c),
                   1858:                            SSL_CIPHER_get_name(c));
                   1859:                        SSL_SESSION_print(io, SSL_get_session(con));
                   1860:                        BIO_printf(io, "---\n");
                   1861:                        print_stats(io, SSL_get_SSL_CTX(con));
                   1862:                        BIO_printf(io, "---\n");
                   1863:                        peer = SSL_get_peer_certificate(con);
                   1864:                        if (peer != NULL) {
                   1865:                                BIO_printf(io, "Client certificate\n");
                   1866:                                X509_print(io, peer);
                   1867:                                PEM_write_bio_X509(io, peer);
                   1868:                        } else
                   1869:                                BIO_puts(io, "no client certificate available\n");
                   1870:                        BIO_puts(io, "</BODY></HTML>\r\n\r\n");
                   1871:                        break;
                   1872:                } else if ((www == 2 || www == 3)
                   1873:                    && (strncmp("GET /", buf, 5) == 0)) {
                   1874:                        BIO *file;
                   1875:                        char *p, *e;
                   1876:                        static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
                   1877:
                   1878:                        /* skip the '/' */
                   1879:                        p = &(buf[5]);
                   1880:
                   1881:                        dot = 1;
                   1882:                        for (e = p; *e != '\0'; e++) {
                   1883:                                if (e[0] == ' ')
                   1884:                                        break;
                   1885:
                   1886:                                switch (dot) {
                   1887:                                case 1:
                   1888:                                        dot = (e[0] == '.') ? 2 : 0;
                   1889:                                        break;
                   1890:                                case 2:
                   1891:                                        dot = (e[0] == '.') ? 3 : 0;
                   1892:                                        break;
                   1893:                                case 3:
                   1894:                                        dot = (e[0] == '/') ? -1 : 0;
                   1895:                                        break;
                   1896:                                }
                   1897:                                if (dot == 0)
                   1898:                                        dot = (e[0] == '/') ? 1 : 0;
                   1899:                        }
                   1900:                        dot = (dot == 3) || (dot == -1);        /* filename contains
                   1901:                                                                 * ".." component */
                   1902:
                   1903:                        if (*e == '\0') {
                   1904:                                BIO_puts(io, text);
                   1905:                                BIO_printf(io, "'%s' is an invalid file name\r\n", p);
                   1906:                                break;
                   1907:                        }
                   1908:                        *e = '\0';
                   1909:
                   1910:                        if (dot) {
                   1911:                                BIO_puts(io, text);
                   1912:                                BIO_printf(io, "'%s' contains '..' reference\r\n", p);
                   1913:                                break;
                   1914:                        }
                   1915:                        if (*p == '/') {
                   1916:                                BIO_puts(io, text);
                   1917:                                BIO_printf(io, "'%s' is an invalid path\r\n", p);
                   1918:                                break;
                   1919:                        }
                   1920:                        /* if a directory, do the index thang */
                   1921:                        if (app_isdir(p) > 0) {
                   1922:                                BIO_puts(io, text);
                   1923:                                BIO_printf(io, "'%s' is a directory\r\n", p);
                   1924:                                break;
                   1925:                        }
                   1926:                        if ((file = BIO_new_file(p, "r")) == NULL) {
                   1927:                                BIO_puts(io, text);
                   1928:                                BIO_printf(io, "Error opening '%s'\r\n", p);
                   1929:                                ERR_print_errors(io);
                   1930:                                break;
                   1931:                        }
                   1932:                        if (!s_quiet)
                   1933:                                BIO_printf(bio_err, "FILE:%s\n", p);
                   1934:
                   1935:                        if (www == 2) {
                   1936:                                i = strlen(p);
                   1937:                                if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
                   1938:                                    ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
                   1939:                                    ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
                   1940:                                        BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
                   1941:                                else
                   1942:                                        BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
                   1943:                        }
                   1944:                        /* send the file */
                   1945:                        for (;;) {
                   1946:                                i = BIO_read(file, buf, bufsize);
                   1947:                                if (i <= 0)
                   1948:                                        break;
                   1949:
                   1950: #ifdef RENEG
                   1951:                                total_bytes += i;
                   1952:                                fprintf(stderr, "%d\n", i);
                   1953:                                if (total_bytes > 3 * 1024) {
                   1954:                                        total_bytes = 0;
                   1955:                                        fprintf(stderr, "RENEGOTIATE\n");
                   1956:                                        SSL_renegotiate(con);
                   1957:                                }
                   1958: #endif
                   1959:
                   1960:                                for (j = 0; j < i;) {
                   1961: #ifdef RENEG
                   1962:                                        {
                   1963:                                                static count = 0;
                   1964:                                                if (++count == 13) {
                   1965:                                                        SSL_renegotiate(con);
                   1966:                                                }
                   1967:                                        }
                   1968: #endif
                   1969:                                        k = BIO_write(io, &(buf[j]), i - j);
                   1970:                                        if (k <= 0) {
                   1971:                                                if (!BIO_should_retry(io))
                   1972:                                                        goto write_error;
                   1973:                                                else {
                   1974:                                                        BIO_printf(bio_s_out, "rwrite W BLOCK\n");
                   1975:                                                }
                   1976:                                        } else {
                   1977:                                                j += k;
                   1978:                                        }
                   1979:                                }
                   1980:                        }
                   1981:        write_error:
                   1982:                        BIO_free(file);
                   1983:                        break;
                   1984:                }
                   1985:        }
                   1986:
                   1987:        for (;;) {
                   1988:                i = (int) BIO_flush(io);
                   1989:                if (i <= 0) {
                   1990:                        if (!BIO_should_retry(io))
                   1991:                                break;
                   1992:                } else
                   1993:                        break;
                   1994:        }
                   1995: end:
                   1996:        /* make sure we re-use sessions */
                   1997:        SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
                   1998:
                   1999: err:
                   2000:
                   2001:        if (ret >= 0)
                   2002:                BIO_printf(bio_s_out, "ACCEPT\n");
                   2003:
                   2004:        if (buf != NULL)
                   2005:                free(buf);
                   2006:        if (io != NULL)
                   2007:                BIO_free_all(io);
                   2008: /*     if (ssl_bio != NULL) BIO_free(ssl_bio);*/
                   2009:        return (ret);
                   2010: }
                   2011:
                   2012: #define MAX_SESSION_ID_ATTEMPTS 10
                   2013: static int
                   2014: generate_session_id(const SSL * ssl, unsigned char *id,
                   2015:     unsigned int *id_len)
                   2016: {
                   2017:        unsigned int count = 0;
                   2018:        do {
1.3       jsing    2019:                arc4random_buf(id, *id_len);
1.1       jsing    2020:                /*
                   2021:                 * Prefix the session_id with the required prefix. NB: If our
                   2022:                 * prefix is too long, clip it - but there will be worse
                   2023:                 * effects anyway, eg. the server could only possibly create
                   2024:                 * 1 session ID (ie. the prefix!) so all future session
                   2025:                 * negotiations will fail due to conflicts.
                   2026:                 */
                   2027:                memcpy(id, session_id_prefix,
                   2028:                    (strlen(session_id_prefix) < *id_len) ?
                   2029:                    strlen(session_id_prefix) : *id_len);
                   2030:        }
                   2031:        while (SSL_has_matching_session_id(ssl, id, *id_len) &&
                   2032:            (++count < MAX_SESSION_ID_ATTEMPTS));
                   2033:        if (count >= MAX_SESSION_ID_ATTEMPTS)
                   2034:                return 0;
                   2035:        return 1;
                   2036: }