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