source: rtems-libbsd/freebsd/crypto/openssl/apps/s_client.c @ 0fecf49

5
Last change on this file since 0fecf49 was 0fecf49, checked in by Christian Mauderer <christian.mauderer@…>, on 03/26/19 at 09:19:22

bin/openssl: Import from FreeBSD.

  • Property mode set to 100644
File size: 112.2 KB
Line 
1#include <machine/rtems-bsd-user-space.h>
2
3/*
4 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
5 * Copyright 2005 Nokia. All rights reserved.
6 *
7 * Licensed under the OpenSSL license (the "License").  You may not use
8 * this file except in compliance with the License.  You can obtain a copy
9 * in the file LICENSE in the source distribution or at
10 * https://www.openssl.org/source/license.html
11 */
12
13#include "e_os.h"
14#include <ctype.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <errno.h>
19#include <openssl/e_os2.h>
20
21#ifndef OPENSSL_NO_SOCK
22
23/*
24 * With IPv6, it looks like Digital has mixed up the proper order of
25 * recursive header file inclusion, resulting in the compiler complaining
26 * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
27 * needed to have fileno() declared correctly...  So let's define u_int
28 */
29#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
30# define __U_INT
31typedef unsigned int u_int;
32#endif
33
34#include "apps.h"
35#include "progs.h"
36#include <openssl/x509.h>
37#include <openssl/ssl.h>
38#include <openssl/err.h>
39#include <openssl/pem.h>
40#include <openssl/rand.h>
41#include <openssl/ocsp.h>
42#include <openssl/bn.h>
43#include <openssl/async.h>
44#ifndef OPENSSL_NO_SRP
45# include <openssl/srp.h>
46#endif
47#ifndef OPENSSL_NO_CT
48# include <openssl/ct.h>
49#endif
50#include "s_apps.h"
51#include "timeouts.h"
52#include "internal/sockets.h"
53
54#if defined(__has_feature)
55# if __has_feature(memory_sanitizer)
56#  include <sanitizer/msan_interface.h>
57# endif
58#endif
59
60#undef BUFSIZZ
61#define BUFSIZZ 1024*8
62#define S_CLIENT_IRC_READ_TIMEOUT 8
63
64static char *prog;
65static int c_debug = 0;
66static int c_showcerts = 0;
67static char *keymatexportlabel = NULL;
68static int keymatexportlen = 20;
69static BIO *bio_c_out = NULL;
70static int c_quiet = 0;
71static char *sess_out = NULL;
72static SSL_SESSION *psksess = NULL;
73
74static void print_stuff(BIO *berr, SSL *con, int full);
75#ifndef OPENSSL_NO_OCSP
76static int ocsp_resp_cb(SSL *s, void *arg);
77#endif
78static int ldap_ExtendedResponse_parse(const char *buf, long rem);
79
80static int saved_errno;
81
82static void save_errno(void)
83{
84    saved_errno = errno;
85    errno = 0;
86}
87
88static int restore_errno(void)
89{
90    int ret = errno;
91    errno = saved_errno;
92    return ret;
93}
94
95static void do_ssl_shutdown(SSL *ssl)
96{
97    int ret;
98
99    do {
100        /* We only do unidirectional shutdown */
101        ret = SSL_shutdown(ssl);
102        if (ret < 0) {
103            switch (SSL_get_error(ssl, ret)) {
104            case SSL_ERROR_WANT_READ:
105            case SSL_ERROR_WANT_WRITE:
106            case SSL_ERROR_WANT_ASYNC:
107            case SSL_ERROR_WANT_ASYNC_JOB:
108                /* We just do busy waiting. Nothing clever */
109                continue;
110            }
111            ret = 0;
112        }
113    } while (ret < 0);
114}
115
116/* Default PSK identity and key */
117static char *psk_identity = "Client_identity";
118
119#ifndef OPENSSL_NO_PSK
120static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
121                                  unsigned int max_identity_len,
122                                  unsigned char *psk,
123                                  unsigned int max_psk_len)
124{
125    int ret;
126    long key_len;
127    unsigned char *key;
128
129    if (c_debug)
130        BIO_printf(bio_c_out, "psk_client_cb\n");
131    if (!hint) {
132        /* no ServerKeyExchange message */
133        if (c_debug)
134            BIO_printf(bio_c_out,
135                       "NULL received PSK identity hint, continuing anyway\n");
136    } else if (c_debug) {
137        BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
138    }
139
140    /*
141     * lookup PSK identity and PSK key based on the given identity hint here
142     */
143    ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
144    if (ret < 0 || (unsigned int)ret > max_identity_len)
145        goto out_err;
146    if (c_debug)
147        BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
148                   ret);
149
150    /* convert the PSK key to binary */
151    key = OPENSSL_hexstr2buf(psk_key, &key_len);
152    if (key == NULL) {
153        BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
154                   psk_key);
155        return 0;
156    }
157    if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
158        BIO_printf(bio_err,
159                   "psk buffer of callback is too small (%d) for key (%ld)\n",
160                   max_psk_len, key_len);
161        OPENSSL_free(key);
162        return 0;
163    }
164
165    memcpy(psk, key, key_len);
166    OPENSSL_free(key);
167
168    if (c_debug)
169        BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
170
171    return key_len;
172 out_err:
173    if (c_debug)
174        BIO_printf(bio_err, "Error in PSK client callback\n");
175    return 0;
176}
177#endif
178
179const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
180const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
181
182static int psk_use_session_cb(SSL *s, const EVP_MD *md,
183                              const unsigned char **id, size_t *idlen,
184                              SSL_SESSION **sess)
185{
186    SSL_SESSION *usesess = NULL;
187    const SSL_CIPHER *cipher = NULL;
188
189    if (psksess != NULL) {
190        SSL_SESSION_up_ref(psksess);
191        usesess = psksess;
192    } else {
193        long key_len;
194        unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
195
196        if (key == NULL) {
197            BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
198                       psk_key);
199            return 0;
200        }
201
202        /* We default to SHA-256 */
203        cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
204        if (cipher == NULL) {
205            BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
206            OPENSSL_free(key);
207            return 0;
208        }
209
210        usesess = SSL_SESSION_new();
211        if (usesess == NULL
212                || !SSL_SESSION_set1_master_key(usesess, key, key_len)
213                || !SSL_SESSION_set_cipher(usesess, cipher)
214                || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
215            OPENSSL_free(key);
216            goto err;
217        }
218        OPENSSL_free(key);
219    }
220
221    cipher = SSL_SESSION_get0_cipher(usesess);
222    if (cipher == NULL)
223        goto err;
224
225    if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
226        /* PSK not usable, ignore it */
227        *id = NULL;
228        *idlen = 0;
229        *sess = NULL;
230        SSL_SESSION_free(usesess);
231    } else {
232        *sess = usesess;
233        *id = (unsigned char *)psk_identity;
234        *idlen = strlen(psk_identity);
235    }
236
237    return 1;
238
239 err:
240    SSL_SESSION_free(usesess);
241    return 0;
242}
243
244/* This is a context that we pass to callbacks */
245typedef struct tlsextctx_st {
246    BIO *biodebug;
247    int ack;
248} tlsextctx;
249
250static int ssl_servername_cb(SSL *s, int *ad, void *arg)
251{
252    tlsextctx *p = (tlsextctx *) arg;
253    const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
254    if (SSL_get_servername_type(s) != -1)
255        p->ack = !SSL_session_reused(s) && hn != NULL;
256    else
257        BIO_printf(bio_err, "Can't use SSL_get_servername\n");
258
259    return SSL_TLSEXT_ERR_OK;
260}
261
262#ifndef OPENSSL_NO_SRP
263
264/* This is a context that we pass to all callbacks */
265typedef struct srp_arg_st {
266    char *srppassin;
267    char *srplogin;
268    int msg;                    /* copy from c_msg */
269    int debug;                  /* copy from c_debug */
270    int amp;                    /* allow more groups */
271    int strength;               /* minimal size for N */
272} SRP_ARG;
273
274# define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
275
276static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
277{
278    BN_CTX *bn_ctx = BN_CTX_new();
279    BIGNUM *p = BN_new();
280    BIGNUM *r = BN_new();
281    int ret =
282        g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
283        BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
284        p != NULL && BN_rshift1(p, N) &&
285        /* p = (N-1)/2 */
286        BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
287        r != NULL &&
288        /* verify g^((N-1)/2) == -1 (mod N) */
289        BN_mod_exp(r, g, p, N, bn_ctx) &&
290        BN_add_word(r, 1) && BN_cmp(r, N) == 0;
291
292    BN_free(r);
293    BN_free(p);
294    BN_CTX_free(bn_ctx);
295    return ret;
296}
297
298/*-
299 * This callback is used here for two purposes:
300 * - extended debugging
301 * - making some primality tests for unknown groups
302 * The callback is only called for a non default group.
303 *
304 * An application does not need the call back at all if
305 * only the standard groups are used.  In real life situations,
306 * client and server already share well known groups,
307 * thus there is no need to verify them.
308 * Furthermore, in case that a server actually proposes a group that
309 * is not one of those defined in RFC 5054, it is more appropriate
310 * to add the group to a static list and then compare since
311 * primality tests are rather cpu consuming.
312 */
313
314static int ssl_srp_verify_param_cb(SSL *s, void *arg)
315{
316    SRP_ARG *srp_arg = (SRP_ARG *)arg;
317    BIGNUM *N = NULL, *g = NULL;
318
319    if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
320        return 0;
321    if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
322        BIO_printf(bio_err, "SRP parameters:\n");
323        BIO_printf(bio_err, "\tN=");
324        BN_print(bio_err, N);
325        BIO_printf(bio_err, "\n\tg=");
326        BN_print(bio_err, g);
327        BIO_printf(bio_err, "\n");
328    }
329
330    if (SRP_check_known_gN_param(g, N))
331        return 1;
332
333    if (srp_arg->amp == 1) {
334        if (srp_arg->debug)
335            BIO_printf(bio_err,
336                       "SRP param N and g are not known params, going to check deeper.\n");
337
338        /*
339         * The srp_moregroups is a real debugging feature. Implementors
340         * should rather add the value to the known ones. The minimal size
341         * has already been tested.
342         */
343        if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
344            return 1;
345    }
346    BIO_printf(bio_err, "SRP param N and g rejected.\n");
347    return 0;
348}
349
350# define PWD_STRLEN 1024
351
352static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
353{
354    SRP_ARG *srp_arg = (SRP_ARG *)arg;
355    char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
356    PW_CB_DATA cb_tmp;
357    int l;
358
359    cb_tmp.password = (char *)srp_arg->srppassin;
360    cb_tmp.prompt_info = "SRP user";
361    if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
362        BIO_printf(bio_err, "Can't read Password\n");
363        OPENSSL_free(pass);
364        return NULL;
365    }
366    *(pass + l) = '\0';
367
368    return pass;
369}
370
371#endif
372
373#ifndef OPENSSL_NO_NEXTPROTONEG
374/* This the context that we pass to next_proto_cb */
375typedef struct tlsextnextprotoctx_st {
376    unsigned char *data;
377    size_t len;
378    int status;
379} tlsextnextprotoctx;
380
381static tlsextnextprotoctx next_proto;
382
383static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
384                         const unsigned char *in, unsigned int inlen,
385                         void *arg)
386{
387    tlsextnextprotoctx *ctx = arg;
388
389    if (!c_quiet) {
390        /* We can assume that |in| is syntactically valid. */
391        unsigned i;
392        BIO_printf(bio_c_out, "Protocols advertised by server: ");
393        for (i = 0; i < inlen;) {
394            if (i)
395                BIO_write(bio_c_out, ", ", 2);
396            BIO_write(bio_c_out, &in[i + 1], in[i]);
397            i += in[i] + 1;
398        }
399        BIO_write(bio_c_out, "\n", 1);
400    }
401
402    ctx->status =
403        SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
404    return SSL_TLSEXT_ERR_OK;
405}
406#endif                         /* ndef OPENSSL_NO_NEXTPROTONEG */
407
408static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
409                                   const unsigned char *in, size_t inlen,
410                                   int *al, void *arg)
411{
412    char pem_name[100];
413    unsigned char ext_buf[4 + 65536];
414
415    /* Reconstruct the type/len fields prior to extension data */
416    inlen &= 0xffff; /* for formal memcmpy correctness */
417    ext_buf[0] = (unsigned char)(ext_type >> 8);
418    ext_buf[1] = (unsigned char)(ext_type);
419    ext_buf[2] = (unsigned char)(inlen >> 8);
420    ext_buf[3] = (unsigned char)(inlen);
421    memcpy(ext_buf + 4, in, inlen);
422
423    BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
424                 ext_type);
425    PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
426    return 1;
427}
428
429/*
430 * Hex decoder that tolerates optional whitespace.  Returns number of bytes
431 * produced, advances inptr to end of input string.
432 */
433static ossl_ssize_t hexdecode(const char **inptr, void *result)
434{
435    unsigned char **out = (unsigned char **)result;
436    const char *in = *inptr;
437    unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
438    unsigned char *cp = ret;
439    uint8_t byte;
440    int nibble = 0;
441
442    if (ret == NULL)
443        return -1;
444
445    for (byte = 0; *in; ++in) {
446        int x;
447
448        if (isspace(_UC(*in)))
449            continue;
450        x = OPENSSL_hexchar2int(*in);
451        if (x < 0) {
452            OPENSSL_free(ret);
453            return 0;
454        }
455        byte |= (char)x;
456        if ((nibble ^= 1) == 0) {
457            *cp++ = byte;
458            byte = 0;
459        } else {
460            byte <<= 4;
461        }
462    }
463    if (nibble != 0) {
464        OPENSSL_free(ret);
465        return 0;
466    }
467    *inptr = in;
468
469    return cp - (*out = ret);
470}
471
472/*
473 * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
474 * inptr to next field skipping leading whitespace.
475 */
476static ossl_ssize_t checked_uint8(const char **inptr, void *out)
477{
478    uint8_t *result = (uint8_t *)out;
479    const char *in = *inptr;
480    char *endp;
481    long v;
482    int e;
483
484    save_errno();
485    v = strtol(in, &endp, 10);
486    e = restore_errno();
487
488    if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
489        endp == in || !isspace(_UC(*endp)) ||
490        v != (*result = (uint8_t) v)) {
491        return -1;
492    }
493    for (in = endp; isspace(_UC(*in)); ++in)
494        continue;
495
496    *inptr = in;
497    return 1;
498}
499
500struct tlsa_field {
501    void *var;
502    const char *name;
503    ossl_ssize_t (*parser)(const char **, void *);
504};
505
506static int tlsa_import_rr(SSL *con, const char *rrdata)
507{
508    /* Not necessary to re-init these values; the "parsers" do that. */
509    static uint8_t usage;
510    static uint8_t selector;
511    static uint8_t mtype;
512    static unsigned char *data;
513    static struct tlsa_field tlsa_fields[] = {
514        { &usage, "usage", checked_uint8 },
515        { &selector, "selector", checked_uint8 },
516        { &mtype, "mtype", checked_uint8 },
517        { &data, "data", hexdecode },
518        { NULL, }
519    };
520    struct tlsa_field *f;
521    int ret;
522    const char *cp = rrdata;
523    ossl_ssize_t len = 0;
524
525    for (f = tlsa_fields; f->var; ++f) {
526        /* Returns number of bytes produced, advances cp to next field */
527        if ((len = f->parser(&cp, f->var)) <= 0) {
528            BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
529                       prog, f->name, rrdata);
530            return 0;
531        }
532    }
533    /* The data field is last, so len is its length */
534    ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
535    OPENSSL_free(data);
536
537    if (ret == 0) {
538        ERR_print_errors(bio_err);
539        BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
540                   prog, rrdata);
541        return 0;
542    }
543    if (ret < 0) {
544        ERR_print_errors(bio_err);
545        BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
546                   prog, rrdata);
547        return 0;
548    }
549    return ret;
550}
551
552static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
553{
554    int num = sk_OPENSSL_STRING_num(rrset);
555    int count = 0;
556    int i;
557
558    for (i = 0; i < num; ++i) {
559        char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
560        if (tlsa_import_rr(con, rrdata) > 0)
561            ++count;
562    }
563    return count > 0;
564}
565
566typedef enum OPTION_choice {
567    OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
568    OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX,
569    OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT,
570    OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
571    OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
572    OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
573    OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF,
574    OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
575    OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
576    OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
577    OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS,
578#ifndef OPENSSL_NO_SRP
579    OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
580    OPT_SRP_MOREGROUPS,
581#endif
582    OPT_SSL3, OPT_SSL_CONFIG,
583    OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
584    OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
585    OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH,
586    OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE,
587    OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN,
588    OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC,
589    OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST,
590    OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES,
591    OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE,
592    OPT_V_ENUM,
593    OPT_X_ENUM,
594    OPT_S_ENUM,
595    OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_DANE_TLSA_DOMAIN,
596#ifndef OPENSSL_NO_CT
597    OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
598#endif
599    OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME,
600    OPT_ENABLE_PHA,
601    OPT_R_ENUM
602} OPTION_CHOICE;
603
604const OPTIONS s_client_options[] = {
605    {"help", OPT_HELP, '-', "Display this summary"},
606    {"host", OPT_HOST, 's', "Use -connect instead"},
607    {"port", OPT_PORT, 'p', "Use -connect instead"},
608    {"connect", OPT_CONNECT, 's',
609     "TCP/IP where to connect (default is :" PORT ")"},
610    {"bind", OPT_BIND, 's', "bind local address for connection"},
611    {"proxy", OPT_PROXY, 's',
612     "Connect to via specified proxy to the real server"},
613#ifdef AF_UNIX
614    {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"},
615#endif
616    {"4", OPT_4, '-', "Use IPv4 only"},
617#ifdef AF_INET6
618    {"6", OPT_6, '-', "Use IPv6 only"},
619#endif
620    {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
621    {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"},
622    {"certform", OPT_CERTFORM, 'F',
623     "Certificate format (PEM or DER) PEM default"},
624    {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
625    {"key", OPT_KEY, 's', "Private key file to use, if not in -cert file"},
626    {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
627    {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
628    {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
629    {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
630    {"no-CAfile", OPT_NOCAFILE, '-',
631     "Do not load the default certificates file"},
632    {"no-CApath", OPT_NOCAPATH, '-',
633     "Do not load certificates from the default certificates directory"},
634    {"requestCAfile", OPT_REQCAFILE, '<',
635      "PEM format file of CA names to send to the server"},
636    {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
637    {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
638     "DANE TLSA rrdata presentation form"},
639    {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
640     "Disable name checks when matching DANE-EE(3) TLSA records"},
641    {"reconnect", OPT_RECONNECT, '-',
642     "Drop and re-make the connection with the same Session-ID"},
643    {"showcerts", OPT_SHOWCERTS, '-',
644     "Show all certificates sent by the server"},
645    {"debug", OPT_DEBUG, '-', "Extra output"},
646    {"msg", OPT_MSG, '-', "Show protocol messages"},
647    {"msgfile", OPT_MSGFILE, '>',
648     "File to send output of -msg or -trace, instead of stdout"},
649    {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
650    {"state", OPT_STATE, '-', "Print the ssl states"},
651    {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
652    {"quiet", OPT_QUIET, '-', "No s_client output"},
653    {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
654    {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
655    {"starttls", OPT_STARTTLS, 's',
656     "Use the appropriate STARTTLS command before starting TLS"},
657    {"xmpphost", OPT_XMPPHOST, 's',
658     "Alias of -name option for \"-starttls xmpp[-server]\""},
659    OPT_R_OPTIONS,
660    {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
661    {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
662#ifndef OPENSSL_NO_SRTP
663    {"use_srtp", OPT_USE_SRTP, 's',
664     "Offer SRTP key management with a colon-separated profile list"},
665#endif
666    {"keymatexport", OPT_KEYMATEXPORT, 's',
667     "Export keying material using label"},
668    {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
669     "Export len bytes of keying material (default 20)"},
670    {"maxfraglen", OPT_MAXFRAGLEN, 'p',
671     "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"},
672    {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
673    {"name", OPT_PROTOHOST, 's',
674     "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""},
675    {"CRL", OPT_CRL, '<', "CRL file to use"},
676    {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
677    {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
678    {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
679     "Close connection on verification error"},
680    {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
681    {"brief", OPT_BRIEF, '-',
682     "Restrict output to brief summary of connection parameters"},
683    {"prexit", OPT_PREXIT, '-',
684     "Print session information when the program exits"},
685    {"security_debug", OPT_SECURITY_DEBUG, '-',
686     "Enable security debug messages"},
687    {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
688     "Output more security debug output"},
689    {"cert_chain", OPT_CERT_CHAIN, '<',
690     "Certificate chain file (in PEM format)"},
691    {"chainCApath", OPT_CHAINCAPATH, '/',
692     "Use dir as certificate store path to build CA certificate chain"},
693    {"verifyCApath", OPT_VERIFYCAPATH, '/',
694     "Use dir as certificate store path to verify CA certificate"},
695    {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
696    {"chainCAfile", OPT_CHAINCAFILE, '<',
697     "CA file for certificate chain (PEM format)"},
698    {"verifyCAfile", OPT_VERIFYCAFILE, '<',
699     "CA file for certificate verification (PEM format)"},
700    {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
701    {"servername", OPT_SERVERNAME, 's',
702     "Set TLS extension servername (SNI) in ClientHello (default)"},
703    {"noservername", OPT_NOSERVERNAME, '-',
704     "Do not send the server name (SNI) extension in the ClientHello"},
705    {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
706     "Hex dump of all TLS extensions received"},
707#ifndef OPENSSL_NO_OCSP
708    {"status", OPT_STATUS, '-', "Request certificate status from server"},
709#endif
710    {"serverinfo", OPT_SERVERINFO, 's',
711     "types  Send empty ClientHello extensions (comma-separated numbers)"},
712    {"alpn", OPT_ALPN, 's',
713     "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
714    {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
715    {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified configuration file"},
716    {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "},
717    {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
718     "Size used to split data for encrypt pipelines"},
719    {"max_pipelines", OPT_MAX_PIPELINES, 'p',
720     "Maximum number of encrypt/decrypt pipelines to be used"},
721    {"read_buf", OPT_READ_BUF, 'p',
722     "Default read buffer size to be used for connections"},
723    OPT_S_OPTIONS,
724    OPT_V_OPTIONS,
725    OPT_X_OPTIONS,
726#ifndef OPENSSL_NO_SSL3
727    {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
728#endif
729#ifndef OPENSSL_NO_TLS1
730    {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
731#endif
732#ifndef OPENSSL_NO_TLS1_1
733    {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
734#endif
735#ifndef OPENSSL_NO_TLS1_2
736    {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
737#endif
738#ifndef OPENSSL_NO_TLS1_3
739    {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
740#endif
741#ifndef OPENSSL_NO_DTLS
742    {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
743    {"timeout", OPT_TIMEOUT, '-',
744     "Enable send/receive timeout on DTLS connections"},
745    {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
746#endif
747#ifndef OPENSSL_NO_DTLS1
748    {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
749#endif
750#ifndef OPENSSL_NO_DTLS1_2
751    {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
752#endif
753#ifndef OPENSSL_NO_SCTP
754    {"sctp", OPT_SCTP, '-', "Use SCTP"},
755#endif
756#ifndef OPENSSL_NO_SSL_TRACE
757    {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
758#endif
759#ifdef WATT32
760    {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
761#endif
762    {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
763    {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
764    {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
765    {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"},
766#ifndef OPENSSL_NO_SRP
767    {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
768    {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
769    {"srp_lateuser", OPT_SRP_LATEUSER, '-',
770     "SRP username into second ClientHello message"},
771    {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
772     "Tolerate other than the known g N values."},
773    {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
774#endif
775#ifndef OPENSSL_NO_NEXTPROTONEG
776    {"nextprotoneg", OPT_NEXTPROTONEG, 's',
777     "Enable NPN extension, considering named protocols supported (comma-separated list)"},
778#endif
779#ifndef OPENSSL_NO_ENGINE
780    {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
781    {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
782     "Specify engine to be used for client certificate operations"},
783#endif
784#ifndef OPENSSL_NO_CT
785    {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
786    {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
787    {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
788#endif
789    {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"},
790    {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"},
791    {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"},
792    {NULL, OPT_EOF, 0x00, NULL}
793};
794
795typedef enum PROTOCOL_choice {
796    PROTO_OFF,
797    PROTO_SMTP,
798    PROTO_POP3,
799    PROTO_IMAP,
800    PROTO_FTP,
801    PROTO_TELNET,
802    PROTO_XMPP,
803    PROTO_XMPP_SERVER,
804    PROTO_CONNECT,
805    PROTO_IRC,
806    PROTO_MYSQL,
807    PROTO_POSTGRES,
808    PROTO_LMTP,
809    PROTO_NNTP,
810    PROTO_SIEVE,
811    PROTO_LDAP
812} PROTOCOL_CHOICE;
813
814static const OPT_PAIR services[] = {
815    {"smtp", PROTO_SMTP},
816    {"pop3", PROTO_POP3},
817    {"imap", PROTO_IMAP},
818    {"ftp", PROTO_FTP},
819    {"xmpp", PROTO_XMPP},
820    {"xmpp-server", PROTO_XMPP_SERVER},
821    {"telnet", PROTO_TELNET},
822    {"irc", PROTO_IRC},
823    {"mysql", PROTO_MYSQL},
824    {"postgres", PROTO_POSTGRES},
825    {"lmtp", PROTO_LMTP},
826    {"nntp", PROTO_NNTP},
827    {"sieve", PROTO_SIEVE},
828    {"ldap", PROTO_LDAP},
829    {NULL, 0}
830};
831
832#define IS_INET_FLAG(o) \
833 (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
834#define IS_UNIX_FLAG(o) (o == OPT_UNIX)
835
836#define IS_PROT_FLAG(o) \
837 (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
838  || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
839
840/* Free |*dest| and optionally set it to a copy of |source|. */
841static void freeandcopy(char **dest, const char *source)
842{
843    OPENSSL_free(*dest);
844    *dest = NULL;
845    if (source != NULL)
846        *dest = OPENSSL_strdup(source);
847}
848
849static int new_session_cb(SSL *s, SSL_SESSION *sess)
850{
851
852    if (sess_out != NULL) {
853        BIO *stmp = BIO_new_file(sess_out, "w");
854
855        if (stmp == NULL) {
856            BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
857        } else {
858            PEM_write_bio_SSL_SESSION(stmp, sess);
859            BIO_free(stmp);
860        }
861    }
862
863    /*
864     * Session data gets dumped on connection for TLSv1.2 and below, and on
865     * arrival of the NewSessionTicket for TLSv1.3.
866     */
867    if (SSL_version(s) == TLS1_3_VERSION) {
868        BIO_printf(bio_c_out,
869                   "---\nPost-Handshake New Session Ticket arrived:\n");
870        SSL_SESSION_print(bio_c_out, sess);
871        BIO_printf(bio_c_out, "---\n");
872    }
873
874    /*
875     * We always return a "fail" response so that the session gets freed again
876     * because we haven't used the reference.
877     */
878    return 0;
879}
880
881int s_client_main(int argc, char **argv)
882{
883    BIO *sbio;
884    EVP_PKEY *key = NULL;
885    SSL *con = NULL;
886    SSL_CTX *ctx = NULL;
887    STACK_OF(X509) *chain = NULL;
888    X509 *cert = NULL;
889    X509_VERIFY_PARAM *vpm = NULL;
890    SSL_EXCERT *exc = NULL;
891    SSL_CONF_CTX *cctx = NULL;
892    STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
893    char *dane_tlsa_domain = NULL;
894    STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
895    int dane_ee_no_name = 0;
896    STACK_OF(X509_CRL) *crls = NULL;
897    const SSL_METHOD *meth = TLS_client_method();
898    const char *CApath = NULL, *CAfile = NULL;
899    char *cbuf = NULL, *sbuf = NULL;
900    char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL, *bindstr = NULL;
901    char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
902    char *chCApath = NULL, *chCAfile = NULL, *host = NULL;
903    char *port = OPENSSL_strdup(PORT);
904    char *bindhost = NULL, *bindport = NULL;
905    char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
906    char *ReqCAfile = NULL;
907    char *sess_in = NULL, *crl_file = NULL, *p;
908    const char *protohost = NULL;
909    struct timeval timeout, *timeoutp;
910    fd_set readfds, writefds;
911    int noCApath = 0, noCAfile = 0;
912    int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
913    int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
914    int prexit = 0;
915    int sdebug = 0;
916    int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
917    int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0;
918    int sbuf_len, sbuf_off, cmdletters = 1;
919    int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
920    int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
921    int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
922#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
923    int at_eof = 0;
924#endif
925    int read_buf_len = 0;
926    int fallback_scsv = 0;
927    OPTION_CHOICE o;
928#ifndef OPENSSL_NO_DTLS
929    int enable_timeouts = 0;
930    long socket_mtu = 0;
931#endif
932#ifndef OPENSSL_NO_ENGINE
933    ENGINE *ssl_client_engine = NULL;
934#endif
935    ENGINE *e = NULL;
936#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
937    struct timeval tv;
938#endif
939    const char *servername = NULL;
940    int noservername = 0;
941    const char *alpn_in = NULL;
942    tlsextctx tlsextcbp = { NULL, 0 };
943    const char *ssl_config = NULL;
944#define MAX_SI_TYPES 100
945    unsigned short serverinfo_types[MAX_SI_TYPES];
946    int serverinfo_count = 0, start = 0, len;
947#ifndef OPENSSL_NO_NEXTPROTONEG
948    const char *next_proto_neg_in = NULL;
949#endif
950#ifndef OPENSSL_NO_SRP
951    char *srppass = NULL;
952    int srp_lateuser = 0;
953    SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
954#endif
955#ifndef OPENSSL_NO_SRTP
956    char *srtp_profiles = NULL;
957#endif
958#ifndef OPENSSL_NO_CT
959    char *ctlog_file = NULL;
960    int ct_validation = 0;
961#endif
962    int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
963    int async = 0;
964    unsigned int max_send_fragment = 0;
965    unsigned int split_send_fragment = 0, max_pipelines = 0;
966    enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
967    int count4or6 = 0;
968    uint8_t maxfraglen = 0;
969    int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
970    int c_tlsextdebug = 0;
971#ifndef OPENSSL_NO_OCSP
972    int c_status_req = 0;
973#endif
974    BIO *bio_c_msg = NULL;
975    const char *keylog_file = NULL, *early_data_file = NULL;
976#ifndef OPENSSL_NO_DTLS
977    int isdtls = 0;
978#endif
979    char *psksessf = NULL;
980    int enable_pha = 0;
981
982    FD_ZERO(&readfds);
983    FD_ZERO(&writefds);
984/* Known false-positive of MemorySanitizer. */
985#if defined(__has_feature)
986# if __has_feature(memory_sanitizer)
987    __msan_unpoison(&readfds, sizeof(readfds));
988    __msan_unpoison(&writefds, sizeof(writefds));
989# endif
990#endif
991
992    prog = opt_progname(argv[0]);
993    c_quiet = 0;
994    c_debug = 0;
995    c_showcerts = 0;
996    c_nbio = 0;
997    vpm = X509_VERIFY_PARAM_new();
998    cctx = SSL_CONF_CTX_new();
999
1000    if (vpm == NULL || cctx == NULL) {
1001        BIO_printf(bio_err, "%s: out of memory\n", prog);
1002        goto end;
1003    }
1004
1005    cbuf = app_malloc(BUFSIZZ, "cbuf");
1006    sbuf = app_malloc(BUFSIZZ, "sbuf");
1007    mbuf = app_malloc(BUFSIZZ, "mbuf");
1008
1009    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
1010
1011    prog = opt_init(argc, argv, s_client_options);
1012    while ((o = opt_next()) != OPT_EOF) {
1013        /* Check for intermixing flags. */
1014        if (connect_type == use_unix && IS_INET_FLAG(o)) {
1015            BIO_printf(bio_err,
1016                       "%s: Intermixed protocol flags (unix and internet domains)\n",
1017                       prog);
1018            goto end;
1019        }
1020        if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
1021            BIO_printf(bio_err,
1022                       "%s: Intermixed protocol flags (internet and unix domains)\n",
1023                       prog);
1024            goto end;
1025        }
1026
1027        if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
1028            BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
1029            goto end;
1030        }
1031        if (IS_NO_PROT_FLAG(o))
1032            no_prot_opt++;
1033        if (prot_opt == 1 && no_prot_opt) {
1034            BIO_printf(bio_err,
1035                       "Cannot supply both a protocol flag and '-no_<prot>'\n");
1036            goto end;
1037        }
1038
1039        switch (o) {
1040        case OPT_EOF:
1041        case OPT_ERR:
1042 opthelp:
1043            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1044            goto end;
1045        case OPT_HELP:
1046            opt_help(s_client_options);
1047            ret = 0;
1048            goto end;
1049        case OPT_4:
1050            connect_type = use_inet;
1051            socket_family = AF_INET;
1052            count4or6++;
1053            break;
1054#ifdef AF_INET6
1055        case OPT_6:
1056            connect_type = use_inet;
1057            socket_family = AF_INET6;
1058            count4or6++;
1059            break;
1060#endif
1061        case OPT_HOST:
1062            connect_type = use_inet;
1063            freeandcopy(&host, opt_arg());
1064            break;
1065        case OPT_PORT:
1066            connect_type = use_inet;
1067            freeandcopy(&port, opt_arg());
1068            break;
1069        case OPT_CONNECT:
1070            connect_type = use_inet;
1071            freeandcopy(&connectstr, opt_arg());
1072            break;
1073        case OPT_BIND:
1074            freeandcopy(&bindstr, opt_arg());
1075            break;
1076        case OPT_PROXY:
1077            proxystr = opt_arg();
1078            starttls_proto = PROTO_CONNECT;
1079            break;
1080#ifdef AF_UNIX
1081        case OPT_UNIX:
1082            connect_type = use_unix;
1083            socket_family = AF_UNIX;
1084            freeandcopy(&host, opt_arg());
1085            break;
1086#endif
1087        case OPT_XMPPHOST:
1088            /* fall through, since this is an alias */
1089        case OPT_PROTOHOST:
1090            protohost = opt_arg();
1091            break;
1092        case OPT_VERIFY:
1093            verify = SSL_VERIFY_PEER;
1094            verify_args.depth = atoi(opt_arg());
1095            if (!c_quiet)
1096                BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
1097            break;
1098        case OPT_CERT:
1099            cert_file = opt_arg();
1100            break;
1101        case OPT_NAMEOPT:
1102            if (!set_nameopt(opt_arg()))
1103                goto end;
1104            break;
1105        case OPT_CRL:
1106            crl_file = opt_arg();
1107            break;
1108        case OPT_CRL_DOWNLOAD:
1109            crl_download = 1;
1110            break;
1111        case OPT_SESS_OUT:
1112            sess_out = opt_arg();
1113            break;
1114        case OPT_SESS_IN:
1115            sess_in = opt_arg();
1116            break;
1117        case OPT_CERTFORM:
1118            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
1119                goto opthelp;
1120            break;
1121        case OPT_CRLFORM:
1122            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1123                goto opthelp;
1124            break;
1125        case OPT_VERIFY_RET_ERROR:
1126            verify_args.return_error = 1;
1127            break;
1128        case OPT_VERIFY_QUIET:
1129            verify_args.quiet = 1;
1130            break;
1131        case OPT_BRIEF:
1132            c_brief = verify_args.quiet = c_quiet = 1;
1133            break;
1134        case OPT_S_CASES:
1135            if (ssl_args == NULL)
1136                ssl_args = sk_OPENSSL_STRING_new_null();
1137            if (ssl_args == NULL
1138                || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1139                || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1140                BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1141                goto end;
1142            }
1143            break;
1144        case OPT_V_CASES:
1145            if (!opt_verify(o, vpm))
1146                goto end;
1147            vpmtouched++;
1148            break;
1149        case OPT_X_CASES:
1150            if (!args_excert(o, &exc))
1151                goto end;
1152            break;
1153        case OPT_PREXIT:
1154            prexit = 1;
1155            break;
1156        case OPT_CRLF:
1157            crlf = 1;
1158            break;
1159        case OPT_QUIET:
1160            c_quiet = c_ign_eof = 1;
1161            break;
1162        case OPT_NBIO:
1163            c_nbio = 1;
1164            break;
1165        case OPT_NOCMDS:
1166            cmdletters = 0;
1167            break;
1168        case OPT_ENGINE:
1169            e = setup_engine(opt_arg(), 1);
1170            break;
1171        case OPT_SSL_CLIENT_ENGINE:
1172#ifndef OPENSSL_NO_ENGINE
1173            ssl_client_engine = ENGINE_by_id(opt_arg());
1174            if (ssl_client_engine == NULL) {
1175                BIO_printf(bio_err, "Error getting client auth engine\n");
1176                goto opthelp;
1177            }
1178#endif
1179            break;
1180        case OPT_R_CASES:
1181            if (!opt_rand(o))
1182                goto end;
1183            break;
1184        case OPT_IGN_EOF:
1185            c_ign_eof = 1;
1186            break;
1187        case OPT_NO_IGN_EOF:
1188            c_ign_eof = 0;
1189            break;
1190        case OPT_DEBUG:
1191            c_debug = 1;
1192            break;
1193        case OPT_TLSEXTDEBUG:
1194            c_tlsextdebug = 1;
1195            break;
1196        case OPT_STATUS:
1197#ifndef OPENSSL_NO_OCSP
1198            c_status_req = 1;
1199#endif
1200            break;
1201        case OPT_WDEBUG:
1202#ifdef WATT32
1203            dbug_init();
1204#endif
1205            break;
1206        case OPT_MSG:
1207            c_msg = 1;
1208            break;
1209        case OPT_MSGFILE:
1210            bio_c_msg = BIO_new_file(opt_arg(), "w");
1211            break;
1212        case OPT_TRACE:
1213#ifndef OPENSSL_NO_SSL_TRACE
1214            c_msg = 2;
1215#endif
1216            break;
1217        case OPT_SECURITY_DEBUG:
1218            sdebug = 1;
1219            break;
1220        case OPT_SECURITY_DEBUG_VERBOSE:
1221            sdebug = 2;
1222            break;
1223        case OPT_SHOWCERTS:
1224            c_showcerts = 1;
1225            break;
1226        case OPT_NBIO_TEST:
1227            nbio_test = 1;
1228            break;
1229        case OPT_STATE:
1230            state = 1;
1231            break;
1232        case OPT_PSK_IDENTITY:
1233            psk_identity = opt_arg();
1234            break;
1235        case OPT_PSK:
1236            for (p = psk_key = opt_arg(); *p; p++) {
1237                if (isxdigit(_UC(*p)))
1238                    continue;
1239                BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1240                goto end;
1241            }
1242            break;
1243        case OPT_PSK_SESS:
1244            psksessf = opt_arg();
1245            break;
1246#ifndef OPENSSL_NO_SRP
1247        case OPT_SRPUSER:
1248            srp_arg.srplogin = opt_arg();
1249            if (min_version < TLS1_VERSION)
1250                min_version = TLS1_VERSION;
1251            break;
1252        case OPT_SRPPASS:
1253            srppass = opt_arg();
1254            if (min_version < TLS1_VERSION)
1255                min_version = TLS1_VERSION;
1256            break;
1257        case OPT_SRP_STRENGTH:
1258            srp_arg.strength = atoi(opt_arg());
1259            BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1260                       srp_arg.strength);
1261            if (min_version < TLS1_VERSION)
1262                min_version = TLS1_VERSION;
1263            break;
1264        case OPT_SRP_LATEUSER:
1265            srp_lateuser = 1;
1266            if (min_version < TLS1_VERSION)
1267                min_version = TLS1_VERSION;
1268            break;
1269        case OPT_SRP_MOREGROUPS:
1270            srp_arg.amp = 1;
1271            if (min_version < TLS1_VERSION)
1272                min_version = TLS1_VERSION;
1273            break;
1274#endif
1275        case OPT_SSL_CONFIG:
1276            ssl_config = opt_arg();
1277            break;
1278        case OPT_SSL3:
1279            min_version = SSL3_VERSION;
1280            max_version = SSL3_VERSION;
1281            break;
1282        case OPT_TLS1_3:
1283            min_version = TLS1_3_VERSION;
1284            max_version = TLS1_3_VERSION;
1285            break;
1286        case OPT_TLS1_2:
1287            min_version = TLS1_2_VERSION;
1288            max_version = TLS1_2_VERSION;
1289            break;
1290        case OPT_TLS1_1:
1291            min_version = TLS1_1_VERSION;
1292            max_version = TLS1_1_VERSION;
1293            break;
1294        case OPT_TLS1:
1295            min_version = TLS1_VERSION;
1296            max_version = TLS1_VERSION;
1297            break;
1298        case OPT_DTLS:
1299#ifndef OPENSSL_NO_DTLS
1300            meth = DTLS_client_method();
1301            socket_type = SOCK_DGRAM;
1302            isdtls = 1;
1303#endif
1304            break;
1305        case OPT_DTLS1:
1306#ifndef OPENSSL_NO_DTLS1
1307            meth = DTLS_client_method();
1308            min_version = DTLS1_VERSION;
1309            max_version = DTLS1_VERSION;
1310            socket_type = SOCK_DGRAM;
1311            isdtls = 1;
1312#endif
1313            break;
1314        case OPT_DTLS1_2:
1315#ifndef OPENSSL_NO_DTLS1_2
1316            meth = DTLS_client_method();
1317            min_version = DTLS1_2_VERSION;
1318            max_version = DTLS1_2_VERSION;
1319            socket_type = SOCK_DGRAM;
1320            isdtls = 1;
1321#endif
1322            break;
1323        case OPT_SCTP:
1324#ifndef OPENSSL_NO_SCTP
1325            protocol = IPPROTO_SCTP;
1326#endif
1327            break;
1328        case OPT_TIMEOUT:
1329#ifndef OPENSSL_NO_DTLS
1330            enable_timeouts = 1;
1331#endif
1332            break;
1333        case OPT_MTU:
1334#ifndef OPENSSL_NO_DTLS
1335            socket_mtu = atol(opt_arg());
1336#endif
1337            break;
1338        case OPT_FALLBACKSCSV:
1339            fallback_scsv = 1;
1340            break;
1341        case OPT_KEYFORM:
1342            if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
1343                goto opthelp;
1344            break;
1345        case OPT_PASS:
1346            passarg = opt_arg();
1347            break;
1348        case OPT_CERT_CHAIN:
1349            chain_file = opt_arg();
1350            break;
1351        case OPT_KEY:
1352            key_file = opt_arg();
1353            break;
1354        case OPT_RECONNECT:
1355            reconnect = 5;
1356            break;
1357        case OPT_CAPATH:
1358            CApath = opt_arg();
1359            break;
1360        case OPT_NOCAPATH:
1361            noCApath = 1;
1362            break;
1363        case OPT_CHAINCAPATH:
1364            chCApath = opt_arg();
1365            break;
1366        case OPT_VERIFYCAPATH:
1367            vfyCApath = opt_arg();
1368            break;
1369        case OPT_BUILD_CHAIN:
1370            build_chain = 1;
1371            break;
1372        case OPT_REQCAFILE:
1373            ReqCAfile = opt_arg();
1374            break;
1375        case OPT_CAFILE:
1376            CAfile = opt_arg();
1377            break;
1378        case OPT_NOCAFILE:
1379            noCAfile = 1;
1380            break;
1381#ifndef OPENSSL_NO_CT
1382        case OPT_NOCT:
1383            ct_validation = 0;
1384            break;
1385        case OPT_CT:
1386            ct_validation = 1;
1387            break;
1388        case OPT_CTLOG_FILE:
1389            ctlog_file = opt_arg();
1390            break;
1391#endif
1392        case OPT_CHAINCAFILE:
1393            chCAfile = opt_arg();
1394            break;
1395        case OPT_VERIFYCAFILE:
1396            vfyCAfile = opt_arg();
1397            break;
1398        case OPT_DANE_TLSA_DOMAIN:
1399            dane_tlsa_domain = opt_arg();
1400            break;
1401        case OPT_DANE_TLSA_RRDATA:
1402            if (dane_tlsa_rrset == NULL)
1403                dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1404            if (dane_tlsa_rrset == NULL ||
1405                !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1406                BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1407                goto end;
1408            }
1409            break;
1410        case OPT_DANE_EE_NO_NAME:
1411            dane_ee_no_name = 1;
1412            break;
1413        case OPT_NEXTPROTONEG:
1414#ifndef OPENSSL_NO_NEXTPROTONEG
1415            next_proto_neg_in = opt_arg();
1416#endif
1417            break;
1418        case OPT_ALPN:
1419            alpn_in = opt_arg();
1420            break;
1421        case OPT_SERVERINFO:
1422            p = opt_arg();
1423            len = strlen(p);
1424            for (start = 0, i = 0; i <= len; ++i) {
1425                if (i == len || p[i] == ',') {
1426                    serverinfo_types[serverinfo_count] = atoi(p + start);
1427                    if (++serverinfo_count == MAX_SI_TYPES)
1428                        break;
1429                    start = i + 1;
1430                }
1431            }
1432            break;
1433        case OPT_STARTTLS:
1434            if (!opt_pair(opt_arg(), services, &starttls_proto))
1435                goto end;
1436            break;
1437        case OPT_SERVERNAME:
1438            servername = opt_arg();
1439            break;
1440        case OPT_NOSERVERNAME:
1441            noservername = 1;
1442            break;
1443        case OPT_USE_SRTP:
1444#ifndef OPENSSL_NO_SRTP
1445            srtp_profiles = opt_arg();
1446#endif
1447            break;
1448        case OPT_KEYMATEXPORT:
1449            keymatexportlabel = opt_arg();
1450            break;
1451        case OPT_KEYMATEXPORTLEN:
1452            keymatexportlen = atoi(opt_arg());
1453            break;
1454        case OPT_ASYNC:
1455            async = 1;
1456            break;
1457        case OPT_MAXFRAGLEN:
1458            len = atoi(opt_arg());
1459            switch (len) {
1460            case 512:
1461                maxfraglen = TLSEXT_max_fragment_length_512;
1462                break;
1463            case 1024:
1464                maxfraglen = TLSEXT_max_fragment_length_1024;
1465                break;
1466            case 2048:
1467                maxfraglen = TLSEXT_max_fragment_length_2048;
1468                break;
1469            case 4096:
1470                maxfraglen = TLSEXT_max_fragment_length_4096;
1471                break;
1472            default:
1473                BIO_printf(bio_err,
1474                           "%s: Max Fragment Len %u is out of permitted values",
1475                           prog, len);
1476                goto opthelp;
1477            }
1478            break;
1479        case OPT_MAX_SEND_FRAG:
1480            max_send_fragment = atoi(opt_arg());
1481            break;
1482        case OPT_SPLIT_SEND_FRAG:
1483            split_send_fragment = atoi(opt_arg());
1484            break;
1485        case OPT_MAX_PIPELINES:
1486            max_pipelines = atoi(opt_arg());
1487            break;
1488        case OPT_READ_BUF:
1489            read_buf_len = atoi(opt_arg());
1490            break;
1491        case OPT_KEYLOG_FILE:
1492            keylog_file = opt_arg();
1493            break;
1494        case OPT_EARLY_DATA:
1495            early_data_file = opt_arg();
1496            break;
1497        case OPT_ENABLE_PHA:
1498            enable_pha = 1;
1499            break;
1500        }
1501    }
1502    if (count4or6 >= 2) {
1503        BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1504        goto opthelp;
1505    }
1506    if (noservername) {
1507        if (servername != NULL) {
1508            BIO_printf(bio_err,
1509                       "%s: Can't use -servername and -noservername together\n",
1510                       prog);
1511            goto opthelp;
1512        }
1513        if (dane_tlsa_domain != NULL) {
1514            BIO_printf(bio_err,
1515               "%s: Can't use -dane_tlsa_domain and -noservername together\n",
1516               prog);
1517            goto opthelp;
1518        }
1519    }
1520    argc = opt_num_rest();
1521    if (argc == 1) {
1522        /* If there's a positional argument, it's the equivalent of
1523         * OPT_CONNECT.
1524         * Don't allow -connect and a separate argument.
1525         */
1526        if (connectstr != NULL) {
1527            BIO_printf(bio_err,
1528                       "%s: must not provide both -connect option and target parameter\n",
1529                       prog);
1530            goto opthelp;
1531        }
1532        connect_type = use_inet;
1533        freeandcopy(&connectstr, *opt_rest());
1534    } else if (argc != 0) {
1535        goto opthelp;
1536    }
1537
1538#ifndef OPENSSL_NO_NEXTPROTONEG
1539    if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
1540        BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
1541        goto opthelp;
1542    }
1543#endif
1544    if (proxystr != NULL) {
1545        int res;
1546        char *tmp_host = host, *tmp_port = port;
1547        if (connectstr == NULL) {
1548            BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
1549            goto opthelp;
1550        }
1551        res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1552        if (tmp_host != host)
1553            OPENSSL_free(tmp_host);
1554        if (tmp_port != port)
1555            OPENSSL_free(tmp_port);
1556        if (!res) {
1557            BIO_printf(bio_err,
1558                       "%s: -proxy argument malformed or ambiguous\n", prog);
1559            goto end;
1560        }
1561    } else {
1562        int res = 1;
1563        char *tmp_host = host, *tmp_port = port;
1564        if (connectstr != NULL)
1565            res = BIO_parse_hostserv(connectstr, &host, &port,
1566                                     BIO_PARSE_PRIO_HOST);
1567        if (tmp_host != host)
1568            OPENSSL_free(tmp_host);
1569        if (tmp_port != port)
1570            OPENSSL_free(tmp_port);
1571        if (!res) {
1572            BIO_printf(bio_err,
1573                       "%s: -connect argument or target parameter malformed or ambiguous\n",
1574                       prog);
1575            goto end;
1576        }
1577    }
1578
1579    if (bindstr != NULL) {
1580        int res;
1581        res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
1582                                 BIO_PARSE_PRIO_HOST);
1583        if (!res) {
1584            BIO_printf(bio_err,
1585                       "%s: -bind argument parameter malformed or ambiguous\n",
1586                       prog);
1587            goto end;
1588        }
1589    }
1590
1591#ifdef AF_UNIX
1592    if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1593        BIO_printf(bio_err,
1594                   "Can't use unix sockets and datagrams together\n");
1595        goto end;
1596    }
1597#endif
1598
1599#ifndef OPENSSL_NO_SCTP
1600    if (protocol == IPPROTO_SCTP) {
1601        if (socket_type != SOCK_DGRAM) {
1602            BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
1603            goto end;
1604        }
1605        /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
1606        socket_type = SOCK_STREAM;
1607    }
1608#endif
1609
1610#if !defined(OPENSSL_NO_NEXTPROTONEG)
1611    next_proto.status = -1;
1612    if (next_proto_neg_in) {
1613        next_proto.data =
1614            next_protos_parse(&next_proto.len, next_proto_neg_in);
1615        if (next_proto.data == NULL) {
1616            BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1617            goto end;
1618        }
1619    } else
1620        next_proto.data = NULL;
1621#endif
1622
1623    if (!app_passwd(passarg, NULL, &pass, NULL)) {
1624        BIO_printf(bio_err, "Error getting password\n");
1625        goto end;
1626    }
1627
1628    if (key_file == NULL)
1629        key_file = cert_file;
1630
1631    if (key_file != NULL) {
1632        key = load_key(key_file, key_format, 0, pass, e,
1633                       "client certificate private key file");
1634        if (key == NULL) {
1635            ERR_print_errors(bio_err);
1636            goto end;
1637        }
1638    }
1639
1640    if (cert_file != NULL) {
1641        cert = load_cert(cert_file, cert_format, "client certificate file");
1642        if (cert == NULL) {
1643            ERR_print_errors(bio_err);
1644            goto end;
1645        }
1646    }
1647
1648    if (chain_file != NULL) {
1649        if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
1650                        "client certificate chain"))
1651            goto end;
1652    }
1653
1654    if (crl_file != NULL) {
1655        X509_CRL *crl;
1656        crl = load_crl(crl_file, crl_format);
1657        if (crl == NULL) {
1658            BIO_puts(bio_err, "Error loading CRL\n");
1659            ERR_print_errors(bio_err);
1660            goto end;
1661        }
1662        crls = sk_X509_CRL_new_null();
1663        if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1664            BIO_puts(bio_err, "Error adding CRL\n");
1665            ERR_print_errors(bio_err);
1666            X509_CRL_free(crl);
1667            goto end;
1668        }
1669    }
1670
1671    if (!load_excert(&exc))
1672        goto end;
1673
1674    if (bio_c_out == NULL) {
1675        if (c_quiet && !c_debug) {
1676            bio_c_out = BIO_new(BIO_s_null());
1677            if (c_msg && bio_c_msg == NULL)
1678                bio_c_msg = dup_bio_out(FORMAT_TEXT);
1679        } else if (bio_c_out == NULL)
1680            bio_c_out = dup_bio_out(FORMAT_TEXT);
1681    }
1682#ifndef OPENSSL_NO_SRP
1683    if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1684        BIO_printf(bio_err, "Error getting password\n");
1685        goto end;
1686    }
1687#endif
1688
1689    ctx = SSL_CTX_new(meth);
1690    if (ctx == NULL) {
1691        ERR_print_errors(bio_err);
1692        goto end;
1693    }
1694
1695    SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
1696
1697    if (sdebug)
1698        ssl_ctx_security_debug(ctx, sdebug);
1699
1700    if (!config_ctx(cctx, ssl_args, ctx))
1701        goto end;
1702
1703    if (ssl_config != NULL) {
1704        if (SSL_CTX_config(ctx, ssl_config) == 0) {
1705            BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1706                       ssl_config);
1707            ERR_print_errors(bio_err);
1708            goto end;
1709        }
1710    }
1711
1712    if (min_version != 0
1713        && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1714        goto end;
1715    if (max_version != 0
1716        && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1717        goto end;
1718
1719    if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1720        BIO_printf(bio_err, "Error setting verify params\n");
1721        ERR_print_errors(bio_err);
1722        goto end;
1723    }
1724
1725    if (async) {
1726        SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1727    }
1728
1729    if (max_send_fragment > 0
1730        && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
1731        BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
1732                   prog, max_send_fragment);
1733        goto end;
1734    }
1735
1736    if (split_send_fragment > 0
1737        && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
1738        BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
1739                   prog, split_send_fragment);
1740        goto end;
1741    }
1742
1743    if (max_pipelines > 0
1744        && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
1745        BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
1746                   prog, max_pipelines);
1747        goto end;
1748    }
1749
1750    if (read_buf_len > 0) {
1751        SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1752    }
1753
1754    if (maxfraglen > 0
1755            && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
1756        BIO_printf(bio_err,
1757                   "%s: Max Fragment Length code %u is out of permitted values"
1758                   "\n", prog, maxfraglen);
1759        goto end;
1760    }
1761
1762    if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1763                         crls, crl_download)) {
1764        BIO_printf(bio_err, "Error loading store locations\n");
1765        ERR_print_errors(bio_err);
1766        goto end;
1767    }
1768    if (ReqCAfile != NULL) {
1769        STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
1770
1771        if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
1772            sk_X509_NAME_pop_free(nm, X509_NAME_free);
1773            BIO_printf(bio_err, "Error loading CA names\n");
1774            ERR_print_errors(bio_err);
1775            goto end;
1776        }
1777        SSL_CTX_set0_CA_list(ctx, nm);
1778    }
1779#ifndef OPENSSL_NO_ENGINE
1780    if (ssl_client_engine) {
1781        if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1782            BIO_puts(bio_err, "Error setting client auth engine\n");
1783            ERR_print_errors(bio_err);
1784            ENGINE_free(ssl_client_engine);
1785            goto end;
1786        }
1787        ENGINE_free(ssl_client_engine);
1788    }
1789#endif
1790
1791#ifndef OPENSSL_NO_PSK
1792    if (psk_key != NULL) {
1793        if (c_debug)
1794            BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1795        SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1796    }
1797#endif
1798    if (psksessf != NULL) {
1799        BIO *stmp = BIO_new_file(psksessf, "r");
1800
1801        if (stmp == NULL) {
1802            BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
1803            ERR_print_errors(bio_err);
1804            goto end;
1805        }
1806        psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1807        BIO_free(stmp);
1808        if (psksess == NULL) {
1809            BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
1810            ERR_print_errors(bio_err);
1811            goto end;
1812        }
1813    }
1814    if (psk_key != NULL || psksess != NULL)
1815        SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
1816
1817#ifndef OPENSSL_NO_SRTP
1818    if (srtp_profiles != NULL) {
1819        /* Returns 0 on success! */
1820        if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1821            BIO_printf(bio_err, "Error setting SRTP profile\n");
1822            ERR_print_errors(bio_err);
1823            goto end;
1824        }
1825    }
1826#endif
1827
1828    if (exc != NULL)
1829        ssl_ctx_set_excert(ctx, exc);
1830
1831#if !defined(OPENSSL_NO_NEXTPROTONEG)
1832    if (next_proto.data != NULL)
1833        SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1834#endif
1835    if (alpn_in) {
1836        size_t alpn_len;
1837        unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1838
1839        if (alpn == NULL) {
1840            BIO_printf(bio_err, "Error parsing -alpn argument\n");
1841            goto end;
1842        }
1843        /* Returns 0 on success! */
1844        if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1845            BIO_printf(bio_err, "Error setting ALPN\n");
1846            goto end;
1847        }
1848        OPENSSL_free(alpn);
1849    }
1850
1851    for (i = 0; i < serverinfo_count; i++) {
1852        if (!SSL_CTX_add_client_custom_ext(ctx,
1853                                           serverinfo_types[i],
1854                                           NULL, NULL, NULL,
1855                                           serverinfo_cli_parse_cb, NULL)) {
1856            BIO_printf(bio_err,
1857                       "Warning: Unable to add custom extension %u, skipping\n",
1858                       serverinfo_types[i]);
1859        }
1860    }
1861
1862    if (state)
1863        SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1864
1865#ifndef OPENSSL_NO_CT
1866    /* Enable SCT processing, without early connection termination */
1867    if (ct_validation &&
1868        !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1869        ERR_print_errors(bio_err);
1870        goto end;
1871    }
1872
1873    if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1874        if (ct_validation) {
1875            ERR_print_errors(bio_err);
1876            goto end;
1877        }
1878
1879        /*
1880         * If CT validation is not enabled, the log list isn't needed so don't
1881         * show errors or abort. We try to load it regardless because then we
1882         * can show the names of the logs any SCTs came from (SCTs may be seen
1883         * even with validation disabled).
1884         */
1885        ERR_clear_error();
1886    }
1887#endif
1888
1889    SSL_CTX_set_verify(ctx, verify, verify_callback);
1890
1891    if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1892        ERR_print_errors(bio_err);
1893        goto end;
1894    }
1895
1896    ssl_ctx_add_crls(ctx, crls, crl_download);
1897
1898    if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1899        goto end;
1900
1901    if (!noservername) {
1902        tlsextcbp.biodebug = bio_err;
1903        SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1904        SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1905    }
1906# ifndef OPENSSL_NO_SRP
1907    if (srp_arg.srplogin) {
1908        if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
1909            BIO_printf(bio_err, "Unable to set SRP username\n");
1910            goto end;
1911        }
1912        srp_arg.msg = c_msg;
1913        srp_arg.debug = c_debug;
1914        SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
1915        SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
1916        SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
1917        if (c_msg || c_debug || srp_arg.amp == 0)
1918            SSL_CTX_set_srp_verify_param_callback(ctx,
1919                                                  ssl_srp_verify_param_cb);
1920    }
1921# endif
1922
1923    if (dane_tlsa_domain != NULL) {
1924        if (SSL_CTX_dane_enable(ctx) <= 0) {
1925            BIO_printf(bio_err,
1926                       "%s: Error enabling DANE TLSA authentication.\n",
1927                       prog);
1928            ERR_print_errors(bio_err);
1929            goto end;
1930        }
1931    }
1932
1933    /*
1934     * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
1935     * come at any time. Therefore we use a callback to write out the session
1936     * when we know about it. This approach works for < TLSv1.3 as well.
1937     */
1938    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT
1939                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1940    SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
1941
1942    if (set_keylog_file(ctx, keylog_file))
1943        goto end;
1944
1945    con = SSL_new(ctx);
1946    if (con == NULL)
1947        goto end;
1948
1949    if (enable_pha)
1950        SSL_set_post_handshake_auth(con, 1);
1951
1952    if (sess_in != NULL) {
1953        SSL_SESSION *sess;
1954        BIO *stmp = BIO_new_file(sess_in, "r");
1955        if (stmp == NULL) {
1956            BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1957            ERR_print_errors(bio_err);
1958            goto end;
1959        }
1960        sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1961        BIO_free(stmp);
1962        if (sess == NULL) {
1963            BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1964            ERR_print_errors(bio_err);
1965            goto end;
1966        }
1967        if (!SSL_set_session(con, sess)) {
1968            BIO_printf(bio_err, "Can't set session\n");
1969            ERR_print_errors(bio_err);
1970            goto end;
1971        }
1972
1973        SSL_SESSION_free(sess);
1974    }
1975
1976    if (fallback_scsv)
1977        SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
1978
1979    if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
1980        if (servername == NULL)
1981            servername = (host == NULL) ? "localhost" : host;
1982        if (!SSL_set_tlsext_host_name(con, servername)) {
1983            BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
1984            ERR_print_errors(bio_err);
1985            goto end;
1986        }
1987    }
1988
1989    if (dane_tlsa_domain != NULL) {
1990        if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
1991            BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
1992                       "authentication.\n", prog);
1993            ERR_print_errors(bio_err);
1994            goto end;
1995        }
1996        if (dane_tlsa_rrset == NULL) {
1997            BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
1998                       "least one -dane_tlsa_rrdata option.\n", prog);
1999            goto end;
2000        }
2001        if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
2002            BIO_printf(bio_err, "%s: Failed to import any TLSA "
2003                       "records.\n", prog);
2004            goto end;
2005        }
2006        if (dane_ee_no_name)
2007            SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2008    } else if (dane_tlsa_rrset != NULL) {
2009        BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
2010                   "-dane_tlsa_domain option.\n", prog);
2011        goto end;
2012    }
2013
2014 re_start:
2015    if (init_client(&s, host, port, bindhost, bindport, socket_family,
2016                    socket_type, protocol) == 0) {
2017        BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
2018        BIO_closesocket(s);
2019        goto end;
2020    }
2021    BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
2022
2023    if (c_nbio) {
2024        if (!BIO_socket_nbio(s, 1)) {
2025            ERR_print_errors(bio_err);
2026            goto end;
2027        }
2028        BIO_printf(bio_c_out, "Turned on non blocking io\n");
2029    }
2030#ifndef OPENSSL_NO_DTLS
2031    if (isdtls) {
2032        union BIO_sock_info_u peer_info;
2033
2034#ifndef OPENSSL_NO_SCTP
2035        if (protocol == IPPROTO_SCTP)
2036            sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE);
2037        else
2038#endif
2039            sbio = BIO_new_dgram(s, BIO_NOCLOSE);
2040
2041        if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
2042            BIO_printf(bio_err, "memory allocation failure\n");
2043            BIO_closesocket(s);
2044            goto end;
2045        }
2046        if (!BIO_sock_info(s, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
2047            BIO_printf(bio_err, "getsockname:errno=%d\n",
2048                       get_last_socket_error());
2049            BIO_ADDR_free(peer_info.addr);
2050            BIO_closesocket(s);
2051            goto end;
2052        }
2053
2054        (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
2055        BIO_ADDR_free(peer_info.addr);
2056        peer_info.addr = NULL;
2057
2058        if (enable_timeouts) {
2059            timeout.tv_sec = 0;
2060            timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2061            BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2062
2063            timeout.tv_sec = 0;
2064            timeout.tv_usec = DGRAM_SND_TIMEOUT;
2065            BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2066        }
2067
2068        if (socket_mtu) {
2069            if (socket_mtu < DTLS_get_link_min_mtu(con)) {
2070                BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
2071                           DTLS_get_link_min_mtu(con));
2072                BIO_free(sbio);
2073                goto shut;
2074            }
2075            SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2076            if (!DTLS_set_link_mtu(con, socket_mtu)) {
2077                BIO_printf(bio_err, "Failed to set MTU\n");
2078                BIO_free(sbio);
2079                goto shut;
2080            }
2081        } else {
2082            /* want to do MTU discovery */
2083            BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2084        }
2085    } else
2086#endif /* OPENSSL_NO_DTLS */
2087        sbio = BIO_new_socket(s, BIO_NOCLOSE);
2088
2089    if (nbio_test) {
2090        BIO *test;
2091
2092        test = BIO_new(BIO_f_nbio_test());
2093        sbio = BIO_push(test, sbio);
2094    }
2095
2096    if (c_debug) {
2097        BIO_set_callback(sbio, bio_dump_callback);
2098        BIO_set_callback_arg(sbio, (char *)bio_c_out);
2099    }
2100    if (c_msg) {
2101#ifndef OPENSSL_NO_SSL_TRACE
2102        if (c_msg == 2)
2103            SSL_set_msg_callback(con, SSL_trace);
2104        else
2105#endif
2106            SSL_set_msg_callback(con, msg_cb);
2107        SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
2108    }
2109
2110    if (c_tlsextdebug) {
2111        SSL_set_tlsext_debug_callback(con, tlsext_cb);
2112        SSL_set_tlsext_debug_arg(con, bio_c_out);
2113    }
2114#ifndef OPENSSL_NO_OCSP
2115    if (c_status_req) {
2116        SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
2117        SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
2118        SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
2119    }
2120#endif
2121
2122    SSL_set_bio(con, sbio, sbio);
2123    SSL_set_connect_state(con);
2124
2125    /* ok, lets connect */
2126    if (fileno_stdin() > SSL_get_fd(con))
2127        width = fileno_stdin() + 1;
2128    else
2129        width = SSL_get_fd(con) + 1;
2130
2131    read_tty = 1;
2132    write_tty = 0;
2133    tty_on = 0;
2134    read_ssl = 1;
2135    write_ssl = 1;
2136
2137    cbuf_len = 0;
2138    cbuf_off = 0;
2139    sbuf_len = 0;
2140    sbuf_off = 0;
2141
2142    switch ((PROTOCOL_CHOICE) starttls_proto) {
2143    case PROTO_OFF:
2144        break;
2145    case PROTO_LMTP:
2146    case PROTO_SMTP:
2147        {
2148            /*
2149             * This is an ugly hack that does a lot of assumptions. We do
2150             * have to handle multi-line responses which may come in a single
2151             * packet or not. We therefore have to use BIO_gets() which does
2152             * need a buffering BIO. So during the initial chitchat we do
2153             * push a buffering BIO into the chain that is removed again
2154             * later on to not disturb the rest of the s_client operation.
2155             */
2156            int foundit = 0;
2157            BIO *fbio = BIO_new(BIO_f_buffer());
2158
2159            BIO_push(fbio, sbio);
2160            /* Wait for multi-line response to end from LMTP or SMTP */
2161            do {
2162                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2163            } while (mbuf_len > 3 && mbuf[3] == '-');
2164            if (protohost == NULL)
2165                protohost = "mail.example.com";
2166            if (starttls_proto == (int)PROTO_LMTP)
2167                BIO_printf(fbio, "LHLO %s\r\n", protohost);
2168            else
2169                BIO_printf(fbio, "EHLO %s\r\n", protohost);
2170            (void)BIO_flush(fbio);
2171            /*
2172             * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
2173             * response.
2174             */
2175            do {
2176                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2177                if (strstr(mbuf, "STARTTLS"))
2178                    foundit = 1;
2179            } while (mbuf_len > 3 && mbuf[3] == '-');
2180            (void)BIO_flush(fbio);
2181            BIO_pop(fbio);
2182            BIO_free(fbio);
2183            if (!foundit)
2184                BIO_printf(bio_err,
2185                           "Didn't find STARTTLS in server response,"
2186                           " trying anyway...\n");
2187            BIO_printf(sbio, "STARTTLS\r\n");
2188            BIO_read(sbio, sbuf, BUFSIZZ);
2189        }
2190        break;
2191    case PROTO_POP3:
2192        {
2193            BIO_read(sbio, mbuf, BUFSIZZ);
2194            BIO_printf(sbio, "STLS\r\n");
2195            mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
2196            if (mbuf_len < 0) {
2197                BIO_printf(bio_err, "BIO_read failed\n");
2198                goto end;
2199            }
2200        }
2201        break;
2202    case PROTO_IMAP:
2203        {
2204            int foundit = 0;
2205            BIO *fbio = BIO_new(BIO_f_buffer());
2206
2207            BIO_push(fbio, sbio);
2208            BIO_gets(fbio, mbuf, BUFSIZZ);
2209            /* STARTTLS command requires CAPABILITY... */
2210            BIO_printf(fbio, ". CAPABILITY\r\n");
2211            (void)BIO_flush(fbio);
2212            /* wait for multi-line CAPABILITY response */
2213            do {
2214                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2215                if (strstr(mbuf, "STARTTLS"))
2216                    foundit = 1;
2217            }
2218            while (mbuf_len > 3 && mbuf[0] != '.');
2219            (void)BIO_flush(fbio);
2220            BIO_pop(fbio);
2221            BIO_free(fbio);
2222            if (!foundit)
2223                BIO_printf(bio_err,
2224                           "Didn't find STARTTLS in server response,"
2225                           " trying anyway...\n");
2226            BIO_printf(sbio, ". STARTTLS\r\n");
2227            BIO_read(sbio, sbuf, BUFSIZZ);
2228        }
2229        break;
2230    case PROTO_FTP:
2231        {
2232            BIO *fbio = BIO_new(BIO_f_buffer());
2233
2234            BIO_push(fbio, sbio);
2235            /* wait for multi-line response to end from FTP */
2236            do {
2237                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2238            }
2239            while (mbuf_len > 3 && mbuf[3] == '-');
2240            (void)BIO_flush(fbio);
2241            BIO_pop(fbio);
2242            BIO_free(fbio);
2243            BIO_printf(sbio, "AUTH TLS\r\n");
2244            BIO_read(sbio, sbuf, BUFSIZZ);
2245        }
2246        break;
2247    case PROTO_XMPP:
2248    case PROTO_XMPP_SERVER:
2249        {
2250            int seen = 0;
2251            BIO_printf(sbio, "<stream:stream "
2252                       "xmlns:stream='http://etherx.jabber.org/streams' "
2253                       "xmlns='jabber:%s' to='%s' version='1.0'>",
2254                       starttls_proto == PROTO_XMPP ? "client" : "server",
2255                       protohost ? protohost : host);
2256            seen = BIO_read(sbio, mbuf, BUFSIZZ);
2257            if (seen < 0) {
2258                BIO_printf(bio_err, "BIO_read failed\n");
2259                goto end;
2260            }
2261            mbuf[seen] = '\0';
2262            while (!strstr
2263                   (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
2264                   && !strstr(mbuf,
2265                              "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
2266            {
2267                seen = BIO_read(sbio, mbuf, BUFSIZZ);
2268
2269                if (seen <= 0)
2270                    goto shut;
2271
2272                mbuf[seen] = '\0';
2273            }
2274            BIO_printf(sbio,
2275                       "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
2276            seen = BIO_read(sbio, sbuf, BUFSIZZ);
2277            if (seen < 0) {
2278                BIO_printf(bio_err, "BIO_read failed\n");
2279                goto shut;
2280            }
2281            sbuf[seen] = '\0';
2282            if (!strstr(sbuf, "<proceed"))
2283                goto shut;
2284            mbuf[0] = '\0';
2285        }
2286        break;
2287    case PROTO_TELNET:
2288        {
2289            static const unsigned char tls_do[] = {
2290                /* IAC    DO   START_TLS */
2291                   255,   253, 46
2292            };
2293            static const unsigned char tls_will[] = {
2294                /* IAC  WILL START_TLS */
2295                   255, 251, 46
2296            };
2297            static const unsigned char tls_follows[] = {
2298                /* IAC  SB   START_TLS FOLLOWS IAC  SE */
2299                   255, 250, 46,       1,      255, 240
2300            };
2301            int bytes;
2302
2303            /* Telnet server should demand we issue START_TLS */
2304            bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2305            if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
2306                goto shut;
2307            /* Agree to issue START_TLS and send the FOLLOWS sub-command */
2308            BIO_write(sbio, tls_will, 3);
2309            BIO_write(sbio, tls_follows, 6);
2310            (void)BIO_flush(sbio);
2311            /* Telnet server also sent the FOLLOWS sub-command */
2312            bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2313            if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2314                goto shut;
2315        }
2316        break;
2317    case PROTO_CONNECT:
2318        {
2319            enum {
2320                error_proto,     /* Wrong protocol, not even HTTP */
2321                error_connect,   /* CONNECT failed */
2322                success
2323            } foundit = error_connect;
2324            BIO *fbio = BIO_new(BIO_f_buffer());
2325
2326            BIO_push(fbio, sbio);
2327            BIO_printf(fbio, "CONNECT %s HTTP/1.0\r\n\r\n", connectstr);
2328            (void)BIO_flush(fbio);
2329            /*
2330             * The first line is the HTTP response.  According to RFC 7230,
2331             * it's formated exactly like this:
2332             *
2333             * HTTP/d.d ddd Reason text\r\n
2334             */
2335            mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2336            if (mbuf_len < (int)strlen("HTTP/1.0 200")) {
2337                BIO_printf(bio_err,
2338                           "%s: HTTP CONNECT failed, insufficient response "
2339                           "from proxy (got %d octets)\n", prog, mbuf_len);
2340                (void)BIO_flush(fbio);
2341                BIO_pop(fbio);
2342                BIO_free(fbio);
2343                goto shut;
2344            }
2345            if (mbuf[8] != ' ') {
2346                BIO_printf(bio_err,
2347                           "%s: HTTP CONNECT failed, incorrect response "
2348                           "from proxy\n", prog);
2349                foundit = error_proto;
2350            } else if (mbuf[9] != '2') {
2351                BIO_printf(bio_err, "%s: HTTP CONNECT failed: %s ", prog,
2352                           &mbuf[9]);
2353            } else {
2354                foundit = success;
2355            }
2356            if (foundit != error_proto) {
2357                /* Read past all following headers */
2358                do {
2359                    mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2360                } while (mbuf_len > 2);
2361            }
2362            (void)BIO_flush(fbio);
2363            BIO_pop(fbio);
2364            BIO_free(fbio);
2365            if (foundit != success) {
2366                goto shut;
2367            }
2368        }
2369        break;
2370    case PROTO_IRC:
2371        {
2372            int numeric;
2373            BIO *fbio = BIO_new(BIO_f_buffer());
2374
2375            BIO_push(fbio, sbio);
2376            BIO_printf(fbio, "STARTTLS\r\n");
2377            (void)BIO_flush(fbio);
2378            width = SSL_get_fd(con) + 1;
2379
2380            do {
2381                numeric = 0;
2382
2383                FD_ZERO(&readfds);
2384                openssl_fdset(SSL_get_fd(con), &readfds);
2385                timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2386                timeout.tv_usec = 0;
2387                /*
2388                 * If the IRCd doesn't respond within
2389                 * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2390                 * it doesn't support STARTTLS. Many IRCds
2391                 * will not give _any_ sort of response to a
2392                 * STARTTLS command when it's not supported.
2393                 */
2394                if (!BIO_get_buffer_num_lines(fbio)
2395                    && !BIO_pending(fbio)
2396                    && !BIO_pending(sbio)
2397                    && select(width, (void *)&readfds, NULL, NULL,
2398                              &timeout) < 1) {
2399                    BIO_printf(bio_err,
2400                               "Timeout waiting for response (%d seconds).\n",
2401                               S_CLIENT_IRC_READ_TIMEOUT);
2402                    break;
2403                }
2404
2405                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2406                if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2407                    break;
2408                /* :example.net 451 STARTTLS :You have not registered */
2409                /* :example.net 421 STARTTLS :Unknown command */
2410                if ((numeric == 451 || numeric == 421)
2411                    && strstr(mbuf, "STARTTLS") != NULL) {
2412                    BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2413                    break;
2414                }
2415                if (numeric == 691) {
2416                    BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2417                    ERR_print_errors(bio_err);
2418                    break;
2419                }
2420            } while (numeric != 670);
2421
2422            (void)BIO_flush(fbio);
2423            BIO_pop(fbio);
2424            BIO_free(fbio);
2425            if (numeric != 670) {
2426                BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2427                ret = 1;
2428                goto shut;
2429            }
2430        }
2431        break;
2432    case PROTO_MYSQL:
2433        {
2434            /* SSL request packet */
2435            static const unsigned char ssl_req[] = {
2436                /* payload_length,   sequence_id */
2437                   0x20, 0x00, 0x00, 0x01,
2438                /* payload */
2439                /* capability flags, CLIENT_SSL always set */
2440                   0x85, 0xae, 0x7f, 0x00,
2441                /* max-packet size */
2442                   0x00, 0x00, 0x00, 0x01,
2443                /* character set */
2444                   0x21,
2445                /* string[23] reserved (all [0]) */
2446                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2447                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2448                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2449            };
2450            int bytes = 0;
2451            int ssl_flg = 0x800;
2452            int pos;
2453            const unsigned char *packet = (const unsigned char *)sbuf;
2454
2455            /* Receiving Initial Handshake packet. */
2456            bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
2457            if (bytes < 0) {
2458                BIO_printf(bio_err, "BIO_read failed\n");
2459                goto shut;
2460            /* Packet length[3], Packet number[1] + minimum payload[17] */
2461            } else if (bytes < 21) {
2462                BIO_printf(bio_err, "MySQL packet too short.\n");
2463                goto shut;
2464            } else if (bytes != (4 + packet[0] +
2465                                 (packet[1] << 8) +
2466                                 (packet[2] << 16))) {
2467                BIO_printf(bio_err, "MySQL packet length does not match.\n");
2468                goto shut;
2469            /* protocol version[1] */
2470            } else if (packet[4] != 0xA) {
2471                BIO_printf(bio_err,
2472                           "Only MySQL protocol version 10 is supported.\n");
2473                goto shut;
2474            }
2475
2476            pos = 5;
2477            /* server version[string+NULL] */
2478            for (;;) {
2479                if (pos >= bytes) {
2480                    BIO_printf(bio_err, "Cannot confirm server version. ");
2481                    goto shut;
2482                } else if (packet[pos++] == '\0') {
2483                    break;
2484                }
2485            }
2486
2487            /* make sure we have at least 15 bytes left in the packet */
2488            if (pos + 15 > bytes) {
2489                BIO_printf(bio_err,
2490                           "MySQL server handshake packet is broken.\n");
2491                goto shut;
2492            }
2493
2494            pos += 12; /* skip over conn id[4] + SALT[8] */
2495            if (packet[pos++] != '\0') { /* verify filler */
2496                BIO_printf(bio_err,
2497                           "MySQL packet is broken.\n");
2498                goto shut;
2499            }
2500
2501            /* capability flags[2] */
2502            if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
2503                BIO_printf(bio_err, "MySQL server does not support SSL.\n");
2504                goto shut;
2505            }
2506
2507            /* Sending SSL Handshake packet. */
2508            BIO_write(sbio, ssl_req, sizeof(ssl_req));
2509            (void)BIO_flush(sbio);
2510        }
2511        break;
2512    case PROTO_POSTGRES:
2513        {
2514            static const unsigned char ssl_request[] = {
2515                /* Length        SSLRequest */
2516                   0, 0, 0, 8,   4, 210, 22, 47
2517            };
2518            int bytes;
2519
2520            /* Send SSLRequest packet */
2521            BIO_write(sbio, ssl_request, 8);
2522            (void)BIO_flush(sbio);
2523
2524            /* Reply will be a single S if SSL is enabled */
2525            bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2526            if (bytes != 1 || sbuf[0] != 'S')
2527                goto shut;
2528        }
2529        break;
2530    case PROTO_NNTP:
2531        {
2532            int foundit = 0;
2533            BIO *fbio = BIO_new(BIO_f_buffer());
2534
2535            BIO_push(fbio, sbio);
2536            BIO_gets(fbio, mbuf, BUFSIZZ);
2537            /* STARTTLS command requires CAPABILITIES... */
2538            BIO_printf(fbio, "CAPABILITIES\r\n");
2539            (void)BIO_flush(fbio);
2540            /* wait for multi-line CAPABILITIES response */
2541            do {
2542                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2543                if (strstr(mbuf, "STARTTLS"))
2544                    foundit = 1;
2545            } while (mbuf_len > 1 && mbuf[0] != '.');
2546            (void)BIO_flush(fbio);
2547            BIO_pop(fbio);
2548            BIO_free(fbio);
2549            if (!foundit)
2550                BIO_printf(bio_err,
2551                           "Didn't find STARTTLS in server response,"
2552                           " trying anyway...\n");
2553            BIO_printf(sbio, "STARTTLS\r\n");
2554            mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2555            if (mbuf_len < 0) {
2556                BIO_printf(bio_err, "BIO_read failed\n");
2557                goto end;
2558            }
2559            mbuf[mbuf_len] = '\0';
2560            if (strstr(mbuf, "382") == NULL) {
2561                BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2562                goto shut;
2563            }
2564        }
2565        break;
2566    case PROTO_SIEVE:
2567        {
2568            int foundit = 0;
2569            BIO *fbio = BIO_new(BIO_f_buffer());
2570
2571            BIO_push(fbio, sbio);
2572            /* wait for multi-line response to end from Sieve */
2573            do {
2574                mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2575                /*
2576                 * According to RFC 5804 § 1.7, capability
2577                 * is case-insensitive, make it uppercase
2578                 */
2579                if (mbuf_len > 1 && mbuf[0] == '"') {
2580                    make_uppercase(mbuf);
2581                    if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0)
2582                        foundit = 1;
2583                }
2584            } while (mbuf_len > 1 && mbuf[0] == '"');
2585            (void)BIO_flush(fbio);
2586            BIO_pop(fbio);
2587            BIO_free(fbio);
2588            if (!foundit)
2589                BIO_printf(bio_err,
2590                           "Didn't find STARTTLS in server response,"
2591                           " trying anyway...\n");
2592            BIO_printf(sbio, "STARTTLS\r\n");
2593            mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2594            if (mbuf_len < 0) {
2595                BIO_printf(bio_err, "BIO_read failed\n");
2596                goto end;
2597            }
2598            mbuf[mbuf_len] = '\0';
2599            if (mbuf_len < 2) {
2600                BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
2601                goto shut;
2602            }
2603            /*
2604             * According to RFC 5804 § 2.2, response codes are case-
2605             * insensitive, make it uppercase but preserve the response.
2606             */
2607            strncpy(sbuf, mbuf, 2);
2608            make_uppercase(sbuf);
2609            if (strncmp(sbuf, "OK", 2) != 0) {
2610                BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2611                goto shut;
2612            }
2613        }
2614        break;
2615    case PROTO_LDAP:
2616        {
2617            /* StartTLS Operation according to RFC 4511 */
2618            static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
2619                "[LDAPMessage]\n"
2620                "messageID=INTEGER:1\n"
2621                "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
2622                "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
2623            long errline = -1;
2624            char *genstr = NULL;
2625            int result = -1;
2626            ASN1_TYPE *atyp = NULL;
2627            BIO *ldapbio = BIO_new(BIO_s_mem());
2628            CONF *cnf = NCONF_new(NULL);
2629
2630            if (cnf == NULL) {
2631                BIO_free(ldapbio);
2632                goto end;
2633            }
2634            BIO_puts(ldapbio, ldap_tls_genconf);
2635            if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
2636                BIO_free(ldapbio);
2637                NCONF_free(cnf);
2638                if (errline <= 0) {
2639                    BIO_printf(bio_err, "NCONF_load_bio failed\n");
2640                    goto end;
2641                } else {
2642                    BIO_printf(bio_err, "Error on line %ld\n", errline);
2643                    goto end;
2644                }
2645            }
2646            BIO_free(ldapbio);
2647            genstr = NCONF_get_string(cnf, "default", "asn1");
2648            if (genstr == NULL) {
2649                NCONF_free(cnf);
2650                BIO_printf(bio_err, "NCONF_get_string failed\n");
2651                goto end;
2652            }
2653            atyp = ASN1_generate_nconf(genstr, cnf);
2654            if (atyp == NULL) {
2655                NCONF_free(cnf);
2656                BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
2657                goto end;
2658            }
2659            NCONF_free(cnf);
2660
2661            /* Send SSLRequest packet */
2662            BIO_write(sbio, atyp->value.sequence->data,
2663                      atyp->value.sequence->length);
2664            (void)BIO_flush(sbio);
2665            ASN1_TYPE_free(atyp);
2666
2667            mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
2668            if (mbuf_len < 0) {
2669                BIO_printf(bio_err, "BIO_read failed\n");
2670                goto end;
2671            }
2672            result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
2673            if (result < 0) {
2674                BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
2675                goto shut;
2676            } else if (result > 0) {
2677                BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
2678                           result);
2679                goto shut;
2680            }
2681            mbuf_len = 0;
2682        }
2683        break;
2684    }
2685
2686    if (early_data_file != NULL
2687            && ((SSL_get0_session(con) != NULL
2688                 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
2689                || (psksess != NULL
2690                    && SSL_SESSION_get_max_early_data(psksess) > 0))) {
2691        BIO *edfile = BIO_new_file(early_data_file, "r");
2692        size_t readbytes, writtenbytes;
2693        int finish = 0;
2694
2695        if (edfile == NULL) {
2696            BIO_printf(bio_err, "Cannot open early data file\n");
2697            goto shut;
2698        }
2699
2700        while (!finish) {
2701            if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
2702                finish = 1;
2703
2704            while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
2705                switch (SSL_get_error(con, 0)) {
2706                case SSL_ERROR_WANT_WRITE:
2707                case SSL_ERROR_WANT_ASYNC:
2708                case SSL_ERROR_WANT_READ:
2709                    /* Just keep trying - busy waiting */
2710                    continue;
2711                default:
2712                    BIO_printf(bio_err, "Error writing early data\n");
2713                    BIO_free(edfile);
2714                    ERR_print_errors(bio_err);
2715                    goto shut;
2716                }
2717            }
2718        }
2719
2720        BIO_free(edfile);
2721    }
2722
2723    for (;;) {
2724        FD_ZERO(&readfds);
2725        FD_ZERO(&writefds);
2726
2727        if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
2728            timeoutp = &timeout;
2729        else
2730            timeoutp = NULL;
2731
2732        if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
2733                && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
2734            in_init = 1;
2735            tty_on = 0;
2736        } else {
2737            tty_on = 1;
2738            if (in_init) {
2739                in_init = 0;
2740
2741                if (c_brief) {
2742                    BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2743                    print_ssl_summary(con);
2744                }
2745
2746                print_stuff(bio_c_out, con, full_log);
2747                if (full_log > 0)
2748                    full_log--;
2749
2750                if (starttls_proto) {
2751                    BIO_write(bio_err, mbuf, mbuf_len);
2752                    /* We don't need to know any more */
2753                    if (!reconnect)
2754                        starttls_proto = PROTO_OFF;
2755                }
2756
2757                if (reconnect) {
2758                    reconnect--;
2759                    BIO_printf(bio_c_out,
2760                               "drop connection and then reconnect\n");
2761                    do_ssl_shutdown(con);
2762                    SSL_set_connect_state(con);
2763                    BIO_closesocket(SSL_get_fd(con));
2764                    goto re_start;
2765                }
2766            }
2767        }
2768
2769        ssl_pending = read_ssl && SSL_has_pending(con);
2770
2771        if (!ssl_pending) {
2772#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2773            if (tty_on) {
2774                /*
2775                 * Note that select() returns when read _would not block_,
2776                 * and EOF satisfies that.  To avoid a CPU-hogging loop,
2777                 * set the flag so we exit.
2778                 */
2779                if (read_tty && !at_eof)
2780                    openssl_fdset(fileno_stdin(), &readfds);
2781#if !defined(OPENSSL_SYS_VMS)
2782                if (write_tty)
2783                    openssl_fdset(fileno_stdout(), &writefds);
2784#endif
2785            }
2786            if (read_ssl)
2787                openssl_fdset(SSL_get_fd(con), &readfds);
2788            if (write_ssl)
2789                openssl_fdset(SSL_get_fd(con), &writefds);
2790#else
2791            if (!tty_on || !write_tty) {
2792                if (read_ssl)
2793                    openssl_fdset(SSL_get_fd(con), &readfds);
2794                if (write_ssl)
2795                    openssl_fdset(SSL_get_fd(con), &writefds);
2796            }
2797#endif
2798
2799            /*
2800             * Note: under VMS with SOCKETSHR the second parameter is
2801             * currently of type (int *) whereas under other systems it is
2802             * (void *) if you don't have a cast it will choke the compiler:
2803             * if you do have a cast then you can either go for (int *) or
2804             * (void *).
2805             */
2806#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2807            /*
2808             * Under Windows/DOS we make the assumption that we can always
2809             * write to the tty: therefore if we need to write to the tty we
2810             * just fall through. Otherwise we timeout the select every
2811             * second and see if there are any keypresses. Note: this is a
2812             * hack, in a proper Windows application we wouldn't do this.
2813             */
2814            i = 0;
2815            if (!write_tty) {
2816                if (read_tty) {
2817                    tv.tv_sec = 1;
2818                    tv.tv_usec = 0;
2819                    i = select(width, (void *)&readfds, (void *)&writefds,
2820                               NULL, &tv);
2821                    if (!i && (!has_stdin_waiting() || !read_tty))
2822                        continue;
2823                } else
2824                    i = select(width, (void *)&readfds, (void *)&writefds,
2825                               NULL, timeoutp);
2826            }
2827#else
2828            i = select(width, (void *)&readfds, (void *)&writefds,
2829                       NULL, timeoutp);
2830#endif
2831            if (i < 0) {
2832                BIO_printf(bio_err, "bad select %d\n",
2833                           get_last_socket_error());
2834                goto shut;
2835            }
2836        }
2837
2838        if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
2839            BIO_printf(bio_err, "TIMEOUT occurred\n");
2840
2841        if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2842            k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2843            switch (SSL_get_error(con, k)) {
2844            case SSL_ERROR_NONE:
2845                cbuf_off += k;
2846                cbuf_len -= k;
2847                if (k <= 0)
2848                    goto end;
2849                /* we have done a  write(con,NULL,0); */
2850                if (cbuf_len <= 0) {
2851                    read_tty = 1;
2852                    write_ssl = 0;
2853                } else {        /* if (cbuf_len > 0) */
2854
2855                    read_tty = 0;
2856                    write_ssl = 1;
2857                }
2858                break;
2859            case SSL_ERROR_WANT_WRITE:
2860                BIO_printf(bio_c_out, "write W BLOCK\n");
2861                write_ssl = 1;
2862                read_tty = 0;
2863                break;
2864            case SSL_ERROR_WANT_ASYNC:
2865                BIO_printf(bio_c_out, "write A BLOCK\n");
2866                wait_for_async(con);
2867                write_ssl = 1;
2868                read_tty = 0;
2869                break;
2870            case SSL_ERROR_WANT_READ:
2871                BIO_printf(bio_c_out, "write R BLOCK\n");
2872                write_tty = 0;
2873                read_ssl = 1;
2874                write_ssl = 0;
2875                break;
2876            case SSL_ERROR_WANT_X509_LOOKUP:
2877                BIO_printf(bio_c_out, "write X BLOCK\n");
2878                break;
2879            case SSL_ERROR_ZERO_RETURN:
2880                if (cbuf_len != 0) {
2881                    BIO_printf(bio_c_out, "shutdown\n");
2882                    ret = 0;
2883                    goto shut;
2884                } else {
2885                    read_tty = 1;
2886                    write_ssl = 0;
2887                    break;
2888                }
2889
2890            case SSL_ERROR_SYSCALL:
2891                if ((k != 0) || (cbuf_len != 0)) {
2892                    BIO_printf(bio_err, "write:errno=%d\n",
2893                               get_last_socket_error());
2894                    goto shut;
2895                } else {
2896                    read_tty = 1;
2897                    write_ssl = 0;
2898                }
2899                break;
2900            case SSL_ERROR_WANT_ASYNC_JOB:
2901                /* This shouldn't ever happen in s_client - treat as an error */
2902            case SSL_ERROR_SSL:
2903                ERR_print_errors(bio_err);
2904                goto shut;
2905            }
2906        }
2907#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2908        /* Assume Windows/DOS/BeOS can always write */
2909        else if (!ssl_pending && write_tty)
2910#else
2911        else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2912#endif
2913        {
2914#ifdef CHARSET_EBCDIC
2915            ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2916#endif
2917            i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2918
2919            if (i <= 0) {
2920                BIO_printf(bio_c_out, "DONE\n");
2921                ret = 0;
2922                goto shut;
2923            }
2924
2925            sbuf_len -= i;
2926            sbuf_off += i;
2927            if (sbuf_len <= 0) {
2928                read_ssl = 1;
2929                write_tty = 0;
2930            }
2931        } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
2932#ifdef RENEG
2933            {
2934                static int iiii;
2935                if (++iiii == 52) {
2936                    SSL_renegotiate(con);
2937                    iiii = 0;
2938                }
2939            }
2940#endif
2941            k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
2942
2943            switch (SSL_get_error(con, k)) {
2944            case SSL_ERROR_NONE:
2945                if (k <= 0)
2946                    goto end;
2947                sbuf_off = 0;
2948                sbuf_len = k;
2949
2950                read_ssl = 0;
2951                write_tty = 1;
2952                break;
2953            case SSL_ERROR_WANT_ASYNC:
2954                BIO_printf(bio_c_out, "read A BLOCK\n");
2955                wait_for_async(con);
2956                write_tty = 0;
2957                read_ssl = 1;
2958                if ((read_tty == 0) && (write_ssl == 0))
2959                    write_ssl = 1;
2960                break;
2961            case SSL_ERROR_WANT_WRITE:
2962                BIO_printf(bio_c_out, "read W BLOCK\n");
2963                write_ssl = 1;
2964                read_tty = 0;
2965                break;
2966            case SSL_ERROR_WANT_READ:
2967                BIO_printf(bio_c_out, "read R BLOCK\n");
2968                write_tty = 0;
2969                read_ssl = 1;
2970                if ((read_tty == 0) && (write_ssl == 0))
2971                    write_ssl = 1;
2972                break;
2973            case SSL_ERROR_WANT_X509_LOOKUP:
2974                BIO_printf(bio_c_out, "read X BLOCK\n");
2975                break;
2976            case SSL_ERROR_SYSCALL:
2977                ret = get_last_socket_error();
2978                if (c_brief)
2979                    BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
2980                else
2981                    BIO_printf(bio_err, "read:errno=%d\n", ret);
2982                goto shut;
2983            case SSL_ERROR_ZERO_RETURN:
2984                BIO_printf(bio_c_out, "closed\n");
2985                ret = 0;
2986                goto shut;
2987            case SSL_ERROR_WANT_ASYNC_JOB:
2988                /* This shouldn't ever happen in s_client. Treat as an error */
2989            case SSL_ERROR_SSL:
2990                ERR_print_errors(bio_err);
2991                goto shut;
2992            }
2993        }
2994/* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
2995#if defined(OPENSSL_SYS_MSDOS)
2996        else if (has_stdin_waiting())
2997#else
2998        else if (FD_ISSET(fileno_stdin(), &readfds))
2999#endif
3000        {
3001            if (crlf) {
3002                int j, lf_num;
3003
3004                i = raw_read_stdin(cbuf, BUFSIZZ / 2);
3005                lf_num = 0;
3006                /* both loops are skipped when i <= 0 */
3007                for (j = 0; j < i; j++)
3008                    if (cbuf[j] == '\n')
3009                        lf_num++;
3010                for (j = i - 1; j >= 0; j--) {
3011                    cbuf[j + lf_num] = cbuf[j];
3012                    if (cbuf[j] == '\n') {
3013                        lf_num--;
3014                        i++;
3015                        cbuf[j + lf_num] = '\r';
3016                    }
3017                }
3018                assert(lf_num == 0);
3019            } else
3020                i = raw_read_stdin(cbuf, BUFSIZZ);
3021#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
3022            if (i == 0)
3023                at_eof = 1;
3024#endif
3025
3026            if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
3027                BIO_printf(bio_err, "DONE\n");
3028                ret = 0;
3029                goto shut;
3030            }
3031
3032            if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
3033                BIO_printf(bio_err, "RENEGOTIATING\n");
3034                SSL_renegotiate(con);
3035                cbuf_len = 0;
3036            }
3037
3038            if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' )
3039                    && cmdletters) {
3040                BIO_printf(bio_err, "KEYUPDATE\n");
3041                SSL_key_update(con,
3042                               cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED
3043                                              : SSL_KEY_UPDATE_NOT_REQUESTED);
3044                cbuf_len = 0;
3045            }
3046#ifndef OPENSSL_NO_HEARTBEATS
3047            else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) {
3048                BIO_printf(bio_err, "HEARTBEATING\n");
3049                SSL_heartbeat(con);
3050                cbuf_len = 0;
3051            }
3052#endif
3053            else {
3054                cbuf_len = i;
3055                cbuf_off = 0;
3056#ifdef CHARSET_EBCDIC
3057                ebcdic2ascii(cbuf, cbuf, i);
3058#endif
3059            }
3060
3061            write_ssl = 1;
3062            read_tty = 0;
3063        }
3064    }
3065
3066    ret = 0;
3067 shut:
3068    if (in_init)
3069        print_stuff(bio_c_out, con, full_log);
3070    do_ssl_shutdown(con);
3071
3072    /*
3073     * If we ended with an alert being sent, but still with data in the
3074     * network buffer to be read, then calling BIO_closesocket() will
3075     * result in a TCP-RST being sent. On some platforms (notably
3076     * Windows) then this will result in the peer immediately abandoning
3077     * the connection including any buffered alert data before it has
3078     * had a chance to be read. Shutting down the sending side first,
3079     * and then closing the socket sends TCP-FIN first followed by
3080     * TCP-RST. This seems to allow the peer to read the alert data.
3081     */
3082    shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
3083    /*
3084     * We just said we have nothing else to say, but it doesn't mean that
3085     * the other side has nothing. It's even recommended to consume incoming
3086     * data. [In testing context this ensures that alerts are passed on...]
3087     */
3088    timeout.tv_sec = 0;
3089    timeout.tv_usec = 500000;  /* some extreme round-trip */
3090    do {
3091        FD_ZERO(&readfds);
3092        openssl_fdset(s, &readfds);
3093    } while (select(s + 1, &readfds, NULL, NULL, &timeout) > 0
3094             && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
3095
3096    BIO_closesocket(SSL_get_fd(con));
3097 end:
3098    if (con != NULL) {
3099        if (prexit != 0)
3100            print_stuff(bio_c_out, con, 1);
3101        SSL_free(con);
3102    }
3103    SSL_SESSION_free(psksess);
3104#if !defined(OPENSSL_NO_NEXTPROTONEG)
3105    OPENSSL_free(next_proto.data);
3106#endif
3107    SSL_CTX_free(ctx);
3108    set_keylog_file(NULL, NULL);
3109    X509_free(cert);
3110    sk_X509_CRL_pop_free(crls, X509_CRL_free);
3111    EVP_PKEY_free(key);
3112    sk_X509_pop_free(chain, X509_free);
3113    OPENSSL_free(pass);
3114#ifndef OPENSSL_NO_SRP
3115    OPENSSL_free(srp_arg.srppassin);
3116#endif
3117    OPENSSL_free(connectstr);
3118    OPENSSL_free(bindstr);
3119    OPENSSL_free(host);
3120    OPENSSL_free(port);
3121    X509_VERIFY_PARAM_free(vpm);
3122    ssl_excert_free(exc);
3123    sk_OPENSSL_STRING_free(ssl_args);
3124    sk_OPENSSL_STRING_free(dane_tlsa_rrset);
3125    SSL_CONF_CTX_free(cctx);
3126    OPENSSL_clear_free(cbuf, BUFSIZZ);
3127    OPENSSL_clear_free(sbuf, BUFSIZZ);
3128    OPENSSL_clear_free(mbuf, BUFSIZZ);
3129    release_engine(e);
3130    BIO_free(bio_c_out);
3131    bio_c_out = NULL;
3132    BIO_free(bio_c_msg);
3133    bio_c_msg = NULL;
3134    return ret;
3135}
3136
3137static void print_stuff(BIO *bio, SSL *s, int full)
3138{
3139    X509 *peer = NULL;
3140    STACK_OF(X509) *sk;
3141    const SSL_CIPHER *c;
3142    int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
3143    long verify_result;
3144#ifndef OPENSSL_NO_COMP
3145    const COMP_METHOD *comp, *expansion;
3146#endif
3147    unsigned char *exportedkeymat;
3148#ifndef OPENSSL_NO_CT
3149    const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
3150#endif
3151
3152    if (full) {
3153        int got_a_chain = 0;
3154
3155        sk = SSL_get_peer_cert_chain(s);
3156        if (sk != NULL) {
3157            got_a_chain = 1;
3158
3159            BIO_printf(bio, "---\nCertificate chain\n");
3160            for (i = 0; i < sk_X509_num(sk); i++) {
3161                BIO_printf(bio, "%2d s:", i);
3162                X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt());
3163                BIO_puts(bio, "\n");
3164                BIO_printf(bio, "   i:");
3165                X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt());
3166                BIO_puts(bio, "\n");
3167                if (c_showcerts)
3168                    PEM_write_bio_X509(bio, sk_X509_value(sk, i));
3169            }
3170        }
3171
3172        BIO_printf(bio, "---\n");
3173        peer = SSL_get_peer_certificate(s);
3174        if (peer != NULL) {
3175            BIO_printf(bio, "Server certificate\n");
3176
3177            /* Redundant if we showed the whole chain */
3178            if (!(c_showcerts && got_a_chain))
3179                PEM_write_bio_X509(bio, peer);
3180            dump_cert_text(bio, peer);
3181        } else {
3182            BIO_printf(bio, "no peer certificate available\n");
3183        }
3184        print_ca_names(bio, s);
3185
3186        ssl_print_sigalgs(bio, s);
3187        ssl_print_tmp_key(bio, s);
3188
3189#ifndef OPENSSL_NO_CT
3190        /*
3191         * When the SSL session is anonymous, or resumed via an abbreviated
3192         * handshake, no SCTs are provided as part of the handshake.  While in
3193         * a resumed session SCTs may be present in the session's certificate,
3194         * no callbacks are invoked to revalidate these, and in any case that
3195         * set of SCTs may be incomplete.  Thus it makes little sense to
3196         * attempt to display SCTs from a resumed session's certificate, and of
3197         * course none are associated with an anonymous peer.
3198         */
3199        if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
3200            const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
3201            int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
3202
3203            BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
3204            if (sct_count > 0) {
3205                const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
3206
3207                BIO_printf(bio, "---\n");
3208                for (i = 0; i < sct_count; ++i) {
3209                    SCT *sct = sk_SCT_value(scts, i);
3210
3211                    BIO_printf(bio, "SCT validation status: %s\n",
3212                               SCT_validation_status_string(sct));
3213                    SCT_print(sct, bio, 0, log_store);
3214                    if (i < sct_count - 1)
3215                        BIO_printf(bio, "\n---\n");
3216                }
3217                BIO_printf(bio, "\n");
3218            }
3219        }
3220#endif
3221
3222        BIO_printf(bio,
3223                   "---\nSSL handshake has read %ju bytes "
3224                   "and written %ju bytes\n",
3225                   BIO_number_read(SSL_get_rbio(s)),
3226                   BIO_number_written(SSL_get_wbio(s)));
3227    }
3228    print_verify_detail(s, bio);
3229    BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
3230    c = SSL_get_current_cipher(s);
3231    BIO_printf(bio, "%s, Cipher is %s\n",
3232               SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
3233    if (peer != NULL) {
3234        EVP_PKEY *pktmp;
3235
3236        pktmp = X509_get0_pubkey(peer);
3237        BIO_printf(bio, "Server public key is %d bit\n",
3238                   EVP_PKEY_bits(pktmp));
3239    }
3240    BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
3241               SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
3242#ifndef OPENSSL_NO_COMP
3243    comp = SSL_get_current_compression(s);
3244    expansion = SSL_get_current_expansion(s);
3245    BIO_printf(bio, "Compression: %s\n",
3246               comp ? SSL_COMP_get_name(comp) : "NONE");
3247    BIO_printf(bio, "Expansion: %s\n",
3248               expansion ? SSL_COMP_get_name(expansion) : "NONE");
3249#endif
3250
3251#ifdef SSL_DEBUG
3252    {
3253        /* Print out local port of connection: useful for debugging */
3254        int sock;
3255        union BIO_sock_info_u info;
3256
3257        sock = SSL_get_fd(s);
3258        if ((info.addr = BIO_ADDR_new()) != NULL
3259            && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
3260            BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
3261                       ntohs(BIO_ADDR_rawport(info.addr)));
3262        }
3263        BIO_ADDR_free(info.addr);
3264    }
3265#endif
3266
3267#if !defined(OPENSSL_NO_NEXTPROTONEG)
3268    if (next_proto.status != -1) {
3269        const unsigned char *proto;
3270        unsigned int proto_len;
3271        SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
3272        BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
3273        BIO_write(bio, proto, proto_len);
3274        BIO_write(bio, "\n", 1);
3275    }
3276#endif
3277    {
3278        const unsigned char *proto;
3279        unsigned int proto_len;
3280        SSL_get0_alpn_selected(s, &proto, &proto_len);
3281        if (proto_len > 0) {
3282            BIO_printf(bio, "ALPN protocol: ");
3283            BIO_write(bio, proto, proto_len);
3284            BIO_write(bio, "\n", 1);
3285        } else
3286            BIO_printf(bio, "No ALPN negotiated\n");
3287    }
3288
3289#ifndef OPENSSL_NO_SRTP
3290    {
3291        SRTP_PROTECTION_PROFILE *srtp_profile =
3292            SSL_get_selected_srtp_profile(s);
3293
3294        if (srtp_profile)
3295            BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
3296                       srtp_profile->name);
3297    }
3298#endif
3299
3300    if (istls13) {
3301        switch (SSL_get_early_data_status(s)) {
3302        case SSL_EARLY_DATA_NOT_SENT:
3303            BIO_printf(bio, "Early data was not sent\n");
3304            break;
3305
3306        case SSL_EARLY_DATA_REJECTED:
3307            BIO_printf(bio, "Early data was rejected\n");
3308            break;
3309
3310        case SSL_EARLY_DATA_ACCEPTED:
3311            BIO_printf(bio, "Early data was accepted\n");
3312            break;
3313
3314        }
3315
3316        /*
3317         * We also print the verify results when we dump session information,
3318         * but in TLSv1.3 we may not get that right away (or at all) depending
3319         * on when we get a NewSessionTicket. Therefore we print it now as well.
3320         */
3321        verify_result = SSL_get_verify_result(s);
3322        BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
3323                   X509_verify_cert_error_string(verify_result));
3324    } else {
3325        /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
3326        SSL_SESSION_print(bio, SSL_get_session(s));
3327    }
3328
3329    if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
3330        BIO_printf(bio, "Keying material exporter:\n");
3331        BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
3332        BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
3333        exportedkeymat = app_malloc(keymatexportlen, "export key");
3334        if (!SSL_export_keying_material(s, exportedkeymat,
3335                                        keymatexportlen,
3336                                        keymatexportlabel,
3337                                        strlen(keymatexportlabel),
3338                                        NULL, 0, 0)) {
3339            BIO_printf(bio, "    Error\n");
3340        } else {
3341            BIO_printf(bio, "    Keying material: ");
3342            for (i = 0; i < keymatexportlen; i++)
3343                BIO_printf(bio, "%02X", exportedkeymat[i]);
3344            BIO_printf(bio, "\n");
3345        }
3346        OPENSSL_free(exportedkeymat);
3347    }
3348    BIO_printf(bio, "---\n");
3349    X509_free(peer);
3350    /* flush, or debugging output gets mixed with http response */
3351    (void)BIO_flush(bio);
3352}
3353
3354# ifndef OPENSSL_NO_OCSP
3355static int ocsp_resp_cb(SSL *s, void *arg)
3356{
3357    const unsigned char *p;
3358    int len;
3359    OCSP_RESPONSE *rsp;
3360    len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3361    BIO_puts(arg, "OCSP response: ");
3362    if (p == NULL) {
3363        BIO_puts(arg, "no response sent\n");
3364        return 1;
3365    }
3366    rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3367    if (rsp == NULL) {
3368        BIO_puts(arg, "response parse error\n");
3369        BIO_dump_indent(arg, (char *)p, len, 4);
3370        return 0;
3371    }
3372    BIO_puts(arg, "\n======================================\n");
3373    OCSP_RESPONSE_print(arg, rsp, 0);
3374    BIO_puts(arg, "======================================\n");
3375    OCSP_RESPONSE_free(rsp);
3376    return 1;
3377}
3378# endif
3379
3380static int ldap_ExtendedResponse_parse(const char *buf, long rem)
3381{
3382    const unsigned char *cur, *end;
3383    long len;
3384    int tag, xclass, inf, ret = -1;
3385
3386    cur = (const unsigned char *)buf;
3387    end = cur + rem;
3388
3389    /*
3390     * From RFC 4511:
3391     *
3392     *    LDAPMessage ::= SEQUENCE {
3393     *         messageID       MessageID,
3394     *         protocolOp      CHOICE {
3395     *              ...
3396     *              extendedResp          ExtendedResponse,
3397     *              ... },
3398     *         controls       [0] Controls OPTIONAL }
3399     *
3400     *    ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
3401     *         COMPONENTS OF LDAPResult,
3402     *         responseName     [10] LDAPOID OPTIONAL,
3403     *         responseValue    [11] OCTET STRING OPTIONAL }
3404     *
3405     *    LDAPResult ::= SEQUENCE {
3406     *         resultCode         ENUMERATED {
3407     *              success                      (0),
3408     *              ...
3409     *              other                        (80),
3410     *              ...  },
3411     *         matchedDN          LDAPDN,
3412     *         diagnosticMessage  LDAPString,
3413     *         referral           [3] Referral OPTIONAL }
3414     */
3415
3416    /* pull SEQUENCE */
3417    inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3418    if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE ||
3419        (rem = end - cur, len > rem)) {
3420        BIO_printf(bio_err, "Unexpected LDAP response\n");
3421        goto end;
3422    }
3423
3424    rem = len;  /* ensure that we don't overstep the SEQUENCE */
3425
3426    /* pull MessageID */
3427    inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3428    if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER ||
3429        (rem = end - cur, len > rem)) {
3430        BIO_printf(bio_err, "No MessageID\n");
3431        goto end;
3432    }
3433
3434    cur += len; /* shall we check for MessageId match or just skip? */
3435
3436    /* pull [APPLICATION 24] */
3437    rem = end - cur;
3438    inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3439    if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION ||
3440        tag != 24) {
3441        BIO_printf(bio_err, "Not ExtendedResponse\n");
3442        goto end;
3443    }
3444
3445    /* pull resultCode */
3446    rem = end - cur;
3447    inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
3448    if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 ||
3449        (rem = end - cur, len > rem)) {
3450        BIO_printf(bio_err, "Not LDAPResult\n");
3451        goto end;
3452    }
3453
3454    /* len should always be one, but just in case... */
3455    for (ret = 0, inf = 0; inf < len; inf++) {
3456        ret <<= 8;
3457        ret |= cur[inf];
3458    }
3459    /* There is more data, but we don't care... */
3460 end:
3461    return ret;
3462}
3463
3464#endif                          /* OPENSSL_NO_SOCK */
Note: See TracBrowser for help on using the repository browser.