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