Update copyright year
[oweals/openssl.git] / ssl / ssl_lib.c
1 /*
2  * Copyright 1995-2018 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 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  * ECC cipher suite support in OpenSSL originally developed by
13  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
14  */
15 /* ====================================================================
16  * Copyright 2005 Nokia. All rights reserved.
17  *
18  * The portions of the attached software ("Contribution") is developed by
19  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
20  * license.
21  *
22  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
23  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
24  * support (see RFC 4279) to OpenSSL.
25  *
26  * No patent licenses or other rights except those expressly stated in
27  * the OpenSSL open source license shall be deemed granted or received
28  * expressly, by implication, estoppel, or otherwise.
29  *
30  * No assurances are provided by Nokia that the Contribution does not
31  * infringe the patent or other intellectual property rights of any third
32  * party or that the license provides you with all the necessary rights
33  * to make use of the Contribution.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
36  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
37  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
38  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
39  * OTHERWISE.
40  */
41
42 #include <assert.h>
43 #include <stdio.h>
44 #include "ssl_locl.h"
45 #include <openssl/objects.h>
46 #include <openssl/lhash.h>
47 #include <openssl/x509v3.h>
48 #include <openssl/rand.h>
49 #include <openssl/ocsp.h>
50 #include <openssl/dh.h>
51 #include <openssl/engine.h>
52 #include <openssl/async.h>
53 #include <openssl/ct.h>
54
55 const char SSL_version_str[] = OPENSSL_VERSION_TEXT;
56
57 static int ssl_undefined_function_1(SSL *ssl, SSL3_RECORD *r, unsigned int s,
58                                     int t)
59 {
60     (void)r;
61     (void)s;
62     (void)t;
63     return ssl_undefined_function(ssl);
64 }
65
66 static int ssl_undefined_function_2(SSL *ssl, SSL3_RECORD *r, unsigned char *s,
67                                     int t)
68 {
69     (void)r;
70     (void)s;
71     (void)t;
72     return ssl_undefined_function(ssl);
73 }
74
75 static int ssl_undefined_function_3(SSL *ssl, unsigned char *r,
76                                     unsigned char *s, int t)
77 {
78     (void)r;
79     (void)s;
80     (void)t;
81     return ssl_undefined_function(ssl);
82 }
83
84 static int ssl_undefined_function_4(SSL *ssl, int r)
85 {
86     (void)r;
87     return ssl_undefined_function(ssl);
88 }
89
90 static int ssl_undefined_function_5(SSL *ssl, const char *r, int s,
91                                     unsigned char *t)
92 {
93     (void)r;
94     (void)s;
95     (void)t;
96     return ssl_undefined_function(ssl);
97 }
98
99 static int ssl_undefined_function_6(int r)
100 {
101     (void)r;
102     return ssl_undefined_function(NULL);
103 }
104
105 static int ssl_undefined_function_7(SSL *ssl, unsigned char *r, size_t s,
106                                     const char *t, size_t u,
107                                     const unsigned char *v, size_t w, int x)
108 {
109     (void)r;
110     (void)s;
111     (void)t;
112     (void)u;
113     (void)v;
114     (void)w;
115     (void)x;
116     return ssl_undefined_function(ssl);
117 }
118
119 SSL3_ENC_METHOD ssl3_undef_enc_method = {
120     ssl_undefined_function_1,
121     ssl_undefined_function_2,
122     ssl_undefined_function,
123     ssl_undefined_function_3,
124     ssl_undefined_function_4,
125     ssl_undefined_function_5,
126     0,                          /* finish_mac_length */
127     NULL,                       /* client_finished_label */
128     0,                          /* client_finished_label_len */
129     NULL,                       /* server_finished_label */
130     0,                          /* server_finished_label_len */
131     ssl_undefined_function_6,
132     ssl_undefined_function_7,
133 };
134
135 struct ssl_async_args {
136     SSL *s;
137     void *buf;
138     int num;
139     enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
140     union {
141         int (*func_read) (SSL *, void *, int);
142         int (*func_write) (SSL *, const void *, int);
143         int (*func_other) (SSL *);
144     } f;
145 };
146
147 static const struct {
148     uint8_t mtype;
149     uint8_t ord;
150     int nid;
151 } dane_mds[] = {
152     {
153         DANETLS_MATCHING_FULL, 0, NID_undef
154     },
155     {
156         DANETLS_MATCHING_2256, 1, NID_sha256
157     },
158     {
159         DANETLS_MATCHING_2512, 2, NID_sha512
160     },
161 };
162
163 static int dane_ctx_enable(struct dane_ctx_st *dctx)
164 {
165     const EVP_MD **mdevp;
166     uint8_t *mdord;
167     uint8_t mdmax = DANETLS_MATCHING_LAST;
168     int n = ((int)mdmax) + 1;   /* int to handle PrivMatch(255) */
169     size_t i;
170
171     if (dctx->mdevp != NULL)
172         return 1;
173
174     mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
175     mdord = OPENSSL_zalloc(n * sizeof(*mdord));
176
177     if (mdord == NULL || mdevp == NULL) {
178         OPENSSL_free(mdord);
179         OPENSSL_free(mdevp);
180         SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
181         return 0;
182     }
183
184     /* Install default entries */
185     for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
186         const EVP_MD *md;
187
188         if (dane_mds[i].nid == NID_undef ||
189             (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
190             continue;
191         mdevp[dane_mds[i].mtype] = md;
192         mdord[dane_mds[i].mtype] = dane_mds[i].ord;
193     }
194
195     dctx->mdevp = mdevp;
196     dctx->mdord = mdord;
197     dctx->mdmax = mdmax;
198
199     return 1;
200 }
201
202 static void dane_ctx_final(struct dane_ctx_st *dctx)
203 {
204     OPENSSL_free(dctx->mdevp);
205     dctx->mdevp = NULL;
206
207     OPENSSL_free(dctx->mdord);
208     dctx->mdord = NULL;
209     dctx->mdmax = 0;
210 }
211
212 static void tlsa_free(danetls_record *t)
213 {
214     if (t == NULL)
215         return;
216     OPENSSL_free(t->data);
217     EVP_PKEY_free(t->spki);
218     OPENSSL_free(t);
219 }
220
221 static void dane_final(SSL_DANE *dane)
222 {
223     sk_danetls_record_pop_free(dane->trecs, tlsa_free);
224     dane->trecs = NULL;
225
226     sk_X509_pop_free(dane->certs, X509_free);
227     dane->certs = NULL;
228
229     X509_free(dane->mcert);
230     dane->mcert = NULL;
231     dane->mtlsa = NULL;
232     dane->mdpth = -1;
233     dane->pdpth = -1;
234 }
235
236 /*
237  * dane_copy - Copy dane configuration, sans verification state.
238  */
239 static int ssl_dane_dup(SSL *to, SSL *from)
240 {
241     int num;
242     int i;
243
244     if (!DANETLS_ENABLED(&from->dane))
245         return 1;
246
247     dane_final(&to->dane);
248     to->dane.flags = from->dane.flags;
249     to->dane.dctx = &to->ctx->dane;
250     to->dane.trecs = sk_danetls_record_new_null();
251
252     if (to->dane.trecs == NULL) {
253         SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
254         return 0;
255     }
256
257     num = sk_danetls_record_num(from->dane.trecs);
258     for (i = 0; i < num; ++i) {
259         danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
260
261         if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
262                               t->data, t->dlen) <= 0)
263             return 0;
264     }
265     return 1;
266 }
267
268 static int dane_mtype_set(struct dane_ctx_st *dctx,
269                           const EVP_MD *md, uint8_t mtype, uint8_t ord)
270 {
271     int i;
272
273     if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
274         SSLerr(SSL_F_DANE_MTYPE_SET, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
275         return 0;
276     }
277
278     if (mtype > dctx->mdmax) {
279         const EVP_MD **mdevp;
280         uint8_t *mdord;
281         int n = ((int)mtype) + 1;
282
283         mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
284         if (mdevp == NULL) {
285             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
286             return -1;
287         }
288         dctx->mdevp = mdevp;
289
290         mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
291         if (mdord == NULL) {
292             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
293             return -1;
294         }
295         dctx->mdord = mdord;
296
297         /* Zero-fill any gaps */
298         for (i = dctx->mdmax + 1; i < mtype; ++i) {
299             mdevp[i] = NULL;
300             mdord[i] = 0;
301         }
302
303         dctx->mdmax = mtype;
304     }
305
306     dctx->mdevp[mtype] = md;
307     /* Coerce ordinal of disabled matching types to 0 */
308     dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
309
310     return 1;
311 }
312
313 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
314 {
315     if (mtype > dane->dctx->mdmax)
316         return NULL;
317     return dane->dctx->mdevp[mtype];
318 }
319
320 static int dane_tlsa_add(SSL_DANE *dane,
321                          uint8_t usage,
322                          uint8_t selector,
323                          uint8_t mtype, unsigned const char *data, size_t dlen)
324 {
325     danetls_record *t;
326     const EVP_MD *md = NULL;
327     int ilen = (int)dlen;
328     int i;
329     int num;
330
331     if (dane->trecs == NULL) {
332         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
333         return -1;
334     }
335
336     if (ilen < 0 || dlen != (size_t)ilen) {
337         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
338         return 0;
339     }
340
341     if (usage > DANETLS_USAGE_LAST) {
342         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
343         return 0;
344     }
345
346     if (selector > DANETLS_SELECTOR_LAST) {
347         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
348         return 0;
349     }
350
351     if (mtype != DANETLS_MATCHING_FULL) {
352         md = tlsa_md_get(dane, mtype);
353         if (md == NULL) {
354             SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
355             return 0;
356         }
357     }
358
359     if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
360         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
361         return 0;
362     }
363     if (!data) {
364         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
365         return 0;
366     }
367
368     if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
369         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
370         return -1;
371     }
372
373     t->usage = usage;
374     t->selector = selector;
375     t->mtype = mtype;
376     t->data = OPENSSL_malloc(ilen);
377     if (t->data == NULL) {
378         tlsa_free(t);
379         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
380         return -1;
381     }
382     memcpy(t->data, data, ilen);
383     t->dlen = ilen;
384
385     /* Validate and cache full certificate or public key */
386     if (mtype == DANETLS_MATCHING_FULL) {
387         const unsigned char *p = data;
388         X509 *cert = NULL;
389         EVP_PKEY *pkey = NULL;
390
391         switch (selector) {
392         case DANETLS_SELECTOR_CERT:
393             if (!d2i_X509(&cert, &p, dlen) || p < data ||
394                 dlen != (size_t)(p - data)) {
395                 tlsa_free(t);
396                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
397                 return 0;
398             }
399             if (X509_get0_pubkey(cert) == NULL) {
400                 tlsa_free(t);
401                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
402                 return 0;
403             }
404
405             if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
406                 X509_free(cert);
407                 break;
408             }
409
410             /*
411              * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
412              * records that contain full certificates of trust-anchors that are
413              * not present in the wire chain.  For usage PKIX-TA(0), we augment
414              * the chain with untrusted Full(0) certificates from DNS, in case
415              * they are missing from the chain.
416              */
417             if ((dane->certs == NULL &&
418                  (dane->certs = sk_X509_new_null()) == NULL) ||
419                 !sk_X509_push(dane->certs, cert)) {
420                 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
421                 X509_free(cert);
422                 tlsa_free(t);
423                 return -1;
424             }
425             break;
426
427         case DANETLS_SELECTOR_SPKI:
428             if (!d2i_PUBKEY(&pkey, &p, dlen) || p < data ||
429                 dlen != (size_t)(p - data)) {
430                 tlsa_free(t);
431                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
432                 return 0;
433             }
434
435             /*
436              * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
437              * records that contain full bare keys of trust-anchors that are
438              * not present in the wire chain.
439              */
440             if (usage == DANETLS_USAGE_DANE_TA)
441                 t->spki = pkey;
442             else
443                 EVP_PKEY_free(pkey);
444             break;
445         }
446     }
447
448     /*-
449      * Find the right insertion point for the new record.
450      *
451      * See crypto/x509/x509_vfy.c.  We sort DANE-EE(3) records first, so that
452      * they can be processed first, as they require no chain building, and no
453      * expiration or hostname checks.  Because DANE-EE(3) is numerically
454      * largest, this is accomplished via descending sort by "usage".
455      *
456      * We also sort in descending order by matching ordinal to simplify
457      * the implementation of digest agility in the verification code.
458      *
459      * The choice of order for the selector is not significant, so we
460      * use the same descending order for consistency.
461      */
462     num = sk_danetls_record_num(dane->trecs);
463     for (i = 0; i < num; ++i) {
464         danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
465
466         if (rec->usage > usage)
467             continue;
468         if (rec->usage < usage)
469             break;
470         if (rec->selector > selector)
471             continue;
472         if (rec->selector < selector)
473             break;
474         if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
475             continue;
476         break;
477     }
478
479     if (!sk_danetls_record_insert(dane->trecs, t, i)) {
480         tlsa_free(t);
481         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
482         return -1;
483     }
484     dane->umask |= DANETLS_USAGE_BIT(usage);
485
486     return 1;
487 }
488
489 /*
490  * Return 0 if there is only one version configured and it was disabled
491  * at configure time.  Return 1 otherwise.
492  */
493 static int ssl_check_allowed_versions(int min_version, int max_version)
494 {
495     int minisdtls = 0, maxisdtls = 0;
496
497     /* Figure out if we're doing DTLS versions or TLS versions */
498     if (min_version == DTLS1_BAD_VER
499         || min_version >> 8 == DTLS1_VERSION_MAJOR)
500         minisdtls = 1;
501     if (max_version == DTLS1_BAD_VER
502         || max_version >> 8 == DTLS1_VERSION_MAJOR)
503         maxisdtls = 1;
504     /* A wildcard version of 0 could be DTLS or TLS. */
505     if ((minisdtls && !maxisdtls && max_version != 0)
506         || (maxisdtls && !minisdtls && min_version != 0)) {
507         /* Mixing DTLS and TLS versions will lead to sadness; deny it. */
508         return 0;
509     }
510
511     if (minisdtls || maxisdtls) {
512         /* Do DTLS version checks. */
513         if (min_version == 0)
514             /* Ignore DTLS1_BAD_VER */
515             min_version = DTLS1_VERSION;
516         if (max_version == 0)
517             max_version = DTLS1_2_VERSION;
518 #ifdef OPENSSL_NO_DTLS1_2
519         if (max_version == DTLS1_2_VERSION)
520             max_version = DTLS1_VERSION;
521 #endif
522 #ifdef OPENSSL_NO_DTLS1
523         if (min_version == DTLS1_VERSION)
524             min_version = DTLS1_2_VERSION;
525 #endif
526         /* Done massaging versions; do the check. */
527         if (0
528 #ifdef OPENSSL_NO_DTLS1
529             || (DTLS_VERSION_GE(min_version, DTLS1_VERSION)
530                 && DTLS_VERSION_GE(DTLS1_VERSION, max_version))
531 #endif
532 #ifdef OPENSSL_NO_DTLS1_2
533             || (DTLS_VERSION_GE(min_version, DTLS1_2_VERSION)
534                 && DTLS_VERSION_GE(DTLS1_2_VERSION, max_version))
535 #endif
536             )
537             return 0;
538     } else {
539         /* Regular TLS version checks. */
540         if (min_version == 0)
541             min_version = SSL3_VERSION;
542         if (max_version == 0)
543             max_version = TLS1_2_VERSION;
544 #ifdef OPENSSL_NO_TLS1_2
545         if (max_version == TLS1_2_VERSION)
546             max_version = TLS1_1_VERSION;
547 #endif
548 #ifdef OPENSSL_NO_TLS1_1
549         if (max_version == TLS1_1_VERSION)
550             max_version = TLS1_VERSION;
551 #endif
552 #ifdef OPENSSL_NO_TLS1
553         if (max_version == TLS1_VERSION)
554             max_version = SSL3_VERSION;
555 #endif
556 #ifdef OPENSSL_NO_SSL3
557         if (min_version == SSL3_VERSION)
558             min_version = TLS1_VERSION;
559 #endif
560 #ifdef OPENSSL_NO_TLS1
561         if (min_version == TLS1_VERSION)
562             min_version = TLS1_1_VERSION;
563 #endif
564 #ifdef OPENSSL_NO_TLS1_1
565         if (min_version == TLS1_1_VERSION)
566             min_version = TLS1_2_VERSION;
567 #endif
568         /* Done massaging versions; do the check. */
569         if (0
570 #ifdef OPENSSL_NO_SSL3
571             || (min_version <= SSL3_VERSION && SSL3_VERSION <= max_version)
572 #endif
573 #ifdef OPENSSL_NO_TLS1
574             || (min_version <= TLS1_VERSION && TLS1_VERSION <= max_version)
575 #endif
576 #ifdef OPENSSL_NO_TLS1_1
577             || (min_version <= TLS1_1_VERSION && TLS1_1_VERSION <= max_version)
578 #endif
579 #ifdef OPENSSL_NO_TLS1_2
580             || (min_version <= TLS1_2_VERSION && TLS1_2_VERSION <= max_version)
581 #endif
582             )
583             return 0;
584     }
585     return 1;
586 }
587
588 static void clear_ciphers(SSL *s)
589 {
590     /* clear the current cipher */
591     ssl_clear_cipher_ctx(s);
592     ssl_clear_hash_ctx(&s->read_hash);
593     ssl_clear_hash_ctx(&s->write_hash);
594 }
595
596 int SSL_clear(SSL *s)
597 {
598     if (s->method == NULL) {
599         SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
600         return (0);
601     }
602
603     if (ssl_clear_bad_session(s)) {
604         SSL_SESSION_free(s->session);
605         s->session = NULL;
606     }
607
608     s->error = 0;
609     s->hit = 0;
610     s->shutdown = 0;
611
612     if (s->renegotiate) {
613         SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
614         return 0;
615     }
616
617     ossl_statem_clear(s);
618
619     s->version = s->method->version;
620     s->client_version = s->version;
621     s->rwstate = SSL_NOTHING;
622
623     BUF_MEM_free(s->init_buf);
624     s->init_buf = NULL;
625     clear_ciphers(s);
626     s->first_packet = 0;
627
628     /* Reset DANE verification result state */
629     s->dane.mdpth = -1;
630     s->dane.pdpth = -1;
631     X509_free(s->dane.mcert);
632     s->dane.mcert = NULL;
633     s->dane.mtlsa = NULL;
634
635     /* Clear the verification result peername */
636     X509_VERIFY_PARAM_move_peername(s->param, NULL);
637
638     /*
639      * Check to see if we were changed into a different method, if so, revert
640      * back if we are not doing session-id reuse.
641      */
642     if (!ossl_statem_get_in_handshake(s) && (s->session == NULL)
643         && (s->method != s->ctx->method)) {
644         s->method->ssl_free(s);
645         s->method = s->ctx->method;
646         if (!s->method->ssl_new(s))
647             return (0);
648     } else
649         s->method->ssl_clear(s);
650
651     RECORD_LAYER_clear(&s->rlayer);
652
653     return (1);
654 }
655
656 /** Used to change an SSL_CTXs default SSL method type */
657 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
658 {
659     STACK_OF(SSL_CIPHER) *sk;
660
661     ctx->method = meth;
662
663     sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
664                                 &(ctx->cipher_list_by_id),
665                                 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
666     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
667         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
668         return (0);
669     }
670     return (1);
671 }
672
673 SSL *SSL_new(SSL_CTX *ctx)
674 {
675     SSL *s;
676
677     if (ctx == NULL) {
678         SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
679         return (NULL);
680     }
681     if (ctx->method == NULL) {
682         SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
683         return (NULL);
684     }
685
686     s = OPENSSL_zalloc(sizeof(*s));
687     if (s == NULL)
688         goto err;
689
690     s->lock = CRYPTO_THREAD_lock_new();
691     if (s->lock == NULL) {
692         SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
693         OPENSSL_free(s);
694         return NULL;
695     }
696
697     RECORD_LAYER_init(&s->rlayer, s);
698
699     s->options = ctx->options;
700     s->dane.flags = ctx->dane.flags;
701     s->min_proto_version = ctx->min_proto_version;
702     s->max_proto_version = ctx->max_proto_version;
703     s->mode = ctx->mode;
704     s->max_cert_list = ctx->max_cert_list;
705     s->references = 1;
706
707     /*
708      * Earlier library versions used to copy the pointer to the CERT, not
709      * its contents; only when setting new parameters for the per-SSL
710      * copy, ssl_cert_new would be called (and the direct reference to
711      * the per-SSL_CTX settings would be lost, but those still were
712      * indirectly accessed for various purposes, and for that reason they
713      * used to be known as s->ctx->default_cert). Now we don't look at the
714      * SSL_CTX's CERT after having duplicated it once.
715      */
716     s->cert = ssl_cert_dup(ctx->cert);
717     if (s->cert == NULL)
718         goto err;
719
720     RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
721     s->msg_callback = ctx->msg_callback;
722     s->msg_callback_arg = ctx->msg_callback_arg;
723     s->verify_mode = ctx->verify_mode;
724     s->not_resumable_session_cb = ctx->not_resumable_session_cb;
725     s->sid_ctx_length = ctx->sid_ctx_length;
726     OPENSSL_assert(s->sid_ctx_length <= sizeof(s->sid_ctx));
727     memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
728     s->verify_callback = ctx->default_verify_callback;
729     s->generate_session_id = ctx->generate_session_id;
730
731     s->param = X509_VERIFY_PARAM_new();
732     if (s->param == NULL)
733         goto err;
734     X509_VERIFY_PARAM_inherit(s->param, ctx->param);
735     s->quiet_shutdown = ctx->quiet_shutdown;
736     s->max_send_fragment = ctx->max_send_fragment;
737     s->split_send_fragment = ctx->split_send_fragment;
738     s->max_pipelines = ctx->max_pipelines;
739     if (s->max_pipelines > 1)
740         RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
741     if (ctx->default_read_buf_len > 0)
742         SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
743
744     SSL_CTX_up_ref(ctx);
745     s->ctx = ctx;
746     s->tlsext_debug_cb = 0;
747     s->tlsext_debug_arg = NULL;
748     s->tlsext_ticket_expected = 0;
749     s->tlsext_status_type = ctx->tlsext_status_type;
750     s->tlsext_status_expected = 0;
751     s->tlsext_ocsp_ids = NULL;
752     s->tlsext_ocsp_exts = NULL;
753     s->tlsext_ocsp_resp = NULL;
754     s->tlsext_ocsp_resplen = -1;
755     SSL_CTX_up_ref(ctx);
756     s->session_ctx = ctx;
757 #ifndef OPENSSL_NO_EC
758     if (ctx->tlsext_ecpointformatlist) {
759         s->tlsext_ecpointformatlist =
760             OPENSSL_memdup(ctx->tlsext_ecpointformatlist,
761                            ctx->tlsext_ecpointformatlist_length);
762         if (!s->tlsext_ecpointformatlist)
763             goto err;
764         s->tlsext_ecpointformatlist_length =
765             ctx->tlsext_ecpointformatlist_length;
766     }
767     if (ctx->tlsext_ellipticcurvelist) {
768         s->tlsext_ellipticcurvelist =
769             OPENSSL_memdup(ctx->tlsext_ellipticcurvelist,
770                            ctx->tlsext_ellipticcurvelist_length);
771         if (!s->tlsext_ellipticcurvelist)
772             goto err;
773         s->tlsext_ellipticcurvelist_length =
774             ctx->tlsext_ellipticcurvelist_length;
775     }
776 #endif
777 #ifndef OPENSSL_NO_NEXTPROTONEG
778     s->next_proto_negotiated = NULL;
779 #endif
780
781     if (s->ctx->alpn_client_proto_list) {
782         s->alpn_client_proto_list =
783             OPENSSL_malloc(s->ctx->alpn_client_proto_list_len);
784         if (s->alpn_client_proto_list == NULL)
785             goto err;
786         memcpy(s->alpn_client_proto_list, s->ctx->alpn_client_proto_list,
787                s->ctx->alpn_client_proto_list_len);
788         s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
789     }
790
791     s->verified_chain = NULL;
792     s->verify_result = X509_V_OK;
793
794     s->default_passwd_callback = ctx->default_passwd_callback;
795     s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
796
797     s->method = ctx->method;
798
799     if (!s->method->ssl_new(s))
800         goto err;
801
802     s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
803
804     if (!SSL_clear(s))
805         goto err;
806
807     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data))
808         goto err;
809
810 #ifndef OPENSSL_NO_PSK
811     s->psk_client_callback = ctx->psk_client_callback;
812     s->psk_server_callback = ctx->psk_server_callback;
813 #endif
814
815     s->job = NULL;
816
817 #ifndef OPENSSL_NO_CT
818     if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
819                                         ctx->ct_validation_callback_arg))
820         goto err;
821 #endif
822
823     return s;
824  err:
825     SSL_free(s);
826     SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
827     return NULL;
828 }
829
830 int SSL_is_dtls(const SSL *s)
831 {
832     return SSL_IS_DTLS(s) ? 1 : 0;
833 }
834
835 int SSL_up_ref(SSL *s)
836 {
837     int i;
838
839     if (CRYPTO_atomic_add(&s->references, 1, &i, s->lock) <= 0)
840         return 0;
841
842     REF_PRINT_COUNT("SSL", s);
843     REF_ASSERT_ISNT(i < 2);
844     return ((i > 1) ? 1 : 0);
845 }
846
847 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
848                                    unsigned int sid_ctx_len)
849 {
850     if (sid_ctx_len > sizeof(ctx->sid_ctx)) {
851         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
852                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
853         return 0;
854     }
855     ctx->sid_ctx_length = sid_ctx_len;
856     memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
857
858     return 1;
859 }
860
861 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
862                                unsigned int sid_ctx_len)
863 {
864     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
865         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
866                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
867         return 0;
868     }
869     ssl->sid_ctx_length = sid_ctx_len;
870     memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
871
872     return 1;
873 }
874
875 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
876 {
877     CRYPTO_THREAD_write_lock(ctx->lock);
878     ctx->generate_session_id = cb;
879     CRYPTO_THREAD_unlock(ctx->lock);
880     return 1;
881 }
882
883 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
884 {
885     CRYPTO_THREAD_write_lock(ssl->lock);
886     ssl->generate_session_id = cb;
887     CRYPTO_THREAD_unlock(ssl->lock);
888     return 1;
889 }
890
891 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
892                                 unsigned int id_len)
893 {
894     /*
895      * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
896      * we can "construct" a session to give us the desired check - i.e. to
897      * find if there's a session in the hash table that would conflict with
898      * any new session built out of this id/id_len and the ssl_version in use
899      * by this SSL.
900      */
901     SSL_SESSION r, *p;
902
903     if (id_len > sizeof(r.session_id))
904         return 0;
905
906     r.ssl_version = ssl->version;
907     r.session_id_length = id_len;
908     memcpy(r.session_id, id, id_len);
909
910     CRYPTO_THREAD_read_lock(ssl->session_ctx->lock);
911     p = lh_SSL_SESSION_retrieve(ssl->session_ctx->sessions, &r);
912     CRYPTO_THREAD_unlock(ssl->session_ctx->lock);
913     return (p != NULL);
914 }
915
916 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
917 {
918     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
919 }
920
921 int SSL_set_purpose(SSL *s, int purpose)
922 {
923     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
924 }
925
926 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
927 {
928     return X509_VERIFY_PARAM_set_trust(s->param, trust);
929 }
930
931 int SSL_set_trust(SSL *s, int trust)
932 {
933     return X509_VERIFY_PARAM_set_trust(s->param, trust);
934 }
935
936 int SSL_set1_host(SSL *s, const char *hostname)
937 {
938     return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
939 }
940
941 int SSL_add1_host(SSL *s, const char *hostname)
942 {
943     return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
944 }
945
946 void SSL_set_hostflags(SSL *s, unsigned int flags)
947 {
948     X509_VERIFY_PARAM_set_hostflags(s->param, flags);
949 }
950
951 const char *SSL_get0_peername(SSL *s)
952 {
953     return X509_VERIFY_PARAM_get0_peername(s->param);
954 }
955
956 int SSL_CTX_dane_enable(SSL_CTX *ctx)
957 {
958     return dane_ctx_enable(&ctx->dane);
959 }
960
961 unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags)
962 {
963     unsigned long orig = ctx->dane.flags;
964
965     ctx->dane.flags |= flags;
966     return orig;
967 }
968
969 unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags)
970 {
971     unsigned long orig = ctx->dane.flags;
972
973     ctx->dane.flags &= ~flags;
974     return orig;
975 }
976
977 int SSL_dane_enable(SSL *s, const char *basedomain)
978 {
979     SSL_DANE *dane = &s->dane;
980
981     if (s->ctx->dane.mdmax == 0) {
982         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
983         return 0;
984     }
985     if (dane->trecs != NULL) {
986         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
987         return 0;
988     }
989
990     /*
991      * Default SNI name.  This rejects empty names, while set1_host below
992      * accepts them and disables host name checks.  To avoid side-effects with
993      * invalid input, set the SNI name first.
994      */
995     if (s->tlsext_hostname == NULL) {
996         if (!SSL_set_tlsext_host_name(s, basedomain)) {
997             SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
998             return -1;
999         }
1000     }
1001
1002     /* Primary RFC6125 reference identifier */
1003     if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
1004         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
1005         return -1;
1006     }
1007
1008     dane->mdpth = -1;
1009     dane->pdpth = -1;
1010     dane->dctx = &s->ctx->dane;
1011     dane->trecs = sk_danetls_record_new_null();
1012
1013     if (dane->trecs == NULL) {
1014         SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
1015         return -1;
1016     }
1017     return 1;
1018 }
1019
1020 unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags)
1021 {
1022     unsigned long orig = ssl->dane.flags;
1023
1024     ssl->dane.flags |= flags;
1025     return orig;
1026 }
1027
1028 unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags)
1029 {
1030     unsigned long orig = ssl->dane.flags;
1031
1032     ssl->dane.flags &= ~flags;
1033     return orig;
1034 }
1035
1036 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
1037 {
1038     SSL_DANE *dane = &s->dane;
1039
1040     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1041         return -1;
1042     if (dane->mtlsa) {
1043         if (mcert)
1044             *mcert = dane->mcert;
1045         if (mspki)
1046             *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
1047     }
1048     return dane->mdpth;
1049 }
1050
1051 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
1052                        uint8_t *mtype, unsigned const char **data, size_t *dlen)
1053 {
1054     SSL_DANE *dane = &s->dane;
1055
1056     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1057         return -1;
1058     if (dane->mtlsa) {
1059         if (usage)
1060             *usage = dane->mtlsa->usage;
1061         if (selector)
1062             *selector = dane->mtlsa->selector;
1063         if (mtype)
1064             *mtype = dane->mtlsa->mtype;
1065         if (data)
1066             *data = dane->mtlsa->data;
1067         if (dlen)
1068             *dlen = dane->mtlsa->dlen;
1069     }
1070     return dane->mdpth;
1071 }
1072
1073 SSL_DANE *SSL_get0_dane(SSL *s)
1074 {
1075     return &s->dane;
1076 }
1077
1078 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
1079                       uint8_t mtype, unsigned const char *data, size_t dlen)
1080 {
1081     return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
1082 }
1083
1084 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype,
1085                            uint8_t ord)
1086 {
1087     return dane_mtype_set(&ctx->dane, md, mtype, ord);
1088 }
1089
1090 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
1091 {
1092     return X509_VERIFY_PARAM_set1(ctx->param, vpm);
1093 }
1094
1095 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
1096 {
1097     return X509_VERIFY_PARAM_set1(ssl->param, vpm);
1098 }
1099
1100 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
1101 {
1102     return ctx->param;
1103 }
1104
1105 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
1106 {
1107     return ssl->param;
1108 }
1109
1110 void SSL_certs_clear(SSL *s)
1111 {
1112     ssl_cert_clear_certs(s->cert);
1113 }
1114
1115 void SSL_free(SSL *s)
1116 {
1117     int i;
1118
1119     if (s == NULL)
1120         return;
1121
1122     CRYPTO_atomic_add(&s->references, -1, &i, s->lock);
1123     REF_PRINT_COUNT("SSL", s);
1124     if (i > 0)
1125         return;
1126     REF_ASSERT_ISNT(i < 0);
1127
1128     X509_VERIFY_PARAM_free(s->param);
1129     dane_final(&s->dane);
1130     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
1131
1132     ssl_free_wbio_buffer(s);
1133
1134     BIO_free_all(s->wbio);
1135     BIO_free_all(s->rbio);
1136
1137     BUF_MEM_free(s->init_buf);
1138
1139     /* add extra stuff */
1140     sk_SSL_CIPHER_free(s->cipher_list);
1141     sk_SSL_CIPHER_free(s->cipher_list_by_id);
1142
1143     /* Make the next call work :-) */
1144     if (s->session != NULL) {
1145         ssl_clear_bad_session(s);
1146         SSL_SESSION_free(s->session);
1147     }
1148
1149     clear_ciphers(s);
1150
1151     ssl_cert_free(s->cert);
1152     /* Free up if allocated */
1153
1154     OPENSSL_free(s->tlsext_hostname);
1155     SSL_CTX_free(s->session_ctx);
1156 #ifndef OPENSSL_NO_EC
1157     OPENSSL_free(s->tlsext_ecpointformatlist);
1158     OPENSSL_free(s->tlsext_ellipticcurvelist);
1159 #endif                          /* OPENSSL_NO_EC */
1160     sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
1161 #ifndef OPENSSL_NO_OCSP
1162     sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
1163 #endif
1164 #ifndef OPENSSL_NO_CT
1165     SCT_LIST_free(s->scts);
1166     OPENSSL_free(s->tlsext_scts);
1167 #endif
1168     OPENSSL_free(s->tlsext_ocsp_resp);
1169     OPENSSL_free(s->alpn_client_proto_list);
1170
1171     sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
1172
1173     sk_X509_pop_free(s->verified_chain, X509_free);
1174
1175     if (s->method != NULL)
1176         s->method->ssl_free(s);
1177
1178     RECORD_LAYER_release(&s->rlayer);
1179
1180     SSL_CTX_free(s->ctx);
1181
1182     ASYNC_WAIT_CTX_free(s->waitctx);
1183
1184 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1185     OPENSSL_free(s->next_proto_negotiated);
1186 #endif
1187
1188 #ifndef OPENSSL_NO_SRTP
1189     sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1190 #endif
1191
1192     CRYPTO_THREAD_lock_free(s->lock);
1193
1194     OPENSSL_free(s);
1195 }
1196
1197 void SSL_set0_rbio(SSL *s, BIO *rbio)
1198 {
1199     BIO_free_all(s->rbio);
1200     s->rbio = rbio;
1201 }
1202
1203 void SSL_set0_wbio(SSL *s, BIO *wbio)
1204 {
1205     /*
1206      * If the output buffering BIO is still in place, remove it
1207      */
1208     if (s->bbio != NULL)
1209         s->wbio = BIO_pop(s->wbio);
1210
1211     BIO_free_all(s->wbio);
1212     s->wbio = wbio;
1213
1214     /* Re-attach |bbio| to the new |wbio|. */
1215     if (s->bbio != NULL)
1216         s->wbio = BIO_push(s->bbio, s->wbio);
1217 }
1218
1219 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1220 {
1221     /*
1222      * For historical reasons, this function has many different cases in
1223      * ownership handling.
1224      */
1225
1226     /* If nothing has changed, do nothing */
1227     if (rbio == SSL_get_rbio(s) && wbio == SSL_get_wbio(s))
1228         return;
1229
1230     /*
1231      * If the two arguments are equal then one fewer reference is granted by the
1232      * caller than we want to take
1233      */
1234     if (rbio != NULL && rbio == wbio)
1235         BIO_up_ref(rbio);
1236
1237     /*
1238      * If only the wbio is changed only adopt one reference.
1239      */
1240     if (rbio == SSL_get_rbio(s)) {
1241         SSL_set0_wbio(s, wbio);
1242         return;
1243     }
1244     /*
1245      * There is an asymmetry here for historical reasons. If only the rbio is
1246      * changed AND the rbio and wbio were originally different, then we only
1247      * adopt one reference.
1248      */
1249     if (wbio == SSL_get_wbio(s) && SSL_get_rbio(s) != SSL_get_wbio(s)) {
1250         SSL_set0_rbio(s, rbio);
1251         return;
1252     }
1253
1254     /* Otherwise, adopt both references. */
1255     SSL_set0_rbio(s, rbio);
1256     SSL_set0_wbio(s, wbio);
1257 }
1258
1259 BIO *SSL_get_rbio(const SSL *s)
1260 {
1261     return s->rbio;
1262 }
1263
1264 BIO *SSL_get_wbio(const SSL *s)
1265 {
1266     if (s->bbio != NULL) {
1267         /*
1268          * If |bbio| is active, the true caller-configured BIO is its
1269          * |next_bio|.
1270          */
1271         return BIO_next(s->bbio);
1272     }
1273     return s->wbio;
1274 }
1275
1276 int SSL_get_fd(const SSL *s)
1277 {
1278     return SSL_get_rfd(s);
1279 }
1280
1281 int SSL_get_rfd(const SSL *s)
1282 {
1283     int ret = -1;
1284     BIO *b, *r;
1285
1286     b = SSL_get_rbio(s);
1287     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1288     if (r != NULL)
1289         BIO_get_fd(r, &ret);
1290     return (ret);
1291 }
1292
1293 int SSL_get_wfd(const SSL *s)
1294 {
1295     int ret = -1;
1296     BIO *b, *r;
1297
1298     b = SSL_get_wbio(s);
1299     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1300     if (r != NULL)
1301         BIO_get_fd(r, &ret);
1302     return (ret);
1303 }
1304
1305 #ifndef OPENSSL_NO_SOCK
1306 int SSL_set_fd(SSL *s, int fd)
1307 {
1308     int ret = 0;
1309     BIO *bio = NULL;
1310
1311     bio = BIO_new(BIO_s_socket());
1312
1313     if (bio == NULL) {
1314         SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1315         goto err;
1316     }
1317     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1318     SSL_set_bio(s, bio, bio);
1319     ret = 1;
1320  err:
1321     return (ret);
1322 }
1323
1324 int SSL_set_wfd(SSL *s, int fd)
1325 {
1326     BIO *rbio = SSL_get_rbio(s);
1327
1328     if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET
1329         || (int)BIO_get_fd(rbio, NULL) != fd) {
1330         BIO *bio = BIO_new(BIO_s_socket());
1331
1332         if (bio == NULL) {
1333             SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1334             return 0;
1335         }
1336         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1337         SSL_set0_wbio(s, bio);
1338     } else {
1339         BIO_up_ref(rbio);
1340         SSL_set0_wbio(s, rbio);
1341     }
1342     return 1;
1343 }
1344
1345 int SSL_set_rfd(SSL *s, int fd)
1346 {
1347     BIO *wbio = SSL_get_wbio(s);
1348
1349     if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET
1350         || ((int)BIO_get_fd(wbio, NULL) != fd)) {
1351         BIO *bio = BIO_new(BIO_s_socket());
1352
1353         if (bio == NULL) {
1354             SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1355             return 0;
1356         }
1357         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1358         SSL_set0_rbio(s, bio);
1359     } else {
1360         BIO_up_ref(wbio);
1361         SSL_set0_rbio(s, wbio);
1362     }
1363
1364     return 1;
1365 }
1366 #endif
1367
1368 /* return length of latest Finished message we sent, copy to 'buf' */
1369 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1370 {
1371     size_t ret = 0;
1372
1373     if (s->s3 != NULL) {
1374         ret = s->s3->tmp.finish_md_len;
1375         if (count > ret)
1376             count = ret;
1377         memcpy(buf, s->s3->tmp.finish_md, count);
1378     }
1379     return ret;
1380 }
1381
1382 /* return length of latest Finished message we expected, copy to 'buf' */
1383 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1384 {
1385     size_t ret = 0;
1386
1387     if (s->s3 != NULL) {
1388         ret = s->s3->tmp.peer_finish_md_len;
1389         if (count > ret)
1390             count = ret;
1391         memcpy(buf, s->s3->tmp.peer_finish_md, count);
1392     }
1393     return ret;
1394 }
1395
1396 int SSL_get_verify_mode(const SSL *s)
1397 {
1398     return (s->verify_mode);
1399 }
1400
1401 int SSL_get_verify_depth(const SSL *s)
1402 {
1403     return X509_VERIFY_PARAM_get_depth(s->param);
1404 }
1405
1406 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1407     return (s->verify_callback);
1408 }
1409
1410 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1411 {
1412     return (ctx->verify_mode);
1413 }
1414
1415 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1416 {
1417     return X509_VERIFY_PARAM_get_depth(ctx->param);
1418 }
1419
1420 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1421     return (ctx->default_verify_callback);
1422 }
1423
1424 void SSL_set_verify(SSL *s, int mode,
1425                     int (*callback) (int ok, X509_STORE_CTX *ctx))
1426 {
1427     s->verify_mode = mode;
1428     if (callback != NULL)
1429         s->verify_callback = callback;
1430 }
1431
1432 void SSL_set_verify_depth(SSL *s, int depth)
1433 {
1434     X509_VERIFY_PARAM_set_depth(s->param, depth);
1435 }
1436
1437 void SSL_set_read_ahead(SSL *s, int yes)
1438 {
1439     RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1440 }
1441
1442 int SSL_get_read_ahead(const SSL *s)
1443 {
1444     return RECORD_LAYER_get_read_ahead(&s->rlayer);
1445 }
1446
1447 int SSL_pending(const SSL *s)
1448 {
1449     /*
1450      * SSL_pending cannot work properly if read-ahead is enabled
1451      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1452      * impossible to fix since SSL_pending cannot report errors that may be
1453      * observed while scanning the new data. (Note that SSL_pending() is
1454      * often used as a boolean value, so we'd better not return -1.)
1455      */
1456     return (s->method->ssl_pending(s));
1457 }
1458
1459 int SSL_has_pending(const SSL *s)
1460 {
1461     /*
1462      * Similar to SSL_pending() but returns a 1 to indicate that we have
1463      * unprocessed data available or 0 otherwise (as opposed to the number of
1464      * bytes available). Unlike SSL_pending() this will take into account
1465      * read_ahead data. A 1 return simply indicates that we have unprocessed
1466      * data. That data may not result in any application data, or we may fail
1467      * to parse the records for some reason.
1468      */
1469     if (RECORD_LAYER_processed_read_pending(&s->rlayer))
1470         return 1;
1471
1472     return RECORD_LAYER_read_pending(&s->rlayer);
1473 }
1474
1475 X509 *SSL_get_peer_certificate(const SSL *s)
1476 {
1477     X509 *r;
1478
1479     if ((s == NULL) || (s->session == NULL))
1480         r = NULL;
1481     else
1482         r = s->session->peer;
1483
1484     if (r == NULL)
1485         return (r);
1486
1487     X509_up_ref(r);
1488
1489     return (r);
1490 }
1491
1492 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1493 {
1494     STACK_OF(X509) *r;
1495
1496     if ((s == NULL) || (s->session == NULL))
1497         r = NULL;
1498     else
1499         r = s->session->peer_chain;
1500
1501     /*
1502      * If we are a client, cert_chain includes the peer's own certificate; if
1503      * we are a server, it does not.
1504      */
1505
1506     return (r);
1507 }
1508
1509 /*
1510  * Now in theory, since the calling process own 't' it should be safe to
1511  * modify.  We need to be able to read f without being hassled
1512  */
1513 int SSL_copy_session_id(SSL *t, const SSL *f)
1514 {
1515     int i;
1516     /* Do we need to to SSL locking? */
1517     if (!SSL_set_session(t, SSL_get_session(f))) {
1518         return 0;
1519     }
1520
1521     /*
1522      * what if we are setup for one protocol version but want to talk another
1523      */
1524     if (t->method != f->method) {
1525         t->method->ssl_free(t);
1526         t->method = f->method;
1527         if (t->method->ssl_new(t) == 0)
1528             return 0;
1529     }
1530
1531     CRYPTO_atomic_add(&f->cert->references, 1, &i, f->cert->lock);
1532     ssl_cert_free(t->cert);
1533     t->cert = f->cert;
1534     if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length)) {
1535         return 0;
1536     }
1537
1538     return 1;
1539 }
1540
1541 /* Fix this so it checks all the valid key/cert options */
1542 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1543 {
1544     if ((ctx == NULL) || (ctx->cert->key->x509 == NULL)) {
1545         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1546         return (0);
1547     }
1548     if (ctx->cert->key->privatekey == NULL) {
1549         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1550         return (0);
1551     }
1552     return (X509_check_private_key
1553             (ctx->cert->key->x509, ctx->cert->key->privatekey));
1554 }
1555
1556 /* Fix this function so that it takes an optional type parameter */
1557 int SSL_check_private_key(const SSL *ssl)
1558 {
1559     if (ssl == NULL) {
1560         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1561         return (0);
1562     }
1563     if (ssl->cert->key->x509 == NULL) {
1564         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1565         return (0);
1566     }
1567     if (ssl->cert->key->privatekey == NULL) {
1568         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1569         return (0);
1570     }
1571     return (X509_check_private_key(ssl->cert->key->x509,
1572                                    ssl->cert->key->privatekey));
1573 }
1574
1575 int SSL_waiting_for_async(SSL *s)
1576 {
1577     if (s->job)
1578         return 1;
1579
1580     return 0;
1581 }
1582
1583 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1584 {
1585     ASYNC_WAIT_CTX *ctx = s->waitctx;
1586
1587     if (ctx == NULL)
1588         return 0;
1589     return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1590 }
1591
1592 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1593                               OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1594 {
1595     ASYNC_WAIT_CTX *ctx = s->waitctx;
1596
1597     if (ctx == NULL)
1598         return 0;
1599     return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1600                                           numdelfds);
1601 }
1602
1603 int SSL_accept(SSL *s)
1604 {
1605     if (s->handshake_func == NULL) {
1606         /* Not properly initialized yet */
1607         SSL_set_accept_state(s);
1608     }
1609
1610     return SSL_do_handshake(s);
1611 }
1612
1613 int SSL_connect(SSL *s)
1614 {
1615     if (s->handshake_func == NULL) {
1616         /* Not properly initialized yet */
1617         SSL_set_connect_state(s);
1618     }
1619
1620     return SSL_do_handshake(s);
1621 }
1622
1623 long SSL_get_default_timeout(const SSL *s)
1624 {
1625     return (s->method->get_timeout());
1626 }
1627
1628 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1629                                int (*func) (void *))
1630 {
1631     int ret;
1632     if (s->waitctx == NULL) {
1633         s->waitctx = ASYNC_WAIT_CTX_new();
1634         if (s->waitctx == NULL)
1635             return -1;
1636     }
1637     switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1638                             sizeof(struct ssl_async_args))) {
1639     case ASYNC_ERR:
1640         s->rwstate = SSL_NOTHING;
1641         SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1642         return -1;
1643     case ASYNC_PAUSE:
1644         s->rwstate = SSL_ASYNC_PAUSED;
1645         return -1;
1646     case ASYNC_NO_JOBS:
1647         s->rwstate = SSL_ASYNC_NO_JOBS;
1648         return -1;
1649     case ASYNC_FINISH:
1650         s->job = NULL;
1651         return ret;
1652     default:
1653         s->rwstate = SSL_NOTHING;
1654         SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1655         /* Shouldn't happen */
1656         return -1;
1657     }
1658 }
1659
1660 static int ssl_io_intern(void *vargs)
1661 {
1662     struct ssl_async_args *args;
1663     SSL *s;
1664     void *buf;
1665     int num;
1666
1667     args = (struct ssl_async_args *)vargs;
1668     s = args->s;
1669     buf = args->buf;
1670     num = args->num;
1671     switch (args->type) {
1672     case READFUNC:
1673         return args->f.func_read(s, buf, num);
1674     case WRITEFUNC:
1675         return args->f.func_write(s, buf, num);
1676     case OTHERFUNC:
1677         return args->f.func_other(s);
1678     }
1679     return -1;
1680 }
1681
1682 int SSL_read(SSL *s, void *buf, int num)
1683 {
1684     if (s->handshake_func == NULL) {
1685         SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
1686         return -1;
1687     }
1688
1689     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1690         s->rwstate = SSL_NOTHING;
1691         return (0);
1692     }
1693
1694     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1695         struct ssl_async_args args;
1696
1697         args.s = s;
1698         args.buf = buf;
1699         args.num = num;
1700         args.type = READFUNC;
1701         args.f.func_read = s->method->ssl_read;
1702
1703         return ssl_start_async_job(s, &args, ssl_io_intern);
1704     } else {
1705         return s->method->ssl_read(s, buf, num);
1706     }
1707 }
1708
1709 int SSL_peek(SSL *s, void *buf, int num)
1710 {
1711     if (s->handshake_func == NULL) {
1712         SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
1713         return -1;
1714     }
1715
1716     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1717         return (0);
1718     }
1719     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1720         struct ssl_async_args args;
1721
1722         args.s = s;
1723         args.buf = buf;
1724         args.num = num;
1725         args.type = READFUNC;
1726         args.f.func_read = s->method->ssl_peek;
1727
1728         return ssl_start_async_job(s, &args, ssl_io_intern);
1729     } else {
1730         return s->method->ssl_peek(s, buf, num);
1731     }
1732 }
1733
1734 int SSL_write(SSL *s, const void *buf, int num)
1735 {
1736     if (s->handshake_func == NULL) {
1737         SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
1738         return -1;
1739     }
1740
1741     if (s->shutdown & SSL_SENT_SHUTDOWN) {
1742         s->rwstate = SSL_NOTHING;
1743         SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
1744         return (-1);
1745     }
1746
1747     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1748         struct ssl_async_args args;
1749
1750         args.s = s;
1751         args.buf = (void *)buf;
1752         args.num = num;
1753         args.type = WRITEFUNC;
1754         args.f.func_write = s->method->ssl_write;
1755
1756         return ssl_start_async_job(s, &args, ssl_io_intern);
1757     } else {
1758         return s->method->ssl_write(s, buf, num);
1759     }
1760 }
1761
1762 int SSL_shutdown(SSL *s)
1763 {
1764     /*
1765      * Note that this function behaves differently from what one might
1766      * expect.  Return values are 0 for no success (yet), 1 for success; but
1767      * calling it once is usually not enough, even if blocking I/O is used
1768      * (see ssl3_shutdown).
1769      */
1770
1771     if (s->handshake_func == NULL) {
1772         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1773         return -1;
1774     }
1775
1776     if (!SSL_in_init(s)) {
1777         if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1778             struct ssl_async_args args;
1779
1780             args.s = s;
1781             args.type = OTHERFUNC;
1782             args.f.func_other = s->method->ssl_shutdown;
1783
1784             return ssl_start_async_job(s, &args, ssl_io_intern);
1785         } else {
1786             return s->method->ssl_shutdown(s);
1787         }
1788     } else {
1789         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
1790         return -1;
1791     }
1792 }
1793
1794 int SSL_renegotiate(SSL *s)
1795 {
1796     if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1797         SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_NO_RENEGOTIATION);
1798         return 0;
1799     }
1800
1801     if (s->renegotiate == 0)
1802         s->renegotiate = 1;
1803
1804     s->new_session = 1;
1805
1806     return (s->method->ssl_renegotiate(s));
1807 }
1808
1809 int SSL_renegotiate_abbreviated(SSL *s)
1810 {
1811     if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1812         SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_NO_RENEGOTIATION);
1813         return 0;
1814     }
1815
1816     if (s->renegotiate == 0)
1817         s->renegotiate = 1;
1818
1819     s->new_session = 0;
1820
1821     return (s->method->ssl_renegotiate(s));
1822 }
1823
1824 int SSL_renegotiate_pending(SSL *s)
1825 {
1826     /*
1827      * becomes true when negotiation is requested; false again once a
1828      * handshake has finished
1829      */
1830     return (s->renegotiate != 0);
1831 }
1832
1833 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1834 {
1835     long l;
1836
1837     switch (cmd) {
1838     case SSL_CTRL_GET_READ_AHEAD:
1839         return (RECORD_LAYER_get_read_ahead(&s->rlayer));
1840     case SSL_CTRL_SET_READ_AHEAD:
1841         l = RECORD_LAYER_get_read_ahead(&s->rlayer);
1842         RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
1843         return (l);
1844
1845     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1846         s->msg_callback_arg = parg;
1847         return 1;
1848
1849     case SSL_CTRL_MODE:
1850         return (s->mode |= larg);
1851     case SSL_CTRL_CLEAR_MODE:
1852         return (s->mode &= ~larg);
1853     case SSL_CTRL_GET_MAX_CERT_LIST:
1854         return (s->max_cert_list);
1855     case SSL_CTRL_SET_MAX_CERT_LIST:
1856         l = s->max_cert_list;
1857         s->max_cert_list = larg;
1858         return (l);
1859     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1860         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1861             return 0;
1862         s->max_send_fragment = larg;
1863         if (s->max_send_fragment < s->split_send_fragment)
1864             s->split_send_fragment = s->max_send_fragment;
1865         return 1;
1866     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1867         if ((unsigned int)larg > s->max_send_fragment || larg == 0)
1868             return 0;
1869         s->split_send_fragment = larg;
1870         return 1;
1871     case SSL_CTRL_SET_MAX_PIPELINES:
1872         if (larg < 1 || larg > SSL_MAX_PIPELINES)
1873             return 0;
1874         s->max_pipelines = larg;
1875         if (larg > 1)
1876             RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
1877         return 1;
1878     case SSL_CTRL_GET_RI_SUPPORT:
1879         if (s->s3)
1880             return s->s3->send_connection_binding;
1881         else
1882             return 0;
1883     case SSL_CTRL_CERT_FLAGS:
1884         return (s->cert->cert_flags |= larg);
1885     case SSL_CTRL_CLEAR_CERT_FLAGS:
1886         return (s->cert->cert_flags &= ~larg);
1887
1888     case SSL_CTRL_GET_RAW_CIPHERLIST:
1889         if (parg) {
1890             if (s->s3->tmp.ciphers_raw == NULL)
1891                 return 0;
1892             *(unsigned char **)parg = s->s3->tmp.ciphers_raw;
1893             return (int)s->s3->tmp.ciphers_rawlen;
1894         } else {
1895             return TLS_CIPHER_LEN;
1896         }
1897     case SSL_CTRL_GET_EXTMS_SUPPORT:
1898         if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
1899             return -1;
1900         if (s->session->flags & SSL_SESS_FLAG_EXTMS)
1901             return 1;
1902         else
1903             return 0;
1904     case SSL_CTRL_SET_MIN_PROTO_VERSION:
1905         return ssl_check_allowed_versions(larg, s->max_proto_version)
1906                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
1907                                         &s->min_proto_version);
1908     case SSL_CTRL_GET_MIN_PROTO_VERSION:
1909         return s->min_proto_version;
1910     case SSL_CTRL_SET_MAX_PROTO_VERSION:
1911         return ssl_check_allowed_versions(s->min_proto_version, larg)
1912                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
1913                                         &s->max_proto_version);
1914     case SSL_CTRL_GET_MAX_PROTO_VERSION:
1915         return s->max_proto_version;
1916     default:
1917         return (s->method->ssl_ctrl(s, cmd, larg, parg));
1918     }
1919 }
1920
1921 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1922 {
1923     switch (cmd) {
1924     case SSL_CTRL_SET_MSG_CALLBACK:
1925         s->msg_callback = (void (*)
1926                            (int write_p, int version, int content_type,
1927                             const void *buf, size_t len, SSL *ssl,
1928                             void *arg))(fp);
1929         return 1;
1930
1931     default:
1932         return (s->method->ssl_callback_ctrl(s, cmd, fp));
1933     }
1934 }
1935
1936 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
1937 {
1938     return ctx->sessions;
1939 }
1940
1941 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1942 {
1943     long l;
1944     /* For some cases with ctx == NULL perform syntax checks */
1945     if (ctx == NULL) {
1946         switch (cmd) {
1947 #ifndef OPENSSL_NO_EC
1948         case SSL_CTRL_SET_CURVES_LIST:
1949             return tls1_set_curves_list(NULL, NULL, parg);
1950 #endif
1951         case SSL_CTRL_SET_SIGALGS_LIST:
1952         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
1953             return tls1_set_sigalgs_list(NULL, parg, 0);
1954         default:
1955             return 0;
1956         }
1957     }
1958
1959     switch (cmd) {
1960     case SSL_CTRL_GET_READ_AHEAD:
1961         return (ctx->read_ahead);
1962     case SSL_CTRL_SET_READ_AHEAD:
1963         l = ctx->read_ahead;
1964         ctx->read_ahead = larg;
1965         return (l);
1966
1967     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1968         ctx->msg_callback_arg = parg;
1969         return 1;
1970
1971     case SSL_CTRL_GET_MAX_CERT_LIST:
1972         return (ctx->max_cert_list);
1973     case SSL_CTRL_SET_MAX_CERT_LIST:
1974         l = ctx->max_cert_list;
1975         ctx->max_cert_list = larg;
1976         return (l);
1977
1978     case SSL_CTRL_SET_SESS_CACHE_SIZE:
1979         l = ctx->session_cache_size;
1980         ctx->session_cache_size = larg;
1981         return (l);
1982     case SSL_CTRL_GET_SESS_CACHE_SIZE:
1983         return (ctx->session_cache_size);
1984     case SSL_CTRL_SET_SESS_CACHE_MODE:
1985         l = ctx->session_cache_mode;
1986         ctx->session_cache_mode = larg;
1987         return (l);
1988     case SSL_CTRL_GET_SESS_CACHE_MODE:
1989         return (ctx->session_cache_mode);
1990
1991     case SSL_CTRL_SESS_NUMBER:
1992         return (lh_SSL_SESSION_num_items(ctx->sessions));
1993     case SSL_CTRL_SESS_CONNECT:
1994         return (ctx->stats.sess_connect);
1995     case SSL_CTRL_SESS_CONNECT_GOOD:
1996         return (ctx->stats.sess_connect_good);
1997     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1998         return (ctx->stats.sess_connect_renegotiate);
1999     case SSL_CTRL_SESS_ACCEPT:
2000         return (ctx->stats.sess_accept);
2001     case SSL_CTRL_SESS_ACCEPT_GOOD:
2002         return (ctx->stats.sess_accept_good);
2003     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
2004         return (ctx->stats.sess_accept_renegotiate);
2005     case SSL_CTRL_SESS_HIT:
2006         return (ctx->stats.sess_hit);
2007     case SSL_CTRL_SESS_CB_HIT:
2008         return (ctx->stats.sess_cb_hit);
2009     case SSL_CTRL_SESS_MISSES:
2010         return (ctx->stats.sess_miss);
2011     case SSL_CTRL_SESS_TIMEOUTS:
2012         return (ctx->stats.sess_timeout);
2013     case SSL_CTRL_SESS_CACHE_FULL:
2014         return (ctx->stats.sess_cache_full);
2015     case SSL_CTRL_MODE:
2016         return (ctx->mode |= larg);
2017     case SSL_CTRL_CLEAR_MODE:
2018         return (ctx->mode &= ~larg);
2019     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2020         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2021             return 0;
2022         ctx->max_send_fragment = larg;
2023         if (ctx->max_send_fragment < ctx->split_send_fragment)
2024             ctx->split_send_fragment = ctx->max_send_fragment;
2025         return 1;
2026     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2027         if ((unsigned int)larg > ctx->max_send_fragment || larg == 0)
2028             return 0;
2029         ctx->split_send_fragment = larg;
2030         return 1;
2031     case SSL_CTRL_SET_MAX_PIPELINES:
2032         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2033             return 0;
2034         ctx->max_pipelines = larg;
2035         return 1;
2036     case SSL_CTRL_CERT_FLAGS:
2037         return (ctx->cert->cert_flags |= larg);
2038     case SSL_CTRL_CLEAR_CERT_FLAGS:
2039         return (ctx->cert->cert_flags &= ~larg);
2040     case SSL_CTRL_SET_MIN_PROTO_VERSION:
2041         return ssl_check_allowed_versions(larg, ctx->max_proto_version)
2042                && ssl_set_version_bound(ctx->method->version, (int)larg,
2043                                         &ctx->min_proto_version);
2044     case SSL_CTRL_GET_MIN_PROTO_VERSION:
2045         return ctx->min_proto_version;
2046     case SSL_CTRL_SET_MAX_PROTO_VERSION:
2047         return ssl_check_allowed_versions(ctx->min_proto_version, larg)
2048                && ssl_set_version_bound(ctx->method->version, (int)larg,
2049                                         &ctx->max_proto_version);
2050     case SSL_CTRL_GET_MAX_PROTO_VERSION:
2051         return ctx->max_proto_version;
2052     default:
2053         return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
2054     }
2055 }
2056
2057 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
2058 {
2059     switch (cmd) {
2060     case SSL_CTRL_SET_MSG_CALLBACK:
2061         ctx->msg_callback = (void (*)
2062                              (int write_p, int version, int content_type,
2063                               const void *buf, size_t len, SSL *ssl,
2064                               void *arg))(fp);
2065         return 1;
2066
2067     default:
2068         return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
2069     }
2070 }
2071
2072 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
2073 {
2074     if (a->id > b->id)
2075         return 1;
2076     if (a->id < b->id)
2077         return -1;
2078     return 0;
2079 }
2080
2081 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
2082                           const SSL_CIPHER *const *bp)
2083 {
2084     if ((*ap)->id > (*bp)->id)
2085         return 1;
2086     if ((*ap)->id < (*bp)->id)
2087         return -1;
2088     return 0;
2089 }
2090
2091 /** return a STACK of the ciphers available for the SSL and in order of
2092  * preference */
2093 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
2094 {
2095     if (s != NULL) {
2096         if (s->cipher_list != NULL) {
2097             return (s->cipher_list);
2098         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
2099             return (s->ctx->cipher_list);
2100         }
2101     }
2102     return (NULL);
2103 }
2104
2105 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
2106 {
2107     if ((s == NULL) || (s->session == NULL) || !s->server)
2108         return NULL;
2109     return s->session->ciphers;
2110 }
2111
2112 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
2113 {
2114     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
2115     int i;
2116     ciphers = SSL_get_ciphers(s);
2117     if (!ciphers)
2118         return NULL;
2119     ssl_set_client_disabled(s);
2120     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2121         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
2122         if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
2123             if (!sk)
2124                 sk = sk_SSL_CIPHER_new_null();
2125             if (!sk)
2126                 return NULL;
2127             if (!sk_SSL_CIPHER_push(sk, c)) {
2128                 sk_SSL_CIPHER_free(sk);
2129                 return NULL;
2130             }
2131         }
2132     }
2133     return sk;
2134 }
2135
2136 /** return a STACK of the ciphers available for the SSL and in order of
2137  * algorithm id */
2138 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
2139 {
2140     if (s != NULL) {
2141         if (s->cipher_list_by_id != NULL) {
2142             return (s->cipher_list_by_id);
2143         } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
2144             return (s->ctx->cipher_list_by_id);
2145         }
2146     }
2147     return (NULL);
2148 }
2149
2150 /** The old interface to get the same thing as SSL_get_ciphers() */
2151 const char *SSL_get_cipher_list(const SSL *s, int n)
2152 {
2153     const SSL_CIPHER *c;
2154     STACK_OF(SSL_CIPHER) *sk;
2155
2156     if (s == NULL)
2157         return (NULL);
2158     sk = SSL_get_ciphers(s);
2159     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2160         return (NULL);
2161     c = sk_SSL_CIPHER_value(sk, n);
2162     if (c == NULL)
2163         return (NULL);
2164     return (c->name);
2165 }
2166
2167 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2168  * preference */
2169 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2170 {
2171     if (ctx != NULL)
2172         return ctx->cipher_list;
2173     return NULL;
2174 }
2175
2176 /** specify the ciphers to be used by default by the SSL_CTX */
2177 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2178 {
2179     STACK_OF(SSL_CIPHER) *sk;
2180
2181     sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
2182                                 &ctx->cipher_list_by_id, str, ctx->cert);
2183     /*
2184      * ssl_create_cipher_list may return an empty stack if it was unable to
2185      * find a cipher matching the given rule string (for example if the rule
2186      * string specifies a cipher which has been disabled). This is not an
2187      * error as far as ssl_create_cipher_list is concerned, and hence
2188      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2189      */
2190     if (sk == NULL)
2191         return 0;
2192     else if (sk_SSL_CIPHER_num(sk) == 0) {
2193         SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2194         return 0;
2195     }
2196     return 1;
2197 }
2198
2199 /** specify the ciphers to be used by the SSL */
2200 int SSL_set_cipher_list(SSL *s, const char *str)
2201 {
2202     STACK_OF(SSL_CIPHER) *sk;
2203
2204     sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
2205                                 &s->cipher_list_by_id, str, s->cert);
2206     /* see comment in SSL_CTX_set_cipher_list */
2207     if (sk == NULL)
2208         return 0;
2209     else if (sk_SSL_CIPHER_num(sk) == 0) {
2210         SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2211         return 0;
2212     }
2213     return 1;
2214 }
2215
2216 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
2217 {
2218     char *p;
2219     STACK_OF(SSL_CIPHER) *sk;
2220     const SSL_CIPHER *c;
2221     int i;
2222
2223     if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
2224         return (NULL);
2225
2226     p = buf;
2227     sk = s->session->ciphers;
2228
2229     if (sk_SSL_CIPHER_num(sk) == 0)
2230         return NULL;
2231
2232     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2233         int n;
2234
2235         c = sk_SSL_CIPHER_value(sk, i);
2236         n = strlen(c->name);
2237         if (n + 1 > len) {
2238             if (p != buf)
2239                 --p;
2240             *p = '\0';
2241             return buf;
2242         }
2243         memcpy(p, c->name, n + 1);
2244         p += n;
2245         *(p++) = ':';
2246         len -= n + 1;
2247     }
2248     p[-1] = '\0';
2249     return (buf);
2250 }
2251
2252 /** return a servername extension value if provided in Client Hello, or NULL.
2253  * So far, only host_name types are defined (RFC 3546).
2254  */
2255
2256 const char *SSL_get_servername(const SSL *s, const int type)
2257 {
2258     if (type != TLSEXT_NAMETYPE_host_name)
2259         return NULL;
2260
2261     return s->session && !s->tlsext_hostname ?
2262         s->session->tlsext_hostname : s->tlsext_hostname;
2263 }
2264
2265 int SSL_get_servername_type(const SSL *s)
2266 {
2267     if (s->session
2268         && (!s->tlsext_hostname ? s->session->
2269             tlsext_hostname : s->tlsext_hostname))
2270         return TLSEXT_NAMETYPE_host_name;
2271     return -1;
2272 }
2273
2274 /*
2275  * SSL_select_next_proto implements the standard protocol selection. It is
2276  * expected that this function is called from the callback set by
2277  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2278  * vector of 8-bit, length prefixed byte strings. The length byte itself is
2279  * not included in the length. A byte string of length 0 is invalid. No byte
2280  * string may be truncated. The current, but experimental algorithm for
2281  * selecting the protocol is: 1) If the server doesn't support NPN then this
2282  * is indicated to the callback. In this case, the client application has to
2283  * abort the connection or have a default application level protocol. 2) If
2284  * the server supports NPN, but advertises an empty list then the client
2285  * selects the first protocol in its list, but indicates via the API that this
2286  * fallback case was enacted. 3) Otherwise, the client finds the first
2287  * protocol in the server's list that it supports and selects this protocol.
2288  * This is because it's assumed that the server has better information about
2289  * which protocol a client should use. 4) If the client doesn't support any
2290  * of the server's advertised protocols, then this is treated the same as
2291  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2292  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2293  */
2294 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2295                           const unsigned char *server,
2296                           unsigned int server_len,
2297                           const unsigned char *client, unsigned int client_len)
2298 {
2299     unsigned int i, j;
2300     const unsigned char *result;
2301     int status = OPENSSL_NPN_UNSUPPORTED;
2302
2303     /*
2304      * For each protocol in server preference order, see if we support it.
2305      */
2306     for (i = 0; i < server_len;) {
2307         for (j = 0; j < client_len;) {
2308             if (server[i] == client[j] &&
2309                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2310                 /* We found a match */
2311                 result = &server[i];
2312                 status = OPENSSL_NPN_NEGOTIATED;
2313                 goto found;
2314             }
2315             j += client[j];
2316             j++;
2317         }
2318         i += server[i];
2319         i++;
2320     }
2321
2322     /* There's no overlap between our protocols and the server's list. */
2323     result = client;
2324     status = OPENSSL_NPN_NO_OVERLAP;
2325
2326  found:
2327     *out = (unsigned char *)result + 1;
2328     *outlen = result[0];
2329     return status;
2330 }
2331
2332 #ifndef OPENSSL_NO_NEXTPROTONEG
2333 /*
2334  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2335  * client's requested protocol for this connection and returns 0. If the
2336  * client didn't request any protocol, then *data is set to NULL. Note that
2337  * the client can request any protocol it chooses. The value returned from
2338  * this function need not be a member of the list of supported protocols
2339  * provided by the callback.
2340  */
2341 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2342                                     unsigned *len)
2343 {
2344     *data = s->next_proto_negotiated;
2345     if (!*data) {
2346         *len = 0;
2347     } else {
2348         *len = s->next_proto_negotiated_len;
2349     }
2350 }
2351
2352 /*
2353  * SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when
2354  * a TLS server needs a list of supported protocols for Next Protocol
2355  * Negotiation. The returned list must be in wire format.  The list is
2356  * returned by setting |out| to point to it and |outlen| to its length. This
2357  * memory will not be modified, but one should assume that the SSL* keeps a
2358  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2359  * wishes to advertise. Otherwise, no such extension will be included in the
2360  * ServerHello.
2361  */
2362 void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx,
2363                                            int (*cb) (SSL *ssl,
2364                                                       const unsigned char
2365                                                       **out,
2366                                                       unsigned int *outlen,
2367                                                       void *arg), void *arg)
2368 {
2369     ctx->next_protos_advertised_cb = cb;
2370     ctx->next_protos_advertised_cb_arg = arg;
2371 }
2372
2373 /*
2374  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2375  * client needs to select a protocol from the server's provided list. |out|
2376  * must be set to point to the selected protocol (which may be within |in|).
2377  * The length of the protocol name must be written into |outlen|. The
2378  * server's advertised protocols are provided in |in| and |inlen|. The
2379  * callback can assume that |in| is syntactically valid. The client must
2380  * select a protocol. It is fatal to the connection if this callback returns
2381  * a value other than SSL_TLSEXT_ERR_OK.
2382  */
2383 void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,
2384                                       int (*cb) (SSL *s, unsigned char **out,
2385                                                  unsigned char *outlen,
2386                                                  const unsigned char *in,
2387                                                  unsigned int inlen,
2388                                                  void *arg), void *arg)
2389 {
2390     ctx->next_proto_select_cb = cb;
2391     ctx->next_proto_select_cb_arg = arg;
2392 }
2393 #endif
2394
2395 /*
2396  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2397  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2398  * length-prefixed strings). Returns 0 on success.
2399  */
2400 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2401                             unsigned int protos_len)
2402 {
2403     OPENSSL_free(ctx->alpn_client_proto_list);
2404     ctx->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2405     if (ctx->alpn_client_proto_list == NULL) {
2406         SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2407         return 1;
2408     }
2409     ctx->alpn_client_proto_list_len = protos_len;
2410
2411     return 0;
2412 }
2413
2414 /*
2415  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2416  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2417  * length-prefixed strings). Returns 0 on success.
2418  */
2419 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2420                         unsigned int protos_len)
2421 {
2422     OPENSSL_free(ssl->alpn_client_proto_list);
2423     ssl->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2424     if (ssl->alpn_client_proto_list == NULL) {
2425         SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2426         return 1;
2427     }
2428     ssl->alpn_client_proto_list_len = protos_len;
2429
2430     return 0;
2431 }
2432
2433 /*
2434  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2435  * called during ClientHello processing in order to select an ALPN protocol
2436  * from the client's list of offered protocols.
2437  */
2438 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2439                                 int (*cb) (SSL *ssl,
2440                                            const unsigned char **out,
2441                                            unsigned char *outlen,
2442                                            const unsigned char *in,
2443                                            unsigned int inlen,
2444                                            void *arg), void *arg)
2445 {
2446     ctx->alpn_select_cb = cb;
2447     ctx->alpn_select_cb_arg = arg;
2448 }
2449
2450 /*
2451  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
2452  * On return it sets |*data| to point to |*len| bytes of protocol name
2453  * (not including the leading length-prefix byte). If the server didn't
2454  * respond with a negotiated protocol then |*len| will be zero.
2455  */
2456 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
2457                             unsigned int *len)
2458 {
2459     *data = NULL;
2460     if (ssl->s3)
2461         *data = ssl->s3->alpn_selected;
2462     if (*data == NULL)
2463         *len = 0;
2464     else
2465         *len = ssl->s3->alpn_selected_len;
2466 }
2467
2468 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2469                                const char *label, size_t llen,
2470                                const unsigned char *context, size_t contextlen,
2471                                int use_context)
2472 {
2473     if (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER)
2474         return -1;
2475
2476     return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
2477                                                        llen, context,
2478                                                        contextlen, use_context);
2479 }
2480
2481 static unsigned long ssl_session_hash(const SSL_SESSION *a)
2482 {
2483     const unsigned char *session_id = a->session_id;
2484     unsigned long l;
2485     unsigned char tmp_storage[4];
2486
2487     if (a->session_id_length < sizeof(tmp_storage)) {
2488         memset(tmp_storage, 0, sizeof(tmp_storage));
2489         memcpy(tmp_storage, a->session_id, a->session_id_length);
2490         session_id = tmp_storage;
2491     }
2492
2493     l = (unsigned long)
2494         ((unsigned long)session_id[0]) |
2495         ((unsigned long)session_id[1] << 8L) |
2496         ((unsigned long)session_id[2] << 16L) |
2497         ((unsigned long)session_id[3] << 24L);
2498     return (l);
2499 }
2500
2501 /*
2502  * NB: If this function (or indeed the hash function which uses a sort of
2503  * coarser function than this one) is changed, ensure
2504  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
2505  * being able to construct an SSL_SESSION that will collide with any existing
2506  * session with a matching session ID.
2507  */
2508 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
2509 {
2510     if (a->ssl_version != b->ssl_version)
2511         return (1);
2512     if (a->session_id_length != b->session_id_length)
2513         return (1);
2514     return (memcmp(a->session_id, b->session_id, a->session_id_length));
2515 }
2516
2517 /*
2518  * These wrapper functions should remain rather than redeclaring
2519  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
2520  * variable. The reason is that the functions aren't static, they're exposed
2521  * via ssl.h.
2522  */
2523
2524 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
2525 {
2526     SSL_CTX *ret = NULL;
2527
2528     if (meth == NULL) {
2529         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
2530         return (NULL);
2531     }
2532
2533     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
2534         return NULL;
2535
2536     if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
2537         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE);
2538         return NULL;
2539     }
2540
2541     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
2542         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
2543         goto err;
2544     }
2545     ret = OPENSSL_zalloc(sizeof(*ret));
2546     if (ret == NULL)
2547         goto err;
2548
2549     ret->method = meth;
2550     ret->min_proto_version = 0;
2551     ret->max_proto_version = 0;
2552     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
2553     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
2554     /* We take the system default. */
2555     ret->session_timeout = meth->get_timeout();
2556     ret->references = 1;
2557     ret->lock = CRYPTO_THREAD_lock_new();
2558     if (ret->lock == NULL) {
2559         SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2560         OPENSSL_free(ret);
2561         return NULL;
2562     }
2563     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
2564     ret->verify_mode = SSL_VERIFY_NONE;
2565     if ((ret->cert = ssl_cert_new()) == NULL)
2566         goto err;
2567
2568     ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2569     if (ret->sessions == NULL)
2570         goto err;
2571     ret->cert_store = X509_STORE_new();
2572     if (ret->cert_store == NULL)
2573         goto err;
2574 #ifndef OPENSSL_NO_CT
2575     ret->ctlog_store = CTLOG_STORE_new();
2576     if (ret->ctlog_store == NULL)
2577         goto err;
2578 #endif
2579     if (!ssl_create_cipher_list(ret->method,
2580                                 &ret->cipher_list, &ret->cipher_list_by_id,
2581                                 SSL_DEFAULT_CIPHER_LIST, ret->cert)
2582         || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2583         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2584         goto err2;
2585     }
2586
2587     ret->param = X509_VERIFY_PARAM_new();
2588     if (ret->param == NULL)
2589         goto err;
2590
2591     if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
2592         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
2593         goto err2;
2594     }
2595     if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
2596         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
2597         goto err2;
2598     }
2599
2600     if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
2601         goto err;
2602
2603     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data))
2604         goto err;
2605
2606     /* No compression for DTLS */
2607     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
2608         ret->comp_methods = SSL_COMP_get_compression_methods();
2609
2610     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2611     ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2612
2613     /* Setup RFC5077 ticket keys */
2614     if ((RAND_bytes(ret->tlsext_tick_key_name,
2615                     sizeof(ret->tlsext_tick_key_name)) <= 0)
2616         || (RAND_bytes(ret->tlsext_tick_hmac_key,
2617                        sizeof(ret->tlsext_tick_hmac_key)) <= 0)
2618         || (RAND_bytes(ret->tlsext_tick_aes_key,
2619                        sizeof(ret->tlsext_tick_aes_key)) <= 0))
2620         ret->options |= SSL_OP_NO_TICKET;
2621
2622 #ifndef OPENSSL_NO_SRP
2623     if (!SSL_CTX_SRP_CTX_init(ret))
2624         goto err;
2625 #endif
2626 #ifndef OPENSSL_NO_ENGINE
2627 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2628 #  define eng_strx(x)     #x
2629 #  define eng_str(x)      eng_strx(x)
2630     /* Use specific client engine automatically... ignore errors */
2631     {
2632         ENGINE *eng;
2633         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2634         if (!eng) {
2635             ERR_clear_error();
2636             ENGINE_load_builtin_engines();
2637             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2638         }
2639         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2640             ERR_clear_error();
2641     }
2642 # endif
2643 #endif
2644     /*
2645      * Default is to connect to non-RI servers. When RI is more widely
2646      * deployed might change this.
2647      */
2648     ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2649     /*
2650      * Disable compression by default to prevent CRIME. Applications can
2651      * re-enable compression by configuring
2652      * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
2653      * or by using the SSL_CONF library.
2654      */
2655     ret->options |= SSL_OP_NO_COMPRESSION;
2656
2657     ret->tlsext_status_type = -1;
2658
2659     return ret;
2660  err:
2661     SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2662  err2:
2663     SSL_CTX_free(ret);
2664     return NULL;
2665 }
2666
2667 int SSL_CTX_up_ref(SSL_CTX *ctx)
2668 {
2669     int i;
2670
2671     if (CRYPTO_atomic_add(&ctx->references, 1, &i, ctx->lock) <= 0)
2672         return 0;
2673
2674     REF_PRINT_COUNT("SSL_CTX", ctx);
2675     REF_ASSERT_ISNT(i < 2);
2676     return ((i > 1) ? 1 : 0);
2677 }
2678
2679 void SSL_CTX_free(SSL_CTX *a)
2680 {
2681     int i;
2682
2683     if (a == NULL)
2684         return;
2685
2686     CRYPTO_atomic_add(&a->references, -1, &i, a->lock);
2687     REF_PRINT_COUNT("SSL_CTX", a);
2688     if (i > 0)
2689         return;
2690     REF_ASSERT_ISNT(i < 0);
2691
2692     X509_VERIFY_PARAM_free(a->param);
2693     dane_ctx_final(&a->dane);
2694
2695     /*
2696      * Free internal session cache. However: the remove_cb() may reference
2697      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2698      * after the sessions were flushed.
2699      * As the ex_data handling routines might also touch the session cache,
2700      * the most secure solution seems to be: empty (flush) the cache, then
2701      * free ex_data, then finally free the cache.
2702      * (See ticket [openssl.org #212].)
2703      */
2704     if (a->sessions != NULL)
2705         SSL_CTX_flush_sessions(a, 0);
2706
2707     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2708     lh_SSL_SESSION_free(a->sessions);
2709     X509_STORE_free(a->cert_store);
2710 #ifndef OPENSSL_NO_CT
2711     CTLOG_STORE_free(a->ctlog_store);
2712 #endif
2713     sk_SSL_CIPHER_free(a->cipher_list);
2714     sk_SSL_CIPHER_free(a->cipher_list_by_id);
2715     ssl_cert_free(a->cert);
2716     sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
2717     sk_X509_pop_free(a->extra_certs, X509_free);
2718     a->comp_methods = NULL;
2719 #ifndef OPENSSL_NO_SRTP
2720     sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2721 #endif
2722 #ifndef OPENSSL_NO_SRP
2723     SSL_CTX_SRP_CTX_free(a);
2724 #endif
2725 #ifndef OPENSSL_NO_ENGINE
2726     ENGINE_finish(a->client_cert_engine);
2727 #endif
2728
2729 #ifndef OPENSSL_NO_EC
2730     OPENSSL_free(a->tlsext_ecpointformatlist);
2731     OPENSSL_free(a->tlsext_ellipticcurvelist);
2732 #endif
2733     OPENSSL_free(a->alpn_client_proto_list);
2734
2735     CRYPTO_THREAD_lock_free(a->lock);
2736
2737     OPENSSL_free(a);
2738 }
2739
2740 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2741 {
2742     ctx->default_passwd_callback = cb;
2743 }
2744
2745 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2746 {
2747     ctx->default_passwd_callback_userdata = u;
2748 }
2749
2750 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2751 {
2752     return ctx->default_passwd_callback;
2753 }
2754
2755 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2756 {
2757     return ctx->default_passwd_callback_userdata;
2758 }
2759
2760 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
2761 {
2762     s->default_passwd_callback = cb;
2763 }
2764
2765 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
2766 {
2767     s->default_passwd_callback_userdata = u;
2768 }
2769
2770 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
2771 {
2772     return s->default_passwd_callback;
2773 }
2774
2775 void *SSL_get_default_passwd_cb_userdata(SSL *s)
2776 {
2777     return s->default_passwd_callback_userdata;
2778 }
2779
2780 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2781                                       int (*cb) (X509_STORE_CTX *, void *),
2782                                       void *arg)
2783 {
2784     ctx->app_verify_callback = cb;
2785     ctx->app_verify_arg = arg;
2786 }
2787
2788 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
2789                         int (*cb) (int, X509_STORE_CTX *))
2790 {
2791     ctx->verify_mode = mode;
2792     ctx->default_verify_callback = cb;
2793 }
2794
2795 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2796 {
2797     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2798 }
2799
2800 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
2801 {
2802     ssl_cert_set_cert_cb(c->cert, cb, arg);
2803 }
2804
2805 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
2806 {
2807     ssl_cert_set_cert_cb(s->cert, cb, arg);
2808 }
2809
2810 void ssl_set_masks(SSL *s)
2811 {
2812 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_GOST)
2813     CERT_PKEY *cpk;
2814 #endif
2815     CERT *c = s->cert;
2816     uint32_t *pvalid = s->s3->tmp.valid_flags;
2817     int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
2818     unsigned long mask_k, mask_a;
2819 #ifndef OPENSSL_NO_EC
2820     int have_ecc_cert, ecdsa_ok;
2821     X509 *x = NULL;
2822 #endif
2823     if (c == NULL)
2824         return;
2825
2826 #ifndef OPENSSL_NO_DH
2827     dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
2828 #else
2829     dh_tmp = 0;
2830 #endif
2831
2832     rsa_enc = pvalid[SSL_PKEY_RSA_ENC] & CERT_PKEY_VALID;
2833     rsa_sign = pvalid[SSL_PKEY_RSA_SIGN] & CERT_PKEY_SIGN;
2834     dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_SIGN;
2835 #ifndef OPENSSL_NO_EC
2836     have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
2837 #endif
2838     mask_k = 0;
2839     mask_a = 0;
2840
2841 #ifdef CIPHER_DEBUG
2842     fprintf(stderr, "dht=%d re=%d rs=%d ds=%d\n",
2843             dh_tmp, rsa_enc, rsa_sign, dsa_sign);
2844 #endif
2845
2846 #ifndef OPENSSL_NO_GOST
2847     cpk = &(c->pkeys[SSL_PKEY_GOST12_512]);
2848     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2849         mask_k |= SSL_kGOST;
2850         mask_a |= SSL_aGOST12;
2851     }
2852     cpk = &(c->pkeys[SSL_PKEY_GOST12_256]);
2853     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2854         mask_k |= SSL_kGOST;
2855         mask_a |= SSL_aGOST12;
2856     }
2857     cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2858     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2859         mask_k |= SSL_kGOST;
2860         mask_a |= SSL_aGOST01;
2861     }
2862 #endif
2863
2864     if (rsa_enc)
2865         mask_k |= SSL_kRSA;
2866
2867     if (dh_tmp)
2868         mask_k |= SSL_kDHE;
2869
2870     if (rsa_enc || rsa_sign) {
2871         mask_a |= SSL_aRSA;
2872     }
2873
2874     if (dsa_sign) {
2875         mask_a |= SSL_aDSS;
2876     }
2877
2878     mask_a |= SSL_aNULL;
2879
2880     /*
2881      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
2882      * depending on the key usage extension.
2883      */
2884 #ifndef OPENSSL_NO_EC
2885     if (have_ecc_cert) {
2886         uint32_t ex_kusage;
2887         cpk = &c->pkeys[SSL_PKEY_ECC];
2888         x = cpk->x509;
2889         ex_kusage = X509_get_key_usage(x);
2890         ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
2891         if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
2892             ecdsa_ok = 0;
2893         if (ecdsa_ok)
2894             mask_a |= SSL_aECDSA;
2895     }
2896 #endif
2897
2898 #ifndef OPENSSL_NO_EC
2899     mask_k |= SSL_kECDHE;
2900 #endif
2901
2902 #ifndef OPENSSL_NO_PSK
2903     mask_k |= SSL_kPSK;
2904     mask_a |= SSL_aPSK;
2905     if (mask_k & SSL_kRSA)
2906         mask_k |= SSL_kRSAPSK;
2907     if (mask_k & SSL_kDHE)
2908         mask_k |= SSL_kDHEPSK;
2909     if (mask_k & SSL_kECDHE)
2910         mask_k |= SSL_kECDHEPSK;
2911 #endif
2912
2913     s->s3->tmp.mask_k = mask_k;
2914     s->s3->tmp.mask_a = mask_a;
2915 }
2916
2917 #ifndef OPENSSL_NO_EC
2918
2919 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2920 {
2921     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
2922         /* key usage, if present, must allow signing */
2923         if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
2924             SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2925                    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2926             return 0;
2927         }
2928     }
2929     return 1;                   /* all checks are ok */
2930 }
2931
2932 #endif
2933
2934 static int ssl_get_server_cert_index(const SSL *s)
2935 {
2936     int idx;
2937     idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
2938     if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
2939         idx = SSL_PKEY_RSA_SIGN;
2940     if (idx == SSL_PKEY_GOST_EC) {
2941         if (s->cert->pkeys[SSL_PKEY_GOST12_512].x509)
2942             idx = SSL_PKEY_GOST12_512;
2943         else if (s->cert->pkeys[SSL_PKEY_GOST12_256].x509)
2944             idx = SSL_PKEY_GOST12_256;
2945         else if (s->cert->pkeys[SSL_PKEY_GOST01].x509)
2946             idx = SSL_PKEY_GOST01;
2947         else
2948             idx = -1;
2949     }
2950     if (idx == -1)
2951         SSLerr(SSL_F_SSL_GET_SERVER_CERT_INDEX, ERR_R_INTERNAL_ERROR);
2952     return idx;
2953 }
2954
2955 CERT_PKEY *ssl_get_server_send_pkey(SSL *s)
2956 {
2957     CERT *c;
2958     int i;
2959
2960     c = s->cert;
2961     if (!s->s3 || !s->s3->tmp.new_cipher)
2962         return NULL;
2963     ssl_set_masks(s);
2964
2965     i = ssl_get_server_cert_index(s);
2966
2967     /* This may or may not be an error. */
2968     if (i < 0)
2969         return NULL;
2970
2971     /* May be NULL. */
2972     return &c->pkeys[i];
2973 }
2974
2975 EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher,
2976                             const EVP_MD **pmd)
2977 {
2978     unsigned long alg_a;
2979     CERT *c;
2980     int idx = -1;
2981
2982     alg_a = cipher->algorithm_auth;
2983     c = s->cert;
2984
2985     if ((alg_a & SSL_aDSS) && (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2986         idx = SSL_PKEY_DSA_SIGN;
2987     else if (alg_a & SSL_aRSA) {
2988         if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2989             idx = SSL_PKEY_RSA_SIGN;
2990         else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2991             idx = SSL_PKEY_RSA_ENC;
2992     } else if ((alg_a & SSL_aECDSA) &&
2993                (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2994         idx = SSL_PKEY_ECC;
2995     if (idx == -1) {
2996         SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2997         return (NULL);
2998     }
2999     if (pmd)
3000         *pmd = s->s3->tmp.md[idx];
3001     return c->pkeys[idx].privatekey;
3002 }
3003
3004 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
3005                                    size_t *serverinfo_length)
3006 {
3007     CERT *c = NULL;
3008     int i = 0;
3009     *serverinfo_length = 0;
3010
3011     c = s->cert;
3012     i = ssl_get_server_cert_index(s);
3013
3014     if (i == -1)
3015         return 0;
3016     if (c->pkeys[i].serverinfo == NULL)
3017         return 0;
3018
3019     *serverinfo = c->pkeys[i].serverinfo;
3020     *serverinfo_length = c->pkeys[i].serverinfo_length;
3021     return 1;
3022 }
3023
3024 void ssl_update_cache(SSL *s, int mode)
3025 {
3026     int i;
3027
3028     /*
3029      * If the session_id_length is 0, we are not supposed to cache it, and it
3030      * would be rather hard to do anyway :-)
3031      */
3032     if (s->session->session_id_length == 0)
3033         return;
3034
3035     /*
3036      * If sid_ctx_length is 0 there is no specific application context
3037      * associated with this session, so when we try to resume it and
3038      * SSL_VERIFY_PEER is requested, we have no indication that this is
3039      * actually a session for the proper application context, and the
3040      * *handshake* will fail, not just the resumption attempt.
3041      * Do not cache these sessions that are not resumable.
3042      */
3043     if (s->session->sid_ctx_length == 0
3044             && (s->verify_mode & SSL_VERIFY_PEER) != 0)
3045         return;
3046
3047     i = s->session_ctx->session_cache_mode;
3048     if ((i & mode) && (!s->hit)
3049         && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
3050             || SSL_CTX_add_session(s->session_ctx, s->session))
3051         && (s->session_ctx->new_session_cb != NULL)) {
3052         SSL_SESSION_up_ref(s->session);
3053         if (!s->session_ctx->new_session_cb(s, s->session))
3054             SSL_SESSION_free(s->session);
3055     }
3056
3057     /* auto flush every 255 connections */
3058     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
3059         if ((((mode & SSL_SESS_CACHE_CLIENT)
3060               ? s->session_ctx->stats.sess_connect_good
3061               : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
3062             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
3063         }
3064     }
3065 }
3066
3067 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
3068 {
3069     return ctx->method;
3070 }
3071
3072 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
3073 {
3074     return (s->method);
3075 }
3076
3077 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
3078 {
3079     int ret = 1;
3080
3081     if (s->method != meth) {
3082         const SSL_METHOD *sm = s->method;
3083         int (*hf) (SSL *) = s->handshake_func;
3084
3085         if (sm->version == meth->version)
3086             s->method = meth;
3087         else {
3088             sm->ssl_free(s);
3089             s->method = meth;
3090             ret = s->method->ssl_new(s);
3091         }
3092
3093         if (hf == sm->ssl_connect)
3094             s->handshake_func = meth->ssl_connect;
3095         else if (hf == sm->ssl_accept)
3096             s->handshake_func = meth->ssl_accept;
3097     }
3098     return (ret);
3099 }
3100
3101 int SSL_get_error(const SSL *s, int i)
3102 {
3103     int reason;
3104     unsigned long l;
3105     BIO *bio;
3106
3107     if (i > 0)
3108         return (SSL_ERROR_NONE);
3109
3110     /*
3111      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
3112      * where we do encode the error
3113      */
3114     if ((l = ERR_peek_error()) != 0) {
3115         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
3116             return (SSL_ERROR_SYSCALL);
3117         else
3118             return (SSL_ERROR_SSL);
3119     }
3120
3121     if (i < 0) {
3122         if (SSL_want_read(s)) {
3123             bio = SSL_get_rbio(s);
3124             if (BIO_should_read(bio))
3125                 return (SSL_ERROR_WANT_READ);
3126             else if (BIO_should_write(bio))
3127                 /*
3128                  * This one doesn't make too much sense ... We never try to write
3129                  * to the rbio, and an application program where rbio and wbio
3130                  * are separate couldn't even know what it should wait for.
3131                  * However if we ever set s->rwstate incorrectly (so that we have
3132                  * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
3133                  * wbio *are* the same, this test works around that bug; so it
3134                  * might be safer to keep it.
3135                  */
3136                 return (SSL_ERROR_WANT_WRITE);
3137             else if (BIO_should_io_special(bio)) {
3138                 reason = BIO_get_retry_reason(bio);
3139                 if (reason == BIO_RR_CONNECT)
3140                     return (SSL_ERROR_WANT_CONNECT);
3141                 else if (reason == BIO_RR_ACCEPT)
3142                     return (SSL_ERROR_WANT_ACCEPT);
3143                 else
3144                     return (SSL_ERROR_SYSCALL); /* unknown */
3145             }
3146         }
3147
3148         if (SSL_want_write(s)) {
3149             /*
3150              * Access wbio directly - in order to use the buffered bio if
3151              * present
3152              */
3153             bio = s->wbio;
3154             if (BIO_should_write(bio))
3155                 return (SSL_ERROR_WANT_WRITE);
3156             else if (BIO_should_read(bio))
3157                 /*
3158                  * See above (SSL_want_read(s) with BIO_should_write(bio))
3159                  */
3160                 return (SSL_ERROR_WANT_READ);
3161             else if (BIO_should_io_special(bio)) {
3162                 reason = BIO_get_retry_reason(bio);
3163                 if (reason == BIO_RR_CONNECT)
3164                     return (SSL_ERROR_WANT_CONNECT);
3165                 else if (reason == BIO_RR_ACCEPT)
3166                     return (SSL_ERROR_WANT_ACCEPT);
3167                 else
3168                     return (SSL_ERROR_SYSCALL);
3169             }
3170         }
3171         if (SSL_want_x509_lookup(s)) {
3172             return (SSL_ERROR_WANT_X509_LOOKUP);
3173         }
3174         if (SSL_want_async(s)) {
3175             return SSL_ERROR_WANT_ASYNC;
3176         }
3177         if (SSL_want_async_job(s)) {
3178             return SSL_ERROR_WANT_ASYNC_JOB;
3179         }
3180     }
3181
3182     if (i == 0) {
3183         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
3184             (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
3185             return (SSL_ERROR_ZERO_RETURN);
3186     }
3187     return (SSL_ERROR_SYSCALL);
3188 }
3189
3190 static int ssl_do_handshake_intern(void *vargs)
3191 {
3192     struct ssl_async_args *args;
3193     SSL *s;
3194
3195     args = (struct ssl_async_args *)vargs;
3196     s = args->s;
3197
3198     return s->handshake_func(s);
3199 }
3200
3201 int SSL_do_handshake(SSL *s)
3202 {
3203     int ret = 1;
3204
3205     if (s->handshake_func == NULL) {
3206         SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3207         return -1;
3208     }
3209
3210     s->method->ssl_renegotiate_check(s);
3211
3212     if (SSL_in_init(s) || SSL_in_before(s)) {
3213         if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3214             struct ssl_async_args args;
3215
3216             args.s = s;
3217
3218             ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3219         } else {
3220             ret = s->handshake_func(s);
3221         }
3222     }
3223     return ret;
3224 }
3225
3226 void SSL_set_accept_state(SSL *s)
3227 {
3228     s->server = 1;
3229     s->shutdown = 0;
3230     ossl_statem_clear(s);
3231     s->handshake_func = s->method->ssl_accept;
3232     clear_ciphers(s);
3233 }
3234
3235 void SSL_set_connect_state(SSL *s)
3236 {
3237     s->server = 0;
3238     s->shutdown = 0;
3239     ossl_statem_clear(s);
3240     s->handshake_func = s->method->ssl_connect;
3241     clear_ciphers(s);
3242 }
3243
3244 int ssl_undefined_function(SSL *s)
3245 {
3246     SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3247     return (0);
3248 }
3249
3250 int ssl_undefined_void_function(void)
3251 {
3252     SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3253            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3254     return (0);
3255 }
3256
3257 int ssl_undefined_const_function(const SSL *s)
3258 {
3259     return (0);
3260 }
3261
3262 const SSL_METHOD *ssl_bad_method(int ver)
3263 {
3264     SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3265     return (NULL);
3266 }
3267
3268 const char *ssl_protocol_to_string(int version)
3269 {
3270     if (version == TLS1_2_VERSION)
3271         return "TLSv1.2";
3272     else if (version == TLS1_1_VERSION)
3273         return "TLSv1.1";
3274     else if (version == TLS1_VERSION)
3275         return "TLSv1";
3276     else if (version == SSL3_VERSION)
3277         return "SSLv3";
3278     else if (version == DTLS1_BAD_VER)
3279         return "DTLSv0.9";
3280     else if (version == DTLS1_VERSION)
3281         return "DTLSv1";
3282     else if (version == DTLS1_2_VERSION)
3283         return "DTLSv1.2";
3284     else
3285         return ("unknown");
3286 }
3287
3288 const char *SSL_get_version(const SSL *s)
3289 {
3290     return ssl_protocol_to_string(s->version);
3291 }
3292
3293 SSL *SSL_dup(SSL *s)
3294 {
3295     STACK_OF(X509_NAME) *sk;
3296     X509_NAME *xn;
3297     SSL *ret;
3298     int i;
3299
3300     /* If we're not quiescent, just up_ref! */
3301     if (!SSL_in_init(s) || !SSL_in_before(s)) {
3302         CRYPTO_atomic_add(&s->references, 1, &i, s->lock);
3303         return s;
3304     }
3305
3306     /*
3307      * Otherwise, copy configuration state, and session if set.
3308      */
3309     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3310         return (NULL);
3311
3312     if (s->session != NULL) {
3313         /*
3314          * Arranges to share the same session via up_ref.  This "copies"
3315          * session-id, SSL_METHOD, sid_ctx, and 'cert'
3316          */
3317         if (!SSL_copy_session_id(ret, s))
3318             goto err;
3319     } else {
3320         /*
3321          * No session has been established yet, so we have to expect that
3322          * s->cert or ret->cert will be changed later -- they should not both
3323          * point to the same object, and thus we can't use
3324          * SSL_copy_session_id.
3325          */
3326         if (!SSL_set_ssl_method(ret, s->method))
3327             goto err;
3328
3329         if (s->cert != NULL) {
3330             ssl_cert_free(ret->cert);
3331             ret->cert = ssl_cert_dup(s->cert);
3332             if (ret->cert == NULL)
3333                 goto err;
3334         }
3335
3336         if (!SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length))
3337             goto err;
3338     }
3339
3340     if (!ssl_dane_dup(ret, s))
3341         goto err;
3342     ret->version = s->version;
3343     ret->options = s->options;
3344     ret->mode = s->mode;
3345     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3346     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3347     ret->msg_callback = s->msg_callback;
3348     ret->msg_callback_arg = s->msg_callback_arg;
3349     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3350     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
3351     ret->generate_session_id = s->generate_session_id;
3352
3353     SSL_set_info_callback(ret, SSL_get_info_callback(s));
3354
3355     /* copy app data, a little dangerous perhaps */
3356     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
3357         goto err;
3358
3359     /* setup rbio, and wbio */
3360     if (s->rbio != NULL) {
3361         if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
3362             goto err;
3363     }
3364     if (s->wbio != NULL) {
3365         if (s->wbio != s->rbio) {
3366             if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
3367                 goto err;
3368         } else {
3369             BIO_up_ref(ret->rbio);
3370             ret->wbio = ret->rbio;
3371         }
3372     }
3373
3374     ret->server = s->server;
3375     if (s->handshake_func) {
3376         if (s->server)
3377             SSL_set_accept_state(ret);
3378         else
3379             SSL_set_connect_state(ret);
3380     }
3381     ret->shutdown = s->shutdown;
3382     ret->hit = s->hit;
3383
3384     ret->default_passwd_callback = s->default_passwd_callback;
3385     ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
3386
3387     X509_VERIFY_PARAM_inherit(ret->param, s->param);
3388
3389     /* dup the cipher_list and cipher_list_by_id stacks */
3390     if (s->cipher_list != NULL) {
3391         if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
3392             goto err;
3393     }
3394     if (s->cipher_list_by_id != NULL)
3395         if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
3396             == NULL)
3397             goto err;
3398
3399     /* Dup the client_CA list */
3400     if (s->client_CA != NULL) {
3401         if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
3402             goto err;
3403         ret->client_CA = sk;
3404         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
3405             xn = sk_X509_NAME_value(sk, i);
3406             if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
3407                 X509_NAME_free(xn);
3408                 goto err;
3409             }
3410         }
3411     }
3412     return ret;
3413
3414  err:
3415     SSL_free(ret);
3416     return NULL;
3417 }
3418
3419 void ssl_clear_cipher_ctx(SSL *s)
3420 {
3421     if (s->enc_read_ctx != NULL) {
3422         EVP_CIPHER_CTX_free(s->enc_read_ctx);
3423         s->enc_read_ctx = NULL;
3424     }
3425     if (s->enc_write_ctx != NULL) {
3426         EVP_CIPHER_CTX_free(s->enc_write_ctx);
3427         s->enc_write_ctx = NULL;
3428     }
3429 #ifndef OPENSSL_NO_COMP
3430     COMP_CTX_free(s->expand);
3431     s->expand = NULL;
3432     COMP_CTX_free(s->compress);
3433     s->compress = NULL;
3434 #endif
3435 }
3436
3437 X509 *SSL_get_certificate(const SSL *s)
3438 {
3439     if (s->cert != NULL)
3440         return (s->cert->key->x509);
3441     else
3442         return (NULL);
3443 }
3444
3445 EVP_PKEY *SSL_get_privatekey(const SSL *s)
3446 {
3447     if (s->cert != NULL)
3448         return (s->cert->key->privatekey);
3449     else
3450         return (NULL);
3451 }
3452
3453 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3454 {
3455     if (ctx->cert != NULL)
3456         return ctx->cert->key->x509;
3457     else
3458         return NULL;
3459 }
3460
3461 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3462 {
3463     if (ctx->cert != NULL)
3464         return ctx->cert->key->privatekey;
3465     else
3466         return NULL;
3467 }
3468
3469 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
3470 {
3471     if ((s->session != NULL) && (s->session->cipher != NULL))
3472         return (s->session->cipher);
3473     return (NULL);
3474 }
3475
3476 const COMP_METHOD *SSL_get_current_compression(SSL *s)
3477 {
3478 #ifndef OPENSSL_NO_COMP
3479     return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
3480 #else
3481     return NULL;
3482 #endif
3483 }
3484
3485 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
3486 {
3487 #ifndef OPENSSL_NO_COMP
3488     return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
3489 #else
3490     return NULL;
3491 #endif
3492 }
3493
3494 int ssl_init_wbio_buffer(SSL *s)
3495 {
3496     BIO *bbio;
3497
3498     if (s->bbio != NULL) {
3499         /* Already buffered. */
3500         return 1;
3501     }
3502
3503     bbio = BIO_new(BIO_f_buffer());
3504     if (bbio == NULL || !BIO_set_read_buffer_size(bbio, 1)) {
3505         BIO_free(bbio);
3506         SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
3507         return 0;
3508     }
3509     s->bbio = bbio;
3510     s->wbio = BIO_push(bbio, s->wbio);
3511
3512     return 1;
3513 }
3514
3515 void ssl_free_wbio_buffer(SSL *s)
3516 {
3517     /* callers ensure s is never null */
3518     if (s->bbio == NULL)
3519         return;
3520
3521     s->wbio = BIO_pop(s->wbio);
3522     assert(s->wbio != NULL);
3523     BIO_free(s->bbio);
3524     s->bbio = NULL;
3525 }
3526
3527 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3528 {
3529     ctx->quiet_shutdown = mode;
3530 }
3531
3532 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3533 {
3534     return (ctx->quiet_shutdown);
3535 }
3536
3537 void SSL_set_quiet_shutdown(SSL *s, int mode)
3538 {
3539     s->quiet_shutdown = mode;
3540 }
3541
3542 int SSL_get_quiet_shutdown(const SSL *s)
3543 {
3544     return (s->quiet_shutdown);
3545 }
3546
3547 void SSL_set_shutdown(SSL *s, int mode)
3548 {
3549     s->shutdown = mode;
3550 }
3551
3552 int SSL_get_shutdown(const SSL *s)
3553 {
3554     return s->shutdown;
3555 }
3556
3557 int SSL_version(const SSL *s)
3558 {
3559     return s->version;
3560 }
3561
3562 int SSL_client_version(const SSL *s)
3563 {
3564     return s->client_version;
3565 }
3566
3567 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3568 {
3569     return ssl->ctx;
3570 }
3571
3572 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3573 {
3574     CERT *new_cert;
3575     if (ssl->ctx == ctx)
3576         return ssl->ctx;
3577     if (ctx == NULL)
3578         ctx = ssl->session_ctx;
3579     new_cert = ssl_cert_dup(ctx->cert);
3580     if (new_cert == NULL) {
3581         return NULL;
3582     }
3583
3584     if (!custom_exts_copy_flags(&new_cert->srv_ext, &ssl->cert->srv_ext)) {
3585         ssl_cert_free(new_cert);
3586         return NULL;
3587     }
3588
3589     ssl_cert_free(ssl->cert);
3590     ssl->cert = new_cert;
3591
3592     /*
3593      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3594      * so setter APIs must prevent invalid lengths from entering the system.
3595      */
3596     OPENSSL_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
3597
3598     /*
3599      * If the session ID context matches that of the parent SSL_CTX,
3600      * inherit it from the new SSL_CTX as well. If however the context does
3601      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3602      * leave it unchanged.
3603      */
3604     if ((ssl->ctx != NULL) &&
3605         (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3606         (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3607         ssl->sid_ctx_length = ctx->sid_ctx_length;
3608         memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3609     }
3610
3611     SSL_CTX_up_ref(ctx);
3612     SSL_CTX_free(ssl->ctx);     /* decrement reference count */
3613     ssl->ctx = ctx;
3614
3615     return ssl->ctx;
3616 }
3617
3618 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3619 {
3620     return (X509_STORE_set_default_paths(ctx->cert_store));
3621 }
3622
3623 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
3624 {
3625     X509_LOOKUP *lookup;
3626
3627     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
3628     if (lookup == NULL)
3629         return 0;
3630     X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
3631
3632     /* Clear any errors if the default directory does not exist */
3633     ERR_clear_error();
3634
3635     return 1;
3636 }
3637
3638 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
3639 {
3640     X509_LOOKUP *lookup;
3641
3642     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
3643     if (lookup == NULL)
3644         return 0;
3645
3646     X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
3647
3648     /* Clear any errors if the default file does not exist */
3649     ERR_clear_error();
3650
3651     return 1;
3652 }
3653
3654 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3655                                   const char *CApath)
3656 {
3657     return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3658 }
3659
3660 void SSL_set_info_callback(SSL *ssl,
3661                            void (*cb) (const SSL *ssl, int type, int val))
3662 {
3663     ssl->info_callback = cb;
3664 }
3665
3666 /*
3667  * One compiler (Diab DCC) doesn't like argument names in returned function
3668  * pointer.
3669  */
3670 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3671                                                int /* type */ ,
3672                                                int /* val */ ) {
3673     return ssl->info_callback;
3674 }
3675
3676 void SSL_set_verify_result(SSL *ssl, long arg)
3677 {
3678     ssl->verify_result = arg;
3679 }
3680
3681 long SSL_get_verify_result(const SSL *ssl)
3682 {
3683     return (ssl->verify_result);
3684 }
3685
3686 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
3687 {
3688     if (outlen == 0)
3689         return sizeof(ssl->s3->client_random);
3690     if (outlen > sizeof(ssl->s3->client_random))
3691         outlen = sizeof(ssl->s3->client_random);
3692     memcpy(out, ssl->s3->client_random, outlen);
3693     return outlen;
3694 }
3695
3696 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
3697 {
3698     if (outlen == 0)
3699         return sizeof(ssl->s3->server_random);
3700     if (outlen > sizeof(ssl->s3->server_random))
3701         outlen = sizeof(ssl->s3->server_random);
3702     memcpy(out, ssl->s3->server_random, outlen);
3703     return outlen;
3704 }
3705
3706 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
3707                                   unsigned char *out, size_t outlen)
3708 {
3709     if (session->master_key_length < 0) {
3710         /* Should never happen */
3711         return 0;
3712     }
3713     if (outlen == 0)
3714         return session->master_key_length;
3715     if (outlen > (size_t)session->master_key_length)
3716         outlen = session->master_key_length;
3717     memcpy(out, session->master_key, outlen);
3718     return outlen;
3719 }
3720
3721 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3722 {
3723     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3724 }
3725
3726 void *SSL_get_ex_data(const SSL *s, int idx)
3727 {
3728     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3729 }
3730
3731 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3732 {
3733     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3734 }
3735
3736 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3737 {
3738     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3739 }
3740
3741 int ssl_ok(SSL *s)
3742 {
3743     return (1);
3744 }
3745
3746 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3747 {
3748     return (ctx->cert_store);
3749 }
3750
3751 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3752 {
3753     X509_STORE_free(ctx->cert_store);
3754     ctx->cert_store = store;
3755 }
3756
3757 int SSL_want(const SSL *s)
3758 {
3759     return (s->rwstate);
3760 }
3761
3762 /**
3763  * \brief Set the callback for generating temporary DH keys.
3764  * \param ctx the SSL context.
3765  * \param dh the callback
3766  */
3767
3768 #ifndef OPENSSL_NO_DH
3769 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3770                                  DH *(*dh) (SSL *ssl, int is_export,
3771                                             int keylength))
3772 {
3773     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3774 }
3775
3776 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3777                                                   int keylength))
3778 {
3779     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3780 }
3781 #endif
3782
3783 #ifndef OPENSSL_NO_PSK
3784 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3785 {
3786     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3787         SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3788         return 0;
3789     }
3790     OPENSSL_free(ctx->cert->psk_identity_hint);
3791     if (identity_hint != NULL) {
3792         ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3793         if (ctx->cert->psk_identity_hint == NULL)
3794             return 0;
3795     } else
3796         ctx->cert->psk_identity_hint = NULL;
3797     return 1;
3798 }
3799
3800 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3801 {
3802     if (s == NULL)
3803         return 0;
3804
3805     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3806         SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3807         return 0;
3808     }
3809     OPENSSL_free(s->cert->psk_identity_hint);
3810     if (identity_hint != NULL) {
3811         s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3812         if (s->cert->psk_identity_hint == NULL)
3813             return 0;
3814     } else
3815         s->cert->psk_identity_hint = NULL;
3816     return 1;
3817 }
3818
3819 const char *SSL_get_psk_identity_hint(const SSL *s)
3820 {
3821     if (s == NULL || s->session == NULL)
3822         return NULL;
3823     return (s->session->psk_identity_hint);
3824 }
3825
3826 const char *SSL_get_psk_identity(const SSL *s)
3827 {
3828     if (s == NULL || s->session == NULL)
3829         return NULL;
3830     return (s->session->psk_identity);
3831 }
3832
3833 void SSL_set_psk_client_callback(SSL *s,
3834                                  unsigned int (*cb) (SSL *ssl,
3835                                                      const char *hint,
3836                                                      char *identity,
3837                                                      unsigned int
3838                                                      max_identity_len,
3839                                                      unsigned char *psk,
3840                                                      unsigned int max_psk_len))
3841 {
3842     s->psk_client_callback = cb;
3843 }
3844
3845 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3846                                      unsigned int (*cb) (SSL *ssl,
3847                                                          const char *hint,
3848                                                          char *identity,
3849                                                          unsigned int
3850                                                          max_identity_len,
3851                                                          unsigned char *psk,
3852                                                          unsigned int
3853                                                          max_psk_len))
3854 {
3855     ctx->psk_client_callback = cb;
3856 }
3857
3858 void SSL_set_psk_server_callback(SSL *s,
3859                                  unsigned int (*cb) (SSL *ssl,
3860                                                      const char *identity,
3861                                                      unsigned char *psk,
3862                                                      unsigned int max_psk_len))
3863 {
3864     s->psk_server_callback = cb;
3865 }
3866
3867 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3868                                      unsigned int (*cb) (SSL *ssl,
3869                                                          const char *identity,
3870                                                          unsigned char *psk,
3871                                                          unsigned int
3872                                                          max_psk_len))
3873 {
3874     ctx->psk_server_callback = cb;
3875 }
3876 #endif
3877
3878 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
3879                               void (*cb) (int write_p, int version,
3880                                           int content_type, const void *buf,
3881                                           size_t len, SSL *ssl, void *arg))
3882 {
3883     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3884 }
3885
3886 void SSL_set_msg_callback(SSL *ssl,
3887                           void (*cb) (int write_p, int version,
3888                                       int content_type, const void *buf,
3889                                       size_t len, SSL *ssl, void *arg))
3890 {
3891     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3892 }
3893
3894 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
3895                                                 int (*cb) (SSL *ssl,
3896                                                            int
3897                                                            is_forward_secure))
3898 {
3899     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3900                           (void (*)(void))cb);
3901 }
3902
3903 void SSL_set_not_resumable_session_callback(SSL *ssl,
3904                                             int (*cb) (SSL *ssl,
3905                                                        int is_forward_secure))
3906 {
3907     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3908                       (void (*)(void))cb);
3909 }
3910
3911 /*
3912  * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3913  * variable, freeing EVP_MD_CTX previously stored in that variable, if any.
3914  * If EVP_MD pointer is passed, initializes ctx with this |md|.
3915  * Returns the newly allocated ctx;
3916  */
3917
3918 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3919 {
3920     ssl_clear_hash_ctx(hash);
3921     *hash = EVP_MD_CTX_new();
3922     if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
3923         EVP_MD_CTX_free(*hash);
3924         *hash = NULL;
3925         return NULL;
3926     }
3927     return *hash;
3928 }
3929
3930 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3931 {
3932
3933     if (*hash)
3934         EVP_MD_CTX_free(*hash);
3935     *hash = NULL;
3936 }
3937
3938 /* Retrieve handshake hashes */
3939 int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen)
3940 {
3941     EVP_MD_CTX *ctx = NULL;
3942     EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
3943     int ret = EVP_MD_CTX_size(hdgst);
3944     if (ret < 0 || ret > outlen) {
3945         ret = 0;
3946         goto err;
3947     }
3948     ctx = EVP_MD_CTX_new();
3949     if (ctx == NULL) {
3950         ret = 0;
3951         goto err;
3952     }
3953     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
3954         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
3955         ret = 0;
3956  err:
3957     EVP_MD_CTX_free(ctx);
3958     return ret;
3959 }
3960
3961 int SSL_session_reused(SSL *s)
3962 {
3963     return s->hit;
3964 }
3965
3966 int SSL_is_server(const SSL *s)
3967 {
3968     return s->server;
3969 }
3970
3971 #if OPENSSL_API_COMPAT < 0x10100000L
3972 void SSL_set_debug(SSL *s, int debug)
3973 {
3974     /* Old function was do-nothing anyway... */
3975     (void)s;
3976     (void)debug;
3977 }
3978 #endif
3979
3980 void SSL_set_security_level(SSL *s, int level)
3981 {
3982     s->cert->sec_level = level;
3983 }
3984
3985 int SSL_get_security_level(const SSL *s)
3986 {
3987     return s->cert->sec_level;
3988 }
3989
3990 void SSL_set_security_callback(SSL *s,
3991                                int (*cb) (const SSL *s, const SSL_CTX *ctx,
3992                                           int op, int bits, int nid,
3993                                           void *other, void *ex))
3994 {
3995     s->cert->sec_cb = cb;
3996 }
3997
3998 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
3999                                                 const SSL_CTX *ctx, int op,
4000                                                 int bits, int nid, void *other,
4001                                                 void *ex) {
4002     return s->cert->sec_cb;
4003 }
4004
4005 void SSL_set0_security_ex_data(SSL *s, void *ex)
4006 {
4007     s->cert->sec_ex = ex;
4008 }
4009
4010 void *SSL_get0_security_ex_data(const SSL *s)
4011 {
4012     return s->cert->sec_ex;
4013 }
4014
4015 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
4016 {
4017     ctx->cert->sec_level = level;
4018 }
4019
4020 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
4021 {
4022     return ctx->cert->sec_level;
4023 }
4024
4025 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
4026                                    int (*cb) (const SSL *s, const SSL_CTX *ctx,
4027                                               int op, int bits, int nid,
4028                                               void *other, void *ex))
4029 {
4030     ctx->cert->sec_cb = cb;
4031 }
4032
4033 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
4034                                                           const SSL_CTX *ctx,
4035                                                           int op, int bits,
4036                                                           int nid,
4037                                                           void *other,
4038                                                           void *ex) {
4039     return ctx->cert->sec_cb;
4040 }
4041
4042 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
4043 {
4044     ctx->cert->sec_ex = ex;
4045 }
4046
4047 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
4048 {
4049     return ctx->cert->sec_ex;
4050 }
4051
4052 /*
4053  * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
4054  * can return unsigned long, instead of the generic long return value from the
4055  * control interface.
4056  */
4057 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
4058 {
4059     return ctx->options;
4060 }
4061
4062 unsigned long SSL_get_options(const SSL *s)
4063 {
4064     return s->options;
4065 }
4066
4067 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
4068 {
4069     return ctx->options |= op;
4070 }
4071
4072 unsigned long SSL_set_options(SSL *s, unsigned long op)
4073 {
4074     return s->options |= op;
4075 }
4076
4077 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
4078 {
4079     return ctx->options &= ~op;
4080 }
4081
4082 unsigned long SSL_clear_options(SSL *s, unsigned long op)
4083 {
4084     return s->options &= ~op;
4085 }
4086
4087 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
4088 {
4089     return s->verified_chain;
4090 }
4091
4092 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
4093
4094 #ifndef OPENSSL_NO_CT
4095
4096 /*
4097  * Moves SCTs from the |src| stack to the |dst| stack.
4098  * The source of each SCT will be set to |origin|.
4099  * If |dst| points to a NULL pointer, a new stack will be created and owned by
4100  * the caller.
4101  * Returns the number of SCTs moved, or a negative integer if an error occurs.
4102  */
4103 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
4104                         sct_source_t origin)
4105 {
4106     int scts_moved = 0;
4107     SCT *sct = NULL;
4108
4109     if (*dst == NULL) {
4110         *dst = sk_SCT_new_null();
4111         if (*dst == NULL) {
4112             SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
4113             goto err;
4114         }
4115     }
4116
4117     while ((sct = sk_SCT_pop(src)) != NULL) {
4118         if (SCT_set_source(sct, origin) != 1)
4119             goto err;
4120
4121         if (sk_SCT_push(*dst, sct) <= 0)
4122             goto err;
4123         scts_moved += 1;
4124     }
4125
4126     return scts_moved;
4127  err:
4128     if (sct != NULL)
4129         sk_SCT_push(src, sct);  /* Put the SCT back */
4130     return -1;
4131 }
4132
4133 /*
4134  * Look for data collected during ServerHello and parse if found.
4135  * Returns the number of SCTs extracted.
4136  */
4137 static int ct_extract_tls_extension_scts(SSL *s)
4138 {
4139     int scts_extracted = 0;
4140
4141     if (s->tlsext_scts != NULL) {
4142         const unsigned char *p = s->tlsext_scts;
4143         STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->tlsext_scts_len);
4144
4145         scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
4146
4147         SCT_LIST_free(scts);
4148     }
4149
4150     return scts_extracted;
4151 }
4152
4153 /*
4154  * Checks for an OCSP response and then attempts to extract any SCTs found if it
4155  * contains an SCT X509 extension. They will be stored in |s->scts|.
4156  * Returns:
4157  * - The number of SCTs extracted, assuming an OCSP response exists.
4158  * - 0 if no OCSP response exists or it contains no SCTs.
4159  * - A negative integer if an error occurs.
4160  */
4161 static int ct_extract_ocsp_response_scts(SSL *s)
4162 {
4163 # ifndef OPENSSL_NO_OCSP
4164     int scts_extracted = 0;
4165     const unsigned char *p;
4166     OCSP_BASICRESP *br = NULL;
4167     OCSP_RESPONSE *rsp = NULL;
4168     STACK_OF(SCT) *scts = NULL;
4169     int i;
4170
4171     if (s->tlsext_ocsp_resp == NULL || s->tlsext_ocsp_resplen == 0)
4172         goto err;
4173
4174     p = s->tlsext_ocsp_resp;
4175     rsp = d2i_OCSP_RESPONSE(NULL, &p, s->tlsext_ocsp_resplen);
4176     if (rsp == NULL)
4177         goto err;
4178
4179     br = OCSP_response_get1_basic(rsp);
4180     if (br == NULL)
4181         goto err;
4182
4183     for (i = 0; i < OCSP_resp_count(br); ++i) {
4184         OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
4185
4186         if (single == NULL)
4187             continue;
4188
4189         scts =
4190             OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
4191         scts_extracted =
4192             ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
4193         if (scts_extracted < 0)
4194             goto err;
4195     }
4196  err:
4197     SCT_LIST_free(scts);
4198     OCSP_BASICRESP_free(br);
4199     OCSP_RESPONSE_free(rsp);
4200     return scts_extracted;
4201 # else
4202     /* Behave as if no OCSP response exists */
4203     return 0;
4204 # endif
4205 }
4206
4207 /*
4208  * Attempts to extract SCTs from the peer certificate.
4209  * Return the number of SCTs extracted, or a negative integer if an error
4210  * occurs.
4211  */
4212 static int ct_extract_x509v3_extension_scts(SSL *s)
4213 {
4214     int scts_extracted = 0;
4215     X509 *cert = s->session != NULL ? s->session->peer : NULL;
4216
4217     if (cert != NULL) {
4218         STACK_OF(SCT) *scts =
4219             X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
4220
4221         scts_extracted =
4222             ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
4223
4224         SCT_LIST_free(scts);
4225     }
4226
4227     return scts_extracted;
4228 }
4229
4230 /*
4231  * Attempts to find all received SCTs by checking TLS extensions, the OCSP
4232  * response (if it exists) and X509v3 extensions in the certificate.
4233  * Returns NULL if an error occurs.
4234  */
4235 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
4236 {
4237     if (!s->scts_parsed) {
4238         if (ct_extract_tls_extension_scts(s) < 0 ||
4239             ct_extract_ocsp_response_scts(s) < 0 ||
4240             ct_extract_x509v3_extension_scts(s) < 0)
4241             goto err;
4242
4243         s->scts_parsed = 1;
4244     }
4245     return s->scts;
4246  err:
4247     return NULL;
4248 }
4249
4250 static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
4251                          const STACK_OF(SCT) *scts, void *unused_arg)
4252 {
4253     return 1;
4254 }
4255
4256 static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
4257                      const STACK_OF(SCT) *scts, void *unused_arg)
4258 {
4259     int count = scts != NULL ? sk_SCT_num(scts) : 0;
4260     int i;
4261
4262     for (i = 0; i < count; ++i) {
4263         SCT *sct = sk_SCT_value(scts, i);
4264         int status = SCT_get_validation_status(sct);
4265
4266         if (status == SCT_VALIDATION_STATUS_VALID)
4267             return 1;
4268     }
4269     SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
4270     return 0;
4271 }
4272
4273 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
4274                                    void *arg)
4275 {
4276     /*
4277      * Since code exists that uses the custom extension handler for CT, look
4278      * for this and throw an error if they have already registered to use CT.
4279      */
4280     if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
4281                                                           TLSEXT_TYPE_signed_certificate_timestamp))
4282     {
4283         SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
4284                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4285         return 0;
4286     }
4287
4288     if (callback != NULL) {
4289         /*
4290          * If we are validating CT, then we MUST accept SCTs served via OCSP
4291          */
4292         if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
4293             return 0;
4294     }
4295
4296     s->ct_validation_callback = callback;
4297     s->ct_validation_callback_arg = arg;
4298
4299     return 1;
4300 }
4301
4302 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
4303                                        ssl_ct_validation_cb callback, void *arg)
4304 {
4305     /*
4306      * Since code exists that uses the custom extension handler for CT, look for
4307      * this and throw an error if they have already registered to use CT.
4308      */
4309     if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
4310                                                           TLSEXT_TYPE_signed_certificate_timestamp))
4311     {
4312         SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
4313                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4314         return 0;
4315     }
4316
4317     ctx->ct_validation_callback = callback;
4318     ctx->ct_validation_callback_arg = arg;
4319     return 1;
4320 }
4321
4322 int SSL_ct_is_enabled(const SSL *s)
4323 {
4324     return s->ct_validation_callback != NULL;
4325 }
4326
4327 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
4328 {
4329     return ctx->ct_validation_callback != NULL;
4330 }
4331
4332 int ssl_validate_ct(SSL *s)
4333 {
4334     int ret = 0;
4335     X509 *cert = s->session != NULL ? s->session->peer : NULL;
4336     X509 *issuer;
4337     SSL_DANE *dane = &s->dane;
4338     CT_POLICY_EVAL_CTX *ctx = NULL;
4339     const STACK_OF(SCT) *scts;
4340
4341     /*
4342      * If no callback is set, the peer is anonymous, or its chain is invalid,
4343      * skip SCT validation - just return success.  Applications that continue
4344      * handshakes without certificates, with unverified chains, or pinned leaf
4345      * certificates are outside the scope of the WebPKI and CT.
4346      *
4347      * The above exclusions notwithstanding the vast majority of peers will
4348      * have rather ordinary certificate chains validated by typical
4349      * applications that perform certificate verification and therefore will
4350      * process SCTs when enabled.
4351      */
4352     if (s->ct_validation_callback == NULL || cert == NULL ||
4353         s->verify_result != X509_V_OK ||
4354         s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
4355         return 1;
4356
4357     /*
4358      * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
4359      * trust-anchors.  See https://tools.ietf.org/html/rfc7671#section-4.2
4360      */
4361     if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
4362         switch (dane->mtlsa->usage) {
4363         case DANETLS_USAGE_DANE_TA:
4364         case DANETLS_USAGE_DANE_EE:
4365             return 1;
4366         }
4367     }
4368
4369     ctx = CT_POLICY_EVAL_CTX_new();
4370     if (ctx == NULL) {
4371         SSLerr(SSL_F_SSL_VALIDATE_CT, ERR_R_MALLOC_FAILURE);
4372         goto end;
4373     }
4374
4375     issuer = sk_X509_value(s->verified_chain, 1);
4376     CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
4377     CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
4378     CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx, s->ctx->ctlog_store);
4379     CT_POLICY_EVAL_CTX_set_time(
4380             ctx, (uint64_t)SSL_SESSION_get_time(SSL_get0_session(s)) * 1000);
4381
4382     scts = SSL_get0_peer_scts(s);
4383
4384     /*
4385      * This function returns success (> 0) only when all the SCTs are valid, 0
4386      * when some are invalid, and < 0 on various internal errors (out of
4387      * memory, etc.).  Having some, or even all, invalid SCTs is not sufficient
4388      * reason to abort the handshake, that decision is up to the callback.
4389      * Therefore, we error out only in the unexpected case that the return
4390      * value is negative.
4391      *
4392      * XXX: One might well argue that the return value of this function is an
4393      * unfortunate design choice.  Its job is only to determine the validation
4394      * status of each of the provided SCTs.  So long as it correctly separates
4395      * the wheat from the chaff it should return success.  Failure in this case
4396      * ought to correspond to an inability to carry out its duties.
4397      */
4398     if (SCT_LIST_validate(scts, ctx) < 0) {
4399         SSLerr(SSL_F_SSL_VALIDATE_CT, SSL_R_SCT_VERIFICATION_FAILED);
4400         goto end;
4401     }
4402
4403     ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
4404     if (ret < 0)
4405         ret = 0;                /* This function returns 0 on failure */
4406
4407  end:
4408     CT_POLICY_EVAL_CTX_free(ctx);
4409     /*
4410      * With SSL_VERIFY_NONE the session may be cached and re-used despite a
4411      * failure return code here.  Also the application may wish the complete
4412      * the handshake, and then disconnect cleanly at a higher layer, after
4413      * checking the verification status of the completed connection.
4414      *
4415      * We therefore force a certificate verification failure which will be
4416      * visible via SSL_get_verify_result() and cached as part of any resumed
4417      * session.
4418      *
4419      * Note: the permissive callback is for information gathering only, always
4420      * returns success, and does not affect verification status.  Only the
4421      * strict callback or a custom application-specified callback can trigger
4422      * connection failure or record a verification error.
4423      */
4424     if (ret <= 0)
4425         s->verify_result = X509_V_ERR_NO_VALID_SCTS;
4426     return ret;
4427 }
4428
4429 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
4430 {
4431     switch (validation_mode) {
4432     default:
4433         SSLerr(SSL_F_SSL_CTX_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4434         return 0;
4435     case SSL_CT_VALIDATION_PERMISSIVE:
4436         return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
4437     case SSL_CT_VALIDATION_STRICT:
4438         return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
4439     }
4440 }
4441
4442 int SSL_enable_ct(SSL *s, int validation_mode)
4443 {
4444     switch (validation_mode) {
4445     default:
4446         SSLerr(SSL_F_SSL_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4447         return 0;
4448     case SSL_CT_VALIDATION_PERMISSIVE:
4449         return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
4450     case SSL_CT_VALIDATION_STRICT:
4451         return SSL_set_ct_validation_callback(s, ct_strict, NULL);
4452     }
4453 }
4454
4455 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
4456 {
4457     return CTLOG_STORE_load_default_file(ctx->ctlog_store);
4458 }
4459
4460 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
4461 {
4462     return CTLOG_STORE_load_file(ctx->ctlog_store, path);
4463 }
4464
4465 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE * logs)
4466 {
4467     CTLOG_STORE_free(ctx->ctlog_store);
4468     ctx->ctlog_store = logs;
4469 }
4470
4471 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
4472 {
4473     return ctx->ctlog_store;
4474 }
4475
4476 #endif