VirtualBox

source: vbox/trunk/src/libs/openssl-3.3.2/apps/s_client.c

Last change on this file was 108206, checked in by vboxsync, 3 months ago

openssl-3.3.2: Exported all files to OSE and removed .scm-settings ​bugref:10757

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette