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