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