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