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