Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/apps/s_client.c

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