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