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