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