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