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