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