c3174a7c91683f14c568b06d6b3d111e0a2c75eb
[openssl.git] / ssl / ssl_lib.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include <stdio.h>
13 #include "ssl_local.h"
14 #include "e_os.h"
15 #include <openssl/objects.h>
16 #include <openssl/x509v3.h>
17 #include <openssl/rand.h>
18 #include <openssl/rand_drbg.h>
19 #include <openssl/ocsp.h>
20 #include <openssl/dh.h>
21 #include <openssl/engine.h>
22 #include <openssl/async.h>
23 #include <openssl/ct.h>
24 #include <openssl/trace.h>
25 #include "internal/cryptlib.h"
26 #include "internal/refcount.h"
27 #include "internal/ktls.h"
28
29 DEFINE_STACK_OF(X509)
30 DEFINE_STACK_OF(X509_NAME)
31 DEFINE_STACK_OF_CONST(SSL_CIPHER)
32 DEFINE_STACK_OF(X509_EXTENSION)
33 DEFINE_STACK_OF(OCSP_RESPID)
34 DEFINE_STACK_OF(SRTP_PROTECTION_PROFILE)
35 DEFINE_STACK_OF(SCT)
36
37 static int ssl_undefined_function_1(SSL *ssl, SSL3_RECORD *r, size_t s, int t,
38                                     SSL_MAC_BUF *mac, size_t macsize)
39 {
40     return ssl_undefined_function(ssl);
41 }
42
43 static int ssl_undefined_function_2(SSL *ssl, SSL3_RECORD *r, unsigned char *s,
44                                     int t)
45 {
46     return ssl_undefined_function(ssl);
47 }
48
49 static int ssl_undefined_function_3(SSL *ssl, unsigned char *r,
50                                     unsigned char *s, size_t t, size_t *u)
51 {
52     return ssl_undefined_function(ssl);
53 }
54
55 static int ssl_undefined_function_4(SSL *ssl, int r)
56 {
57     return ssl_undefined_function(ssl);
58 }
59
60 static size_t ssl_undefined_function_5(SSL *ssl, const char *r, size_t s,
61                                        unsigned char *t)
62 {
63     return ssl_undefined_function(ssl);
64 }
65
66 static int ssl_undefined_function_6(int r)
67 {
68     return ssl_undefined_function(NULL);
69 }
70
71 static int ssl_undefined_function_7(SSL *ssl, unsigned char *r, size_t s,
72                                     const char *t, size_t u,
73                                     const unsigned char *v, size_t w, int x)
74 {
75     return ssl_undefined_function(ssl);
76 }
77
78 SSL3_ENC_METHOD ssl3_undef_enc_method = {
79     ssl_undefined_function_1,
80     ssl_undefined_function_2,
81     ssl_undefined_function,
82     ssl_undefined_function_3,
83     ssl_undefined_function_4,
84     ssl_undefined_function_5,
85     NULL,                       /* client_finished_label */
86     0,                          /* client_finished_label_len */
87     NULL,                       /* server_finished_label */
88     0,                          /* server_finished_label_len */
89     ssl_undefined_function_6,
90     ssl_undefined_function_7,
91 };
92
93 struct ssl_async_args {
94     SSL *s;
95     void *buf;
96     size_t num;
97     enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
98     union {
99         int (*func_read) (SSL *, void *, size_t, size_t *);
100         int (*func_write) (SSL *, const void *, size_t, size_t *);
101         int (*func_other) (SSL *);
102     } f;
103 };
104
105 static const struct {
106     uint8_t mtype;
107     uint8_t ord;
108     int nid;
109 } dane_mds[] = {
110     {
111         DANETLS_MATCHING_FULL, 0, NID_undef
112     },
113     {
114         DANETLS_MATCHING_2256, 1, NID_sha256
115     },
116     {
117         DANETLS_MATCHING_2512, 2, NID_sha512
118     },
119 };
120
121 static int dane_ctx_enable(struct dane_ctx_st *dctx)
122 {
123     const EVP_MD **mdevp;
124     uint8_t *mdord;
125     uint8_t mdmax = DANETLS_MATCHING_LAST;
126     int n = ((int)mdmax) + 1;   /* int to handle PrivMatch(255) */
127     size_t i;
128
129     if (dctx->mdevp != NULL)
130         return 1;
131
132     mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
133     mdord = OPENSSL_zalloc(n * sizeof(*mdord));
134
135     if (mdord == NULL || mdevp == NULL) {
136         OPENSSL_free(mdord);
137         OPENSSL_free(mdevp);
138         SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
139         return 0;
140     }
141
142     /* Install default entries */
143     for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
144         const EVP_MD *md;
145
146         if (dane_mds[i].nid == NID_undef ||
147             (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
148             continue;
149         mdevp[dane_mds[i].mtype] = md;
150         mdord[dane_mds[i].mtype] = dane_mds[i].ord;
151     }
152
153     dctx->mdevp = mdevp;
154     dctx->mdord = mdord;
155     dctx->mdmax = mdmax;
156
157     return 1;
158 }
159
160 static void dane_ctx_final(struct dane_ctx_st *dctx)
161 {
162     OPENSSL_free(dctx->mdevp);
163     dctx->mdevp = NULL;
164
165     OPENSSL_free(dctx->mdord);
166     dctx->mdord = NULL;
167     dctx->mdmax = 0;
168 }
169
170 static void tlsa_free(danetls_record *t)
171 {
172     if (t == NULL)
173         return;
174     OPENSSL_free(t->data);
175     EVP_PKEY_free(t->spki);
176     OPENSSL_free(t);
177 }
178
179 static void dane_final(SSL_DANE *dane)
180 {
181     sk_danetls_record_pop_free(dane->trecs, tlsa_free);
182     dane->trecs = NULL;
183
184     sk_X509_pop_free(dane->certs, X509_free);
185     dane->certs = NULL;
186
187     X509_free(dane->mcert);
188     dane->mcert = NULL;
189     dane->mtlsa = NULL;
190     dane->mdpth = -1;
191     dane->pdpth = -1;
192 }
193
194 /*
195  * dane_copy - Copy dane configuration, sans verification state.
196  */
197 static int ssl_dane_dup(SSL *to, SSL *from)
198 {
199     int num;
200     int i;
201
202     if (!DANETLS_ENABLED(&from->dane))
203         return 1;
204
205     num = sk_danetls_record_num(from->dane.trecs);
206     dane_final(&to->dane);
207     to->dane.flags = from->dane.flags;
208     to->dane.dctx = &to->ctx->dane;
209     to->dane.trecs = sk_danetls_record_new_reserve(NULL, num);
210
211     if (to->dane.trecs == NULL) {
212         SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
213         return 0;
214     }
215
216     for (i = 0; i < num; ++i) {
217         danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
218
219         if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
220                               t->data, t->dlen) <= 0)
221             return 0;
222     }
223     return 1;
224 }
225
226 static int dane_mtype_set(struct dane_ctx_st *dctx,
227                           const EVP_MD *md, uint8_t mtype, uint8_t ord)
228 {
229     int i;
230
231     if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
232         SSLerr(SSL_F_DANE_MTYPE_SET, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
233         return 0;
234     }
235
236     if (mtype > dctx->mdmax) {
237         const EVP_MD **mdevp;
238         uint8_t *mdord;
239         int n = ((int)mtype) + 1;
240
241         mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
242         if (mdevp == NULL) {
243             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
244             return -1;
245         }
246         dctx->mdevp = mdevp;
247
248         mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
249         if (mdord == NULL) {
250             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
251             return -1;
252         }
253         dctx->mdord = mdord;
254
255         /* Zero-fill any gaps */
256         for (i = dctx->mdmax + 1; i < mtype; ++i) {
257             mdevp[i] = NULL;
258             mdord[i] = 0;
259         }
260
261         dctx->mdmax = mtype;
262     }
263
264     dctx->mdevp[mtype] = md;
265     /* Coerce ordinal of disabled matching types to 0 */
266     dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
267
268     return 1;
269 }
270
271 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
272 {
273     if (mtype > dane->dctx->mdmax)
274         return NULL;
275     return dane->dctx->mdevp[mtype];
276 }
277
278 static int dane_tlsa_add(SSL_DANE *dane,
279                          uint8_t usage,
280                          uint8_t selector,
281                          uint8_t mtype, unsigned const char *data, size_t dlen)
282 {
283     danetls_record *t;
284     const EVP_MD *md = NULL;
285     int ilen = (int)dlen;
286     int i;
287     int num;
288
289     if (dane->trecs == NULL) {
290         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
291         return -1;
292     }
293
294     if (ilen < 0 || dlen != (size_t)ilen) {
295         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
296         return 0;
297     }
298
299     if (usage > DANETLS_USAGE_LAST) {
300         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
301         return 0;
302     }
303
304     if (selector > DANETLS_SELECTOR_LAST) {
305         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
306         return 0;
307     }
308
309     if (mtype != DANETLS_MATCHING_FULL) {
310         md = tlsa_md_get(dane, mtype);
311         if (md == NULL) {
312             SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
313             return 0;
314         }
315     }
316
317     if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
318         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
319         return 0;
320     }
321     if (!data) {
322         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
323         return 0;
324     }
325
326     if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
327         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
328         return -1;
329     }
330
331     t->usage = usage;
332     t->selector = selector;
333     t->mtype = mtype;
334     t->data = OPENSSL_malloc(dlen);
335     if (t->data == NULL) {
336         tlsa_free(t);
337         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
338         return -1;
339     }
340     memcpy(t->data, data, dlen);
341     t->dlen = dlen;
342
343     /* Validate and cache full certificate or public key */
344     if (mtype == DANETLS_MATCHING_FULL) {
345         const unsigned char *p = data;
346         X509 *cert = NULL;
347         EVP_PKEY *pkey = NULL;
348
349         switch (selector) {
350         case DANETLS_SELECTOR_CERT:
351             if (!d2i_X509(&cert, &p, ilen) || p < data ||
352                 dlen != (size_t)(p - data)) {
353                 tlsa_free(t);
354                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
355                 return 0;
356             }
357             if (X509_get0_pubkey(cert) == NULL) {
358                 tlsa_free(t);
359                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
360                 return 0;
361             }
362
363             if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
364                 X509_free(cert);
365                 break;
366             }
367
368             /*
369              * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
370              * records that contain full certificates of trust-anchors that are
371              * not present in the wire chain.  For usage PKIX-TA(0), we augment
372              * the chain with untrusted Full(0) certificates from DNS, in case
373              * they are missing from the chain.
374              */
375             if ((dane->certs == NULL &&
376                  (dane->certs = sk_X509_new_null()) == NULL) ||
377                 !sk_X509_push(dane->certs, cert)) {
378                 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
379                 X509_free(cert);
380                 tlsa_free(t);
381                 return -1;
382             }
383             break;
384
385         case DANETLS_SELECTOR_SPKI:
386             if (!d2i_PUBKEY(&pkey, &p, ilen) || p < data ||
387                 dlen != (size_t)(p - data)) {
388                 tlsa_free(t);
389                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
390                 return 0;
391             }
392
393             /*
394              * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
395              * records that contain full bare keys of trust-anchors that are
396              * not present in the wire chain.
397              */
398             if (usage == DANETLS_USAGE_DANE_TA)
399                 t->spki = pkey;
400             else
401                 EVP_PKEY_free(pkey);
402             break;
403         }
404     }
405
406     /*-
407      * Find the right insertion point for the new record.
408      *
409      * See crypto/x509/x509_vfy.c.  We sort DANE-EE(3) records first, so that
410      * they can be processed first, as they require no chain building, and no
411      * expiration or hostname checks.  Because DANE-EE(3) is numerically
412      * largest, this is accomplished via descending sort by "usage".
413      *
414      * We also sort in descending order by matching ordinal to simplify
415      * the implementation of digest agility in the verification code.
416      *
417      * The choice of order for the selector is not significant, so we
418      * use the same descending order for consistency.
419      */
420     num = sk_danetls_record_num(dane->trecs);
421     for (i = 0; i < num; ++i) {
422         danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
423
424         if (rec->usage > usage)
425             continue;
426         if (rec->usage < usage)
427             break;
428         if (rec->selector > selector)
429             continue;
430         if (rec->selector < selector)
431             break;
432         if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
433             continue;
434         break;
435     }
436
437     if (!sk_danetls_record_insert(dane->trecs, t, i)) {
438         tlsa_free(t);
439         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
440         return -1;
441     }
442     dane->umask |= DANETLS_USAGE_BIT(usage);
443
444     return 1;
445 }
446
447 /*
448  * Return 0 if there is only one version configured and it was disabled
449  * at configure time.  Return 1 otherwise.
450  */
451 static int ssl_check_allowed_versions(int min_version, int max_version)
452 {
453     int minisdtls = 0, maxisdtls = 0;
454
455     /* Figure out if we're doing DTLS versions or TLS versions */
456     if (min_version == DTLS1_BAD_VER
457         || min_version >> 8 == DTLS1_VERSION_MAJOR)
458         minisdtls = 1;
459     if (max_version == DTLS1_BAD_VER
460         || max_version >> 8 == DTLS1_VERSION_MAJOR)
461         maxisdtls = 1;
462     /* A wildcard version of 0 could be DTLS or TLS. */
463     if ((minisdtls && !maxisdtls && max_version != 0)
464         || (maxisdtls && !minisdtls && min_version != 0)) {
465         /* Mixing DTLS and TLS versions will lead to sadness; deny it. */
466         return 0;
467     }
468
469     if (minisdtls || maxisdtls) {
470         /* Do DTLS version checks. */
471         if (min_version == 0)
472             /* Ignore DTLS1_BAD_VER */
473             min_version = DTLS1_VERSION;
474         if (max_version == 0)
475             max_version = DTLS1_2_VERSION;
476 #ifdef OPENSSL_NO_DTLS1_2
477         if (max_version == DTLS1_2_VERSION)
478             max_version = DTLS1_VERSION;
479 #endif
480 #ifdef OPENSSL_NO_DTLS1
481         if (min_version == DTLS1_VERSION)
482             min_version = DTLS1_2_VERSION;
483 #endif
484         /* Done massaging versions; do the check. */
485         if (0
486 #ifdef OPENSSL_NO_DTLS1
487             || (DTLS_VERSION_GE(min_version, DTLS1_VERSION)
488                 && DTLS_VERSION_GE(DTLS1_VERSION, max_version))
489 #endif
490 #ifdef OPENSSL_NO_DTLS1_2
491             || (DTLS_VERSION_GE(min_version, DTLS1_2_VERSION)
492                 && DTLS_VERSION_GE(DTLS1_2_VERSION, max_version))
493 #endif
494             )
495             return 0;
496     } else {
497         /* Regular TLS version checks. */
498         if (min_version == 0)
499             min_version = SSL3_VERSION;
500         if (max_version == 0)
501             max_version = TLS1_3_VERSION;
502 #ifdef OPENSSL_NO_TLS1_3
503         if (max_version == TLS1_3_VERSION)
504             max_version = TLS1_2_VERSION;
505 #endif
506 #ifdef OPENSSL_NO_TLS1_2
507         if (max_version == TLS1_2_VERSION)
508             max_version = TLS1_1_VERSION;
509 #endif
510 #ifdef OPENSSL_NO_TLS1_1
511         if (max_version == TLS1_1_VERSION)
512             max_version = TLS1_VERSION;
513 #endif
514 #ifdef OPENSSL_NO_TLS1
515         if (max_version == TLS1_VERSION)
516             max_version = SSL3_VERSION;
517 #endif
518 #ifdef OPENSSL_NO_SSL3
519         if (min_version == SSL3_VERSION)
520             min_version = TLS1_VERSION;
521 #endif
522 #ifdef OPENSSL_NO_TLS1
523         if (min_version == TLS1_VERSION)
524             min_version = TLS1_1_VERSION;
525 #endif
526 #ifdef OPENSSL_NO_TLS1_1
527         if (min_version == TLS1_1_VERSION)
528             min_version = TLS1_2_VERSION;
529 #endif
530 #ifdef OPENSSL_NO_TLS1_2
531         if (min_version == TLS1_2_VERSION)
532             min_version = TLS1_3_VERSION;
533 #endif
534         /* Done massaging versions; do the check. */
535         if (0
536 #ifdef OPENSSL_NO_SSL3
537             || (min_version <= SSL3_VERSION && SSL3_VERSION <= max_version)
538 #endif
539 #ifdef OPENSSL_NO_TLS1
540             || (min_version <= TLS1_VERSION && TLS1_VERSION <= max_version)
541 #endif
542 #ifdef OPENSSL_NO_TLS1_1
543             || (min_version <= TLS1_1_VERSION && TLS1_1_VERSION <= max_version)
544 #endif
545 #ifdef OPENSSL_NO_TLS1_2
546             || (min_version <= TLS1_2_VERSION && TLS1_2_VERSION <= max_version)
547 #endif
548 #ifdef OPENSSL_NO_TLS1_3
549             || (min_version <= TLS1_3_VERSION && TLS1_3_VERSION <= max_version)
550 #endif
551             )
552             return 0;
553     }
554     return 1;
555 }
556
557 static void clear_ciphers(SSL *s)
558 {
559     /* clear the current cipher */
560     ssl_clear_cipher_ctx(s);
561     ssl_clear_hash_ctx(&s->read_hash);
562     ssl_clear_hash_ctx(&s->write_hash);
563 }
564
565 int SSL_clear(SSL *s)
566 {
567     if (s->method == NULL) {
568         SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
569         return 0;
570     }
571
572     if (ssl_clear_bad_session(s)) {
573         SSL_SESSION_free(s->session);
574         s->session = NULL;
575     }
576     SSL_SESSION_free(s->psksession);
577     s->psksession = NULL;
578     OPENSSL_free(s->psksession_id);
579     s->psksession_id = NULL;
580     s->psksession_id_len = 0;
581     s->hello_retry_request = 0;
582     s->sent_tickets = 0;
583
584     s->error = 0;
585     s->hit = 0;
586     s->shutdown = 0;
587
588     if (s->renegotiate) {
589         SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
590         return 0;
591     }
592
593     ossl_statem_clear(s);
594
595     s->version = s->method->version;
596     s->client_version = s->version;
597     s->rwstate = SSL_NOTHING;
598
599     BUF_MEM_free(s->init_buf);
600     s->init_buf = NULL;
601     clear_ciphers(s);
602     s->first_packet = 0;
603
604     s->key_update = SSL_KEY_UPDATE_NONE;
605
606     EVP_MD_CTX_free(s->pha_dgst);
607     s->pha_dgst = NULL;
608
609     /* Reset DANE verification result state */
610     s->dane.mdpth = -1;
611     s->dane.pdpth = -1;
612     X509_free(s->dane.mcert);
613     s->dane.mcert = NULL;
614     s->dane.mtlsa = NULL;
615
616     /* Clear the verification result peername */
617     X509_VERIFY_PARAM_move_peername(s->param, NULL);
618
619     /* Clear any shared connection state */
620     OPENSSL_free(s->shared_sigalgs);
621     s->shared_sigalgs = NULL;
622     s->shared_sigalgslen = 0;
623
624     /*
625      * Check to see if we were changed into a different method, if so, revert
626      * back.
627      */
628     if (s->method != s->ctx->method) {
629         s->method->ssl_free(s);
630         s->method = s->ctx->method;
631         if (!s->method->ssl_new(s))
632             return 0;
633     } else {
634         if (!s->method->ssl_clear(s))
635             return 0;
636     }
637
638     RECORD_LAYER_clear(&s->rlayer);
639
640     return 1;
641 }
642
643 /** Used to change an SSL_CTXs default SSL method type */
644 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
645 {
646     STACK_OF(SSL_CIPHER) *sk;
647
648     ctx->method = meth;
649
650     if (!SSL_CTX_set_ciphersuites(ctx, OSSL_default_ciphersuites())) {
651         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
652         return 0;
653     }
654     sk = ssl_create_cipher_list(ctx->method,
655                                 ctx->tls13_ciphersuites,
656                                 &(ctx->cipher_list),
657                                 &(ctx->cipher_list_by_id),
658                                 OSSL_default_cipher_list(), ctx->cert);
659     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
660         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
661         return 0;
662     }
663     return 1;
664 }
665
666 SSL *SSL_new(SSL_CTX *ctx)
667 {
668     SSL *s;
669
670     if (ctx == NULL) {
671         SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
672         return NULL;
673     }
674     if (ctx->method == NULL) {
675         SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
676         return NULL;
677     }
678
679     s = OPENSSL_zalloc(sizeof(*s));
680     if (s == NULL)
681         goto err;
682
683     s->references = 1;
684     s->lock = CRYPTO_THREAD_lock_new();
685     if (s->lock == NULL) {
686         OPENSSL_free(s);
687         s = NULL;
688         goto err;
689     }
690
691     RECORD_LAYER_init(&s->rlayer, s);
692
693     s->options = ctx->options;
694     s->dane.flags = ctx->dane.flags;
695     s->min_proto_version = ctx->min_proto_version;
696     s->max_proto_version = ctx->max_proto_version;
697     s->mode = ctx->mode;
698     s->max_cert_list = ctx->max_cert_list;
699     s->max_early_data = ctx->max_early_data;
700     s->recv_max_early_data = ctx->recv_max_early_data;
701     s->num_tickets = ctx->num_tickets;
702     s->pha_enabled = ctx->pha_enabled;
703
704     /* Shallow copy of the ciphersuites stack */
705     s->tls13_ciphersuites = sk_SSL_CIPHER_dup(ctx->tls13_ciphersuites);
706     if (s->tls13_ciphersuites == NULL)
707         goto err;
708
709     /*
710      * Earlier library versions used to copy the pointer to the CERT, not
711      * its contents; only when setting new parameters for the per-SSL
712      * copy, ssl_cert_new would be called (and the direct reference to
713      * the per-SSL_CTX settings would be lost, but those still were
714      * indirectly accessed for various purposes, and for that reason they
715      * used to be known as s->ctx->default_cert). Now we don't look at the
716      * SSL_CTX's CERT after having duplicated it once.
717      */
718     s->cert = ssl_cert_dup(ctx->cert);
719     if (s->cert == NULL)
720         goto err;
721
722     RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
723     s->msg_callback = ctx->msg_callback;
724     s->msg_callback_arg = ctx->msg_callback_arg;
725     s->verify_mode = ctx->verify_mode;
726     s->not_resumable_session_cb = ctx->not_resumable_session_cb;
727     s->record_padding_cb = ctx->record_padding_cb;
728     s->record_padding_arg = ctx->record_padding_arg;
729     s->block_padding = ctx->block_padding;
730     s->sid_ctx_length = ctx->sid_ctx_length;
731     if (!ossl_assert(s->sid_ctx_length <= sizeof(s->sid_ctx)))
732         goto err;
733     memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
734     s->verify_callback = ctx->default_verify_callback;
735     s->generate_session_id = ctx->generate_session_id;
736
737     s->param = X509_VERIFY_PARAM_new();
738     if (s->param == NULL)
739         goto err;
740     X509_VERIFY_PARAM_inherit(s->param, ctx->param);
741     s->quiet_shutdown = ctx->quiet_shutdown;
742
743     s->ext.max_fragment_len_mode = ctx->ext.max_fragment_len_mode;
744     s->max_send_fragment = ctx->max_send_fragment;
745     s->split_send_fragment = ctx->split_send_fragment;
746     s->max_pipelines = ctx->max_pipelines;
747     if (s->max_pipelines > 1)
748         RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
749     if (ctx->default_read_buf_len > 0)
750         SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
751
752     SSL_CTX_up_ref(ctx);
753     s->ctx = ctx;
754     s->ext.debug_cb = 0;
755     s->ext.debug_arg = NULL;
756     s->ext.ticket_expected = 0;
757     s->ext.status_type = ctx->ext.status_type;
758     s->ext.status_expected = 0;
759     s->ext.ocsp.ids = NULL;
760     s->ext.ocsp.exts = NULL;
761     s->ext.ocsp.resp = NULL;
762     s->ext.ocsp.resp_len = 0;
763     SSL_CTX_up_ref(ctx);
764     s->session_ctx = ctx;
765 #ifndef OPENSSL_NO_EC
766     if (ctx->ext.ecpointformats) {
767         s->ext.ecpointformats =
768             OPENSSL_memdup(ctx->ext.ecpointformats,
769                            ctx->ext.ecpointformats_len);
770         if (!s->ext.ecpointformats)
771             goto err;
772         s->ext.ecpointformats_len =
773             ctx->ext.ecpointformats_len;
774     }
775 #endif
776     if (ctx->ext.supportedgroups) {
777         s->ext.supportedgroups =
778             OPENSSL_memdup(ctx->ext.supportedgroups,
779                            ctx->ext.supportedgroups_len
780                                 * sizeof(*ctx->ext.supportedgroups));
781         if (!s->ext.supportedgroups)
782             goto err;
783         s->ext.supportedgroups_len = ctx->ext.supportedgroups_len;
784     }
785
786 #ifndef OPENSSL_NO_NEXTPROTONEG
787     s->ext.npn = NULL;
788 #endif
789
790     if (s->ctx->ext.alpn) {
791         s->ext.alpn = OPENSSL_malloc(s->ctx->ext.alpn_len);
792         if (s->ext.alpn == NULL)
793             goto err;
794         memcpy(s->ext.alpn, s->ctx->ext.alpn, s->ctx->ext.alpn_len);
795         s->ext.alpn_len = s->ctx->ext.alpn_len;
796     }
797
798     s->verified_chain = NULL;
799     s->verify_result = X509_V_OK;
800
801     s->default_passwd_callback = ctx->default_passwd_callback;
802     s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
803
804     s->method = ctx->method;
805
806     s->key_update = SSL_KEY_UPDATE_NONE;
807
808     s->allow_early_data_cb = ctx->allow_early_data_cb;
809     s->allow_early_data_cb_data = ctx->allow_early_data_cb_data;
810
811     if (!s->method->ssl_new(s))
812         goto err;
813
814     s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
815
816     if (!SSL_clear(s))
817         goto err;
818
819     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data))
820         goto err;
821
822 #ifndef OPENSSL_NO_PSK
823     s->psk_client_callback = ctx->psk_client_callback;
824     s->psk_server_callback = ctx->psk_server_callback;
825 #endif
826     s->psk_find_session_cb = ctx->psk_find_session_cb;
827     s->psk_use_session_cb = ctx->psk_use_session_cb;
828
829     s->async_cb = ctx->async_cb;
830     s->async_cb_arg = ctx->async_cb_arg;
831
832     s->job = NULL;
833
834 #ifndef OPENSSL_NO_CT
835     if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
836                                         ctx->ct_validation_callback_arg))
837         goto err;
838 #endif
839
840     return s;
841  err:
842     SSL_free(s);
843     SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
844     return NULL;
845 }
846
847 int SSL_is_dtls(const SSL *s)
848 {
849     return SSL_IS_DTLS(s) ? 1 : 0;
850 }
851
852 int SSL_up_ref(SSL *s)
853 {
854     int i;
855
856     if (CRYPTO_UP_REF(&s->references, &i, s->lock) <= 0)
857         return 0;
858
859     REF_PRINT_COUNT("SSL", s);
860     REF_ASSERT_ISNT(i < 2);
861     return ((i > 1) ? 1 : 0);
862 }
863
864 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
865                                    unsigned int sid_ctx_len)
866 {
867     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
868         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
869                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
870         return 0;
871     }
872     ctx->sid_ctx_length = sid_ctx_len;
873     memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
874
875     return 1;
876 }
877
878 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
879                                unsigned int sid_ctx_len)
880 {
881     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
882         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
883                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
884         return 0;
885     }
886     ssl->sid_ctx_length = sid_ctx_len;
887     memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
888
889     return 1;
890 }
891
892 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
893 {
894     CRYPTO_THREAD_write_lock(ctx->lock);
895     ctx->generate_session_id = cb;
896     CRYPTO_THREAD_unlock(ctx->lock);
897     return 1;
898 }
899
900 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
901 {
902     CRYPTO_THREAD_write_lock(ssl->lock);
903     ssl->generate_session_id = cb;
904     CRYPTO_THREAD_unlock(ssl->lock);
905     return 1;
906 }
907
908 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
909                                 unsigned int id_len)
910 {
911     /*
912      * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
913      * we can "construct" a session to give us the desired check - i.e. to
914      * find if there's a session in the hash table that would conflict with
915      * any new session built out of this id/id_len and the ssl_version in use
916      * by this SSL.
917      */
918     SSL_SESSION r, *p;
919
920     if (id_len > sizeof(r.session_id))
921         return 0;
922
923     r.ssl_version = ssl->version;
924     r.session_id_length = id_len;
925     memcpy(r.session_id, id, id_len);
926
927     CRYPTO_THREAD_read_lock(ssl->session_ctx->lock);
928     p = lh_SSL_SESSION_retrieve(ssl->session_ctx->sessions, &r);
929     CRYPTO_THREAD_unlock(ssl->session_ctx->lock);
930     return (p != NULL);
931 }
932
933 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
934 {
935     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
936 }
937
938 int SSL_set_purpose(SSL *s, int purpose)
939 {
940     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
941 }
942
943 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
944 {
945     return X509_VERIFY_PARAM_set_trust(s->param, trust);
946 }
947
948 int SSL_set_trust(SSL *s, int trust)
949 {
950     return X509_VERIFY_PARAM_set_trust(s->param, trust);
951 }
952
953 int SSL_set1_host(SSL *s, const char *hostname)
954 {
955     return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
956 }
957
958 int SSL_add1_host(SSL *s, const char *hostname)
959 {
960     return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
961 }
962
963 void SSL_set_hostflags(SSL *s, unsigned int flags)
964 {
965     X509_VERIFY_PARAM_set_hostflags(s->param, flags);
966 }
967
968 const char *SSL_get0_peername(SSL *s)
969 {
970     return X509_VERIFY_PARAM_get0_peername(s->param);
971 }
972
973 int SSL_CTX_dane_enable(SSL_CTX *ctx)
974 {
975     return dane_ctx_enable(&ctx->dane);
976 }
977
978 unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags)
979 {
980     unsigned long orig = ctx->dane.flags;
981
982     ctx->dane.flags |= flags;
983     return orig;
984 }
985
986 unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags)
987 {
988     unsigned long orig = ctx->dane.flags;
989
990     ctx->dane.flags &= ~flags;
991     return orig;
992 }
993
994 int SSL_dane_enable(SSL *s, const char *basedomain)
995 {
996     SSL_DANE *dane = &s->dane;
997
998     if (s->ctx->dane.mdmax == 0) {
999         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
1000         return 0;
1001     }
1002     if (dane->trecs != NULL) {
1003         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
1004         return 0;
1005     }
1006
1007     /*
1008      * Default SNI name.  This rejects empty names, while set1_host below
1009      * accepts them and disables host name checks.  To avoid side-effects with
1010      * invalid input, set the SNI name first.
1011      */
1012     if (s->ext.hostname == NULL) {
1013         if (!SSL_set_tlsext_host_name(s, basedomain)) {
1014             SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
1015             return -1;
1016         }
1017     }
1018
1019     /* Primary RFC6125 reference identifier */
1020     if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
1021         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
1022         return -1;
1023     }
1024
1025     dane->mdpth = -1;
1026     dane->pdpth = -1;
1027     dane->dctx = &s->ctx->dane;
1028     dane->trecs = sk_danetls_record_new_null();
1029
1030     if (dane->trecs == NULL) {
1031         SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
1032         return -1;
1033     }
1034     return 1;
1035 }
1036
1037 unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags)
1038 {
1039     unsigned long orig = ssl->dane.flags;
1040
1041     ssl->dane.flags |= flags;
1042     return orig;
1043 }
1044
1045 unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags)
1046 {
1047     unsigned long orig = ssl->dane.flags;
1048
1049     ssl->dane.flags &= ~flags;
1050     return orig;
1051 }
1052
1053 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
1054 {
1055     SSL_DANE *dane = &s->dane;
1056
1057     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1058         return -1;
1059     if (dane->mtlsa) {
1060         if (mcert)
1061             *mcert = dane->mcert;
1062         if (mspki)
1063             *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
1064     }
1065     return dane->mdpth;
1066 }
1067
1068 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
1069                        uint8_t *mtype, unsigned const char **data, size_t *dlen)
1070 {
1071     SSL_DANE *dane = &s->dane;
1072
1073     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1074         return -1;
1075     if (dane->mtlsa) {
1076         if (usage)
1077             *usage = dane->mtlsa->usage;
1078         if (selector)
1079             *selector = dane->mtlsa->selector;
1080         if (mtype)
1081             *mtype = dane->mtlsa->mtype;
1082         if (data)
1083             *data = dane->mtlsa->data;
1084         if (dlen)
1085             *dlen = dane->mtlsa->dlen;
1086     }
1087     return dane->mdpth;
1088 }
1089
1090 SSL_DANE *SSL_get0_dane(SSL *s)
1091 {
1092     return &s->dane;
1093 }
1094
1095 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
1096                       uint8_t mtype, unsigned const char *data, size_t dlen)
1097 {
1098     return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
1099 }
1100
1101 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype,
1102                            uint8_t ord)
1103 {
1104     return dane_mtype_set(&ctx->dane, md, mtype, ord);
1105 }
1106
1107 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
1108 {
1109     return X509_VERIFY_PARAM_set1(ctx->param, vpm);
1110 }
1111
1112 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
1113 {
1114     return X509_VERIFY_PARAM_set1(ssl->param, vpm);
1115 }
1116
1117 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
1118 {
1119     return ctx->param;
1120 }
1121
1122 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
1123 {
1124     return ssl->param;
1125 }
1126
1127 void SSL_certs_clear(SSL *s)
1128 {
1129     ssl_cert_clear_certs(s->cert);
1130 }
1131
1132 void SSL_free(SSL *s)
1133 {
1134     int i;
1135
1136     if (s == NULL)
1137         return;
1138     CRYPTO_DOWN_REF(&s->references, &i, s->lock);
1139     REF_PRINT_COUNT("SSL", s);
1140     if (i > 0)
1141         return;
1142     REF_ASSERT_ISNT(i < 0);
1143
1144     X509_VERIFY_PARAM_free(s->param);
1145     dane_final(&s->dane);
1146     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
1147
1148     RECORD_LAYER_release(&s->rlayer);
1149
1150     /* Ignore return value */
1151     ssl_free_wbio_buffer(s);
1152
1153     BIO_free_all(s->wbio);
1154     s->wbio = NULL;
1155     BIO_free_all(s->rbio);
1156     s->rbio = NULL;
1157
1158     BUF_MEM_free(s->init_buf);
1159
1160     /* add extra stuff */
1161     sk_SSL_CIPHER_free(s->cipher_list);
1162     sk_SSL_CIPHER_free(s->cipher_list_by_id);
1163     sk_SSL_CIPHER_free(s->tls13_ciphersuites);
1164     sk_SSL_CIPHER_free(s->peer_ciphers);
1165
1166     /* Make the next call work :-) */
1167     if (s->session != NULL) {
1168         ssl_clear_bad_session(s);
1169         SSL_SESSION_free(s->session);
1170     }
1171     SSL_SESSION_free(s->psksession);
1172     OPENSSL_free(s->psksession_id);
1173
1174     clear_ciphers(s);
1175
1176     ssl_cert_free(s->cert);
1177     OPENSSL_free(s->shared_sigalgs);
1178     /* Free up if allocated */
1179
1180     OPENSSL_free(s->ext.hostname);
1181     SSL_CTX_free(s->session_ctx);
1182 #ifndef OPENSSL_NO_EC
1183     OPENSSL_free(s->ext.ecpointformats);
1184     OPENSSL_free(s->ext.peer_ecpointformats);
1185 #endif                          /* OPENSSL_NO_EC */
1186     OPENSSL_free(s->ext.supportedgroups);
1187     OPENSSL_free(s->ext.peer_supportedgroups);
1188     sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts, X509_EXTENSION_free);
1189 #ifndef OPENSSL_NO_OCSP
1190     sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
1191 #endif
1192 #ifndef OPENSSL_NO_CT
1193     SCT_LIST_free(s->scts);
1194     OPENSSL_free(s->ext.scts);
1195 #endif
1196     OPENSSL_free(s->ext.ocsp.resp);
1197     OPENSSL_free(s->ext.alpn);
1198     OPENSSL_free(s->ext.tls13_cookie);
1199     if (s->clienthello != NULL)
1200         OPENSSL_free(s->clienthello->pre_proc_exts);
1201     OPENSSL_free(s->clienthello);
1202     OPENSSL_free(s->pha_context);
1203     EVP_MD_CTX_free(s->pha_dgst);
1204
1205     sk_X509_NAME_pop_free(s->ca_names, X509_NAME_free);
1206     sk_X509_NAME_pop_free(s->client_ca_names, X509_NAME_free);
1207
1208     sk_X509_pop_free(s->verified_chain, X509_free);
1209
1210     if (s->method != NULL)
1211         s->method->ssl_free(s);
1212
1213     SSL_CTX_free(s->ctx);
1214
1215     ASYNC_WAIT_CTX_free(s->waitctx);
1216
1217 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1218     OPENSSL_free(s->ext.npn);
1219 #endif
1220
1221 #ifndef OPENSSL_NO_SRTP
1222     sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1223 #endif
1224
1225     CRYPTO_THREAD_lock_free(s->lock);
1226
1227     OPENSSL_free(s);
1228 }
1229
1230 void SSL_set0_rbio(SSL *s, BIO *rbio)
1231 {
1232     BIO_free_all(s->rbio);
1233     s->rbio = rbio;
1234 }
1235
1236 void SSL_set0_wbio(SSL *s, BIO *wbio)
1237 {
1238     /*
1239      * If the output buffering BIO is still in place, remove it
1240      */
1241     if (s->bbio != NULL)
1242         s->wbio = BIO_pop(s->wbio);
1243
1244     BIO_free_all(s->wbio);
1245     s->wbio = wbio;
1246
1247     /* Re-attach |bbio| to the new |wbio|. */
1248     if (s->bbio != NULL)
1249         s->wbio = BIO_push(s->bbio, s->wbio);
1250 }
1251
1252 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1253 {
1254     /*
1255      * For historical reasons, this function has many different cases in
1256      * ownership handling.
1257      */
1258
1259     /* If nothing has changed, do nothing */
1260     if (rbio == SSL_get_rbio(s) && wbio == SSL_get_wbio(s))
1261         return;
1262
1263     /*
1264      * If the two arguments are equal then one fewer reference is granted by the
1265      * caller than we want to take
1266      */
1267     if (rbio != NULL && rbio == wbio)
1268         BIO_up_ref(rbio);
1269
1270     /*
1271      * If only the wbio is changed only adopt one reference.
1272      */
1273     if (rbio == SSL_get_rbio(s)) {
1274         SSL_set0_wbio(s, wbio);
1275         return;
1276     }
1277     /*
1278      * There is an asymmetry here for historical reasons. If only the rbio is
1279      * changed AND the rbio and wbio were originally different, then we only
1280      * adopt one reference.
1281      */
1282     if (wbio == SSL_get_wbio(s) && SSL_get_rbio(s) != SSL_get_wbio(s)) {
1283         SSL_set0_rbio(s, rbio);
1284         return;
1285     }
1286
1287     /* Otherwise, adopt both references. */
1288     SSL_set0_rbio(s, rbio);
1289     SSL_set0_wbio(s, wbio);
1290 }
1291
1292 BIO *SSL_get_rbio(const SSL *s)
1293 {
1294     return s->rbio;
1295 }
1296
1297 BIO *SSL_get_wbio(const SSL *s)
1298 {
1299     if (s->bbio != NULL) {
1300         /*
1301          * If |bbio| is active, the true caller-configured BIO is its
1302          * |next_bio|.
1303          */
1304         return BIO_next(s->bbio);
1305     }
1306     return s->wbio;
1307 }
1308
1309 int SSL_get_fd(const SSL *s)
1310 {
1311     return SSL_get_rfd(s);
1312 }
1313
1314 int SSL_get_rfd(const SSL *s)
1315 {
1316     int ret = -1;
1317     BIO *b, *r;
1318
1319     b = SSL_get_rbio(s);
1320     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1321     if (r != NULL)
1322         BIO_get_fd(r, &ret);
1323     return ret;
1324 }
1325
1326 int SSL_get_wfd(const SSL *s)
1327 {
1328     int ret = -1;
1329     BIO *b, *r;
1330
1331     b = SSL_get_wbio(s);
1332     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1333     if (r != NULL)
1334         BIO_get_fd(r, &ret);
1335     return ret;
1336 }
1337
1338 #ifndef OPENSSL_NO_SOCK
1339 int SSL_set_fd(SSL *s, int fd)
1340 {
1341     int ret = 0;
1342     BIO *bio = NULL;
1343
1344     bio = BIO_new(BIO_s_socket());
1345
1346     if (bio == NULL) {
1347         SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1348         goto err;
1349     }
1350     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1351     SSL_set_bio(s, bio, bio);
1352 #ifndef OPENSSL_NO_KTLS
1353     /*
1354      * The new socket is created successfully regardless of ktls_enable.
1355      * ktls_enable doesn't change any functionality of the socket, except
1356      * changing the setsockopt to enable the processing of ktls_start.
1357      * Thus, it is not a problem to call it for non-TLS sockets.
1358      */
1359     ktls_enable(fd);
1360 #endif /* OPENSSL_NO_KTLS */
1361     ret = 1;
1362  err:
1363     return ret;
1364 }
1365
1366 int SSL_set_wfd(SSL *s, int fd)
1367 {
1368     BIO *rbio = SSL_get_rbio(s);
1369
1370     if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET
1371         || (int)BIO_get_fd(rbio, NULL) != fd) {
1372         BIO *bio = BIO_new(BIO_s_socket());
1373
1374         if (bio == NULL) {
1375             SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1376             return 0;
1377         }
1378         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1379         SSL_set0_wbio(s, bio);
1380 #ifndef OPENSSL_NO_KTLS
1381         /*
1382          * The new socket is created successfully regardless of ktls_enable.
1383          * ktls_enable doesn't change any functionality of the socket, except
1384          * changing the setsockopt to enable the processing of ktls_start.
1385          * Thus, it is not a problem to call it for non-TLS sockets.
1386          */
1387         ktls_enable(fd);
1388 #endif /* OPENSSL_NO_KTLS */
1389     } else {
1390         BIO_up_ref(rbio);
1391         SSL_set0_wbio(s, rbio);
1392     }
1393     return 1;
1394 }
1395
1396 int SSL_set_rfd(SSL *s, int fd)
1397 {
1398     BIO *wbio = SSL_get_wbio(s);
1399
1400     if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET
1401         || ((int)BIO_get_fd(wbio, NULL) != fd)) {
1402         BIO *bio = BIO_new(BIO_s_socket());
1403
1404         if (bio == NULL) {
1405             SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1406             return 0;
1407         }
1408         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1409         SSL_set0_rbio(s, bio);
1410     } else {
1411         BIO_up_ref(wbio);
1412         SSL_set0_rbio(s, wbio);
1413     }
1414
1415     return 1;
1416 }
1417 #endif
1418
1419 /* return length of latest Finished message we sent, copy to 'buf' */
1420 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1421 {
1422     size_t ret = 0;
1423
1424     ret = s->s3.tmp.finish_md_len;
1425     if (count > ret)
1426         count = ret;
1427     memcpy(buf, s->s3.tmp.finish_md, count);
1428     return ret;
1429 }
1430
1431 /* return length of latest Finished message we expected, copy to 'buf' */
1432 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1433 {
1434     size_t ret = 0;
1435
1436     ret = s->s3.tmp.peer_finish_md_len;
1437     if (count > ret)
1438         count = ret;
1439     memcpy(buf, s->s3.tmp.peer_finish_md, count);
1440     return ret;
1441 }
1442
1443 int SSL_get_verify_mode(const SSL *s)
1444 {
1445     return s->verify_mode;
1446 }
1447
1448 int SSL_get_verify_depth(const SSL *s)
1449 {
1450     return X509_VERIFY_PARAM_get_depth(s->param);
1451 }
1452
1453 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1454     return s->verify_callback;
1455 }
1456
1457 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1458 {
1459     return ctx->verify_mode;
1460 }
1461
1462 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1463 {
1464     return X509_VERIFY_PARAM_get_depth(ctx->param);
1465 }
1466
1467 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1468     return ctx->default_verify_callback;
1469 }
1470
1471 void SSL_set_verify(SSL *s, int mode,
1472                     int (*callback) (int ok, X509_STORE_CTX *ctx))
1473 {
1474     s->verify_mode = mode;
1475     if (callback != NULL)
1476         s->verify_callback = callback;
1477 }
1478
1479 void SSL_set_verify_depth(SSL *s, int depth)
1480 {
1481     X509_VERIFY_PARAM_set_depth(s->param, depth);
1482 }
1483
1484 void SSL_set_read_ahead(SSL *s, int yes)
1485 {
1486     RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1487 }
1488
1489 int SSL_get_read_ahead(const SSL *s)
1490 {
1491     return RECORD_LAYER_get_read_ahead(&s->rlayer);
1492 }
1493
1494 int SSL_pending(const SSL *s)
1495 {
1496     size_t pending = s->method->ssl_pending(s);
1497
1498     /*
1499      * SSL_pending cannot work properly if read-ahead is enabled
1500      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1501      * impossible to fix since SSL_pending cannot report errors that may be
1502      * observed while scanning the new data. (Note that SSL_pending() is
1503      * often used as a boolean value, so we'd better not return -1.)
1504      *
1505      * SSL_pending also cannot work properly if the value >INT_MAX. In that case
1506      * we just return INT_MAX.
1507      */
1508     return pending < INT_MAX ? (int)pending : INT_MAX;
1509 }
1510
1511 int SSL_has_pending(const SSL *s)
1512 {
1513     /*
1514      * Similar to SSL_pending() but returns a 1 to indicate that we have
1515      * unprocessed data available or 0 otherwise (as opposed to the number of
1516      * bytes available). Unlike SSL_pending() this will take into account
1517      * read_ahead data. A 1 return simply indicates that we have unprocessed
1518      * data. That data may not result in any application data, or we may fail
1519      * to parse the records for some reason.
1520      */
1521     if (RECORD_LAYER_processed_read_pending(&s->rlayer))
1522         return 1;
1523
1524     return RECORD_LAYER_read_pending(&s->rlayer);
1525 }
1526
1527 X509 *SSL_get_peer_certificate(const SSL *s)
1528 {
1529     X509 *r;
1530
1531     if ((s == NULL) || (s->session == NULL))
1532         r = NULL;
1533     else
1534         r = s->session->peer;
1535
1536     if (r == NULL)
1537         return r;
1538
1539     X509_up_ref(r);
1540
1541     return r;
1542 }
1543
1544 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1545 {
1546     STACK_OF(X509) *r;
1547
1548     if ((s == NULL) || (s->session == NULL))
1549         r = NULL;
1550     else
1551         r = s->session->peer_chain;
1552
1553     /*
1554      * If we are a client, cert_chain includes the peer's own certificate; if
1555      * we are a server, it does not.
1556      */
1557
1558     return r;
1559 }
1560
1561 /*
1562  * Now in theory, since the calling process own 't' it should be safe to
1563  * modify.  We need to be able to read f without being hassled
1564  */
1565 int SSL_copy_session_id(SSL *t, const SSL *f)
1566 {
1567     int i;
1568     /* Do we need to to SSL locking? */
1569     if (!SSL_set_session(t, SSL_get_session(f))) {
1570         return 0;
1571     }
1572
1573     /*
1574      * what if we are setup for one protocol version but want to talk another
1575      */
1576     if (t->method != f->method) {
1577         t->method->ssl_free(t);
1578         t->method = f->method;
1579         if (t->method->ssl_new(t) == 0)
1580             return 0;
1581     }
1582
1583     CRYPTO_UP_REF(&f->cert->references, &i, f->cert->lock);
1584     ssl_cert_free(t->cert);
1585     t->cert = f->cert;
1586     if (!SSL_set_session_id_context(t, f->sid_ctx, (int)f->sid_ctx_length)) {
1587         return 0;
1588     }
1589
1590     return 1;
1591 }
1592
1593 /* Fix this so it checks all the valid key/cert options */
1594 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1595 {
1596     if ((ctx == NULL) || (ctx->cert->key->x509 == NULL)) {
1597         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1598         return 0;
1599     }
1600     if (ctx->cert->key->privatekey == NULL) {
1601         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1602         return 0;
1603     }
1604     return X509_check_private_key
1605             (ctx->cert->key->x509, ctx->cert->key->privatekey);
1606 }
1607
1608 /* Fix this function so that it takes an optional type parameter */
1609 int SSL_check_private_key(const SSL *ssl)
1610 {
1611     if (ssl == NULL) {
1612         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1613         return 0;
1614     }
1615     if (ssl->cert->key->x509 == NULL) {
1616         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1617         return 0;
1618     }
1619     if (ssl->cert->key->privatekey == NULL) {
1620         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1621         return 0;
1622     }
1623     return X509_check_private_key(ssl->cert->key->x509,
1624                                    ssl->cert->key->privatekey);
1625 }
1626
1627 int SSL_waiting_for_async(SSL *s)
1628 {
1629     if (s->job)
1630         return 1;
1631
1632     return 0;
1633 }
1634
1635 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1636 {
1637     ASYNC_WAIT_CTX *ctx = s->waitctx;
1638
1639     if (ctx == NULL)
1640         return 0;
1641     return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1642 }
1643
1644 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1645                               OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1646 {
1647     ASYNC_WAIT_CTX *ctx = s->waitctx;
1648
1649     if (ctx == NULL)
1650         return 0;
1651     return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1652                                           numdelfds);
1653 }
1654
1655 int SSL_CTX_set_async_callback(SSL_CTX *ctx, SSL_async_callback_fn callback)
1656 {
1657     ctx->async_cb = callback;
1658     return 1;
1659 }
1660
1661 int SSL_CTX_set_async_callback_arg(SSL_CTX *ctx, void *arg)
1662 {
1663     ctx->async_cb_arg = arg;
1664     return 1;
1665 }
1666
1667 int SSL_set_async_callback(SSL *s, SSL_async_callback_fn callback)
1668 {
1669     s->async_cb = callback;
1670     return 1;
1671 }
1672
1673 int SSL_set_async_callback_arg(SSL *s, void *arg)
1674 {
1675     s->async_cb_arg = arg;
1676     return 1;
1677 }
1678
1679 int SSL_get_async_status(SSL *s, int *status)
1680 {
1681     ASYNC_WAIT_CTX *ctx = s->waitctx;
1682
1683     if (ctx == NULL)
1684         return 0;
1685     *status = ASYNC_WAIT_CTX_get_status(ctx);
1686     return 1;
1687 }
1688
1689 int SSL_accept(SSL *s)
1690 {
1691     if (s->handshake_func == NULL) {
1692         /* Not properly initialized yet */
1693         SSL_set_accept_state(s);
1694     }
1695
1696     return SSL_do_handshake(s);
1697 }
1698
1699 int SSL_connect(SSL *s)
1700 {
1701     if (s->handshake_func == NULL) {
1702         /* Not properly initialized yet */
1703         SSL_set_connect_state(s);
1704     }
1705
1706     return SSL_do_handshake(s);
1707 }
1708
1709 long SSL_get_default_timeout(const SSL *s)
1710 {
1711     return s->method->get_timeout();
1712 }
1713
1714 static int ssl_async_wait_ctx_cb(void *arg)
1715 {
1716     SSL *s = (SSL *)arg;
1717
1718     return s->async_cb(s, s->async_cb_arg);
1719 }
1720
1721 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1722                                int (*func) (void *))
1723 {
1724     int ret;
1725     if (s->waitctx == NULL) {
1726         s->waitctx = ASYNC_WAIT_CTX_new();
1727         if (s->waitctx == NULL)
1728             return -1;
1729         if (s->async_cb != NULL
1730             && !ASYNC_WAIT_CTX_set_callback
1731                  (s->waitctx, ssl_async_wait_ctx_cb, s))
1732             return -1;
1733     }
1734     switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1735                             sizeof(struct ssl_async_args))) {
1736     case ASYNC_ERR:
1737         s->rwstate = SSL_NOTHING;
1738         SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1739         return -1;
1740     case ASYNC_PAUSE:
1741         s->rwstate = SSL_ASYNC_PAUSED;
1742         return -1;
1743     case ASYNC_NO_JOBS:
1744         s->rwstate = SSL_ASYNC_NO_JOBS;
1745         return -1;
1746     case ASYNC_FINISH:
1747         s->job = NULL;
1748         return ret;
1749     default:
1750         s->rwstate = SSL_NOTHING;
1751         SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1752         /* Shouldn't happen */
1753         return -1;
1754     }
1755 }
1756
1757 static int ssl_io_intern(void *vargs)
1758 {
1759     struct ssl_async_args *args;
1760     SSL *s;
1761     void *buf;
1762     size_t num;
1763
1764     args = (struct ssl_async_args *)vargs;
1765     s = args->s;
1766     buf = args->buf;
1767     num = args->num;
1768     switch (args->type) {
1769     case READFUNC:
1770         return args->f.func_read(s, buf, num, &s->asyncrw);
1771     case WRITEFUNC:
1772         return args->f.func_write(s, buf, num, &s->asyncrw);
1773     case OTHERFUNC:
1774         return args->f.func_other(s);
1775     }
1776     return -1;
1777 }
1778
1779 int ssl_read_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1780 {
1781     if (s->handshake_func == NULL) {
1782         SSLerr(SSL_F_SSL_READ_INTERNAL, SSL_R_UNINITIALIZED);
1783         return -1;
1784     }
1785
1786     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1787         s->rwstate = SSL_NOTHING;
1788         return 0;
1789     }
1790
1791     if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1792                 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY) {
1793         SSLerr(SSL_F_SSL_READ_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1794         return 0;
1795     }
1796     /*
1797      * If we are a client and haven't received the ServerHello etc then we
1798      * better do that
1799      */
1800     ossl_statem_check_finish_init(s, 0);
1801
1802     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1803         struct ssl_async_args args;
1804         int ret;
1805
1806         args.s = s;
1807         args.buf = buf;
1808         args.num = num;
1809         args.type = READFUNC;
1810         args.f.func_read = s->method->ssl_read;
1811
1812         ret = ssl_start_async_job(s, &args, ssl_io_intern);
1813         *readbytes = s->asyncrw;
1814         return ret;
1815     } else {
1816         return s->method->ssl_read(s, buf, num, readbytes);
1817     }
1818 }
1819
1820 int SSL_read(SSL *s, void *buf, int num)
1821 {
1822     int ret;
1823     size_t readbytes;
1824
1825     if (num < 0) {
1826         SSLerr(SSL_F_SSL_READ, SSL_R_BAD_LENGTH);
1827         return -1;
1828     }
1829
1830     ret = ssl_read_internal(s, buf, (size_t)num, &readbytes);
1831
1832     /*
1833      * The cast is safe here because ret should be <= INT_MAX because num is
1834      * <= INT_MAX
1835      */
1836     if (ret > 0)
1837         ret = (int)readbytes;
1838
1839     return ret;
1840 }
1841
1842 int SSL_read_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1843 {
1844     int ret = ssl_read_internal(s, buf, num, readbytes);
1845
1846     if (ret < 0)
1847         ret = 0;
1848     return ret;
1849 }
1850
1851 int SSL_read_early_data(SSL *s, void *buf, size_t num, size_t *readbytes)
1852 {
1853     int ret;
1854
1855     if (!s->server) {
1856         SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1857         return SSL_READ_EARLY_DATA_ERROR;
1858     }
1859
1860     switch (s->early_data_state) {
1861     case SSL_EARLY_DATA_NONE:
1862         if (!SSL_in_before(s)) {
1863             SSLerr(SSL_F_SSL_READ_EARLY_DATA,
1864                    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1865             return SSL_READ_EARLY_DATA_ERROR;
1866         }
1867         /* fall through */
1868
1869     case SSL_EARLY_DATA_ACCEPT_RETRY:
1870         s->early_data_state = SSL_EARLY_DATA_ACCEPTING;
1871         ret = SSL_accept(s);
1872         if (ret <= 0) {
1873             /* NBIO or error */
1874             s->early_data_state = SSL_EARLY_DATA_ACCEPT_RETRY;
1875             return SSL_READ_EARLY_DATA_ERROR;
1876         }
1877         /* fall through */
1878
1879     case SSL_EARLY_DATA_READ_RETRY:
1880         if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
1881             s->early_data_state = SSL_EARLY_DATA_READING;
1882             ret = SSL_read_ex(s, buf, num, readbytes);
1883             /*
1884              * State machine will update early_data_state to
1885              * SSL_EARLY_DATA_FINISHED_READING if we get an EndOfEarlyData
1886              * message
1887              */
1888             if (ret > 0 || (ret <= 0 && s->early_data_state
1889                                         != SSL_EARLY_DATA_FINISHED_READING)) {
1890                 s->early_data_state = SSL_EARLY_DATA_READ_RETRY;
1891                 return ret > 0 ? SSL_READ_EARLY_DATA_SUCCESS
1892                                : SSL_READ_EARLY_DATA_ERROR;
1893             }
1894         } else {
1895             s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
1896         }
1897         *readbytes = 0;
1898         return SSL_READ_EARLY_DATA_FINISH;
1899
1900     default:
1901         SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1902         return SSL_READ_EARLY_DATA_ERROR;
1903     }
1904 }
1905
1906 int SSL_get_early_data_status(const SSL *s)
1907 {
1908     return s->ext.early_data;
1909 }
1910
1911 static int ssl_peek_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1912 {
1913     if (s->handshake_func == NULL) {
1914         SSLerr(SSL_F_SSL_PEEK_INTERNAL, SSL_R_UNINITIALIZED);
1915         return -1;
1916     }
1917
1918     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1919         return 0;
1920     }
1921     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1922         struct ssl_async_args args;
1923         int ret;
1924
1925         args.s = s;
1926         args.buf = buf;
1927         args.num = num;
1928         args.type = READFUNC;
1929         args.f.func_read = s->method->ssl_peek;
1930
1931         ret = ssl_start_async_job(s, &args, ssl_io_intern);
1932         *readbytes = s->asyncrw;
1933         return ret;
1934     } else {
1935         return s->method->ssl_peek(s, buf, num, readbytes);
1936     }
1937 }
1938
1939 int SSL_peek(SSL *s, void *buf, int num)
1940 {
1941     int ret;
1942     size_t readbytes;
1943
1944     if (num < 0) {
1945         SSLerr(SSL_F_SSL_PEEK, SSL_R_BAD_LENGTH);
1946         return -1;
1947     }
1948
1949     ret = ssl_peek_internal(s, buf, (size_t)num, &readbytes);
1950
1951     /*
1952      * The cast is safe here because ret should be <= INT_MAX because num is
1953      * <= INT_MAX
1954      */
1955     if (ret > 0)
1956         ret = (int)readbytes;
1957
1958     return ret;
1959 }
1960
1961
1962 int SSL_peek_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1963 {
1964     int ret = ssl_peek_internal(s, buf, num, readbytes);
1965
1966     if (ret < 0)
1967         ret = 0;
1968     return ret;
1969 }
1970
1971 int ssl_write_internal(SSL *s, const void *buf, size_t num, size_t *written)
1972 {
1973     if (s->handshake_func == NULL) {
1974         SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_UNINITIALIZED);
1975         return -1;
1976     }
1977
1978     if (s->shutdown & SSL_SENT_SHUTDOWN) {
1979         s->rwstate = SSL_NOTHING;
1980         SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_PROTOCOL_IS_SHUTDOWN);
1981         return -1;
1982     }
1983
1984     if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1985                 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY
1986                 || s->early_data_state == SSL_EARLY_DATA_READ_RETRY) {
1987         SSLerr(SSL_F_SSL_WRITE_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1988         return 0;
1989     }
1990     /* If we are a client and haven't sent the Finished we better do that */
1991     ossl_statem_check_finish_init(s, 1);
1992
1993     if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1994         int ret;
1995         struct ssl_async_args args;
1996
1997         args.s = s;
1998         args.buf = (void *)buf;
1999         args.num = num;
2000         args.type = WRITEFUNC;
2001         args.f.func_write = s->method->ssl_write;
2002
2003         ret = ssl_start_async_job(s, &args, ssl_io_intern);
2004         *written = s->asyncrw;
2005         return ret;
2006     } else {
2007         return s->method->ssl_write(s, buf, num, written);
2008     }
2009 }
2010
2011 ossl_ssize_t SSL_sendfile(SSL *s, int fd, off_t offset, size_t size, int flags)
2012 {
2013     ossl_ssize_t ret;
2014
2015     if (s->handshake_func == NULL) {
2016         SSLerr(SSL_F_SSL_SENDFILE, SSL_R_UNINITIALIZED);
2017         return -1;
2018     }
2019
2020     if (s->shutdown & SSL_SENT_SHUTDOWN) {
2021         s->rwstate = SSL_NOTHING;
2022         SSLerr(SSL_F_SSL_SENDFILE, SSL_R_PROTOCOL_IS_SHUTDOWN);
2023         return -1;
2024     }
2025
2026     if (!BIO_get_ktls_send(s->wbio)) {
2027         SSLerr(SSL_F_SSL_SENDFILE, SSL_R_UNINITIALIZED);
2028         return -1;
2029     }
2030
2031     /* If we have an alert to send, lets send it */
2032     if (s->s3.alert_dispatch) {
2033         ret = (ossl_ssize_t)s->method->ssl_dispatch_alert(s);
2034         if (ret <= 0) {
2035             /* SSLfatal() already called if appropriate */
2036             return ret;
2037         }
2038         /* if it went, fall through and send more stuff */
2039     }
2040
2041     s->rwstate = SSL_WRITING;
2042     if (BIO_flush(s->wbio) <= 0) {
2043         if (!BIO_should_retry(s->wbio)) {
2044             s->rwstate = SSL_NOTHING;
2045         } else {
2046 #ifdef EAGAIN
2047             set_sys_error(EAGAIN);
2048 #endif
2049         }
2050         return -1;
2051     }
2052
2053 #ifdef OPENSSL_NO_KTLS
2054     ERR_raise_data(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR,
2055                    "can't call ktls_sendfile(), ktls disabled");
2056     return -1;
2057 #else
2058     ret = ktls_sendfile(SSL_get_wfd(s), fd, offset, size, flags);
2059     if (ret < 0) {
2060 #if defined(EAGAIN) && defined(EINTR) && defined(EBUSY)
2061         if ((get_last_sys_error() == EAGAIN) ||
2062             (get_last_sys_error() == EINTR) ||
2063             (get_last_sys_error() == EBUSY))
2064             BIO_set_retry_write(s->wbio);
2065         else
2066 #endif
2067             SSLerr(SSL_F_SSL_SENDFILE, SSL_R_UNINITIALIZED);
2068         return ret;
2069     }
2070     s->rwstate = SSL_NOTHING;
2071     return ret;
2072 #endif
2073 }
2074
2075 int SSL_write(SSL *s, const void *buf, int num)
2076 {
2077     int ret;
2078     size_t written;
2079
2080     if (num < 0) {
2081         SSLerr(SSL_F_SSL_WRITE, SSL_R_BAD_LENGTH);
2082         return -1;
2083     }
2084
2085     ret = ssl_write_internal(s, buf, (size_t)num, &written);
2086
2087     /*
2088      * The cast is safe here because ret should be <= INT_MAX because num is
2089      * <= INT_MAX
2090      */
2091     if (ret > 0)
2092         ret = (int)written;
2093
2094     return ret;
2095 }
2096
2097 int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
2098 {
2099     int ret = ssl_write_internal(s, buf, num, written);
2100
2101     if (ret < 0)
2102         ret = 0;
2103     return ret;
2104 }
2105
2106 int SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
2107 {
2108     int ret, early_data_state;
2109     size_t writtmp;
2110     uint32_t partialwrite;
2111
2112     switch (s->early_data_state) {
2113     case SSL_EARLY_DATA_NONE:
2114         if (s->server
2115                 || !SSL_in_before(s)
2116                 || ((s->session == NULL || s->session->ext.max_early_data == 0)
2117                      && (s->psk_use_session_cb == NULL))) {
2118             SSLerr(SSL_F_SSL_WRITE_EARLY_DATA,
2119                    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2120             return 0;
2121         }
2122         /* fall through */
2123
2124     case SSL_EARLY_DATA_CONNECT_RETRY:
2125         s->early_data_state = SSL_EARLY_DATA_CONNECTING;
2126         ret = SSL_connect(s);
2127         if (ret <= 0) {
2128             /* NBIO or error */
2129             s->early_data_state = SSL_EARLY_DATA_CONNECT_RETRY;
2130             return 0;
2131         }
2132         /* fall through */
2133
2134     case SSL_EARLY_DATA_WRITE_RETRY:
2135         s->early_data_state = SSL_EARLY_DATA_WRITING;
2136         /*
2137          * We disable partial write for early data because we don't keep track
2138          * of how many bytes we've written between the SSL_write_ex() call and
2139          * the flush if the flush needs to be retried)
2140          */
2141         partialwrite = s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE;
2142         s->mode &= ~SSL_MODE_ENABLE_PARTIAL_WRITE;
2143         ret = SSL_write_ex(s, buf, num, &writtmp);
2144         s->mode |= partialwrite;
2145         if (!ret) {
2146             s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
2147             return ret;
2148         }
2149         s->early_data_state = SSL_EARLY_DATA_WRITE_FLUSH;
2150         /* fall through */
2151
2152     case SSL_EARLY_DATA_WRITE_FLUSH:
2153         /* The buffering BIO is still in place so we need to flush it */
2154         if (statem_flush(s) != 1)
2155             return 0;
2156         *written = num;
2157         s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
2158         return 1;
2159
2160     case SSL_EARLY_DATA_FINISHED_READING:
2161     case SSL_EARLY_DATA_READ_RETRY:
2162         early_data_state = s->early_data_state;
2163         /* We are a server writing to an unauthenticated client */
2164         s->early_data_state = SSL_EARLY_DATA_UNAUTH_WRITING;
2165         ret = SSL_write_ex(s, buf, num, written);
2166         /* The buffering BIO is still in place */
2167         if (ret)
2168             (void)BIO_flush(s->wbio);
2169         s->early_data_state = early_data_state;
2170         return ret;
2171
2172     default:
2173         SSLerr(SSL_F_SSL_WRITE_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2174         return 0;
2175     }
2176 }
2177
2178 int SSL_shutdown(SSL *s)
2179 {
2180     /*
2181      * Note that this function behaves differently from what one might
2182      * expect.  Return values are 0 for no success (yet), 1 for success; but
2183      * calling it once is usually not enough, even if blocking I/O is used
2184      * (see ssl3_shutdown).
2185      */
2186
2187     if (s->handshake_func == NULL) {
2188         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
2189         return -1;
2190     }
2191
2192     if (!SSL_in_init(s)) {
2193         if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
2194             struct ssl_async_args args;
2195
2196             args.s = s;
2197             args.type = OTHERFUNC;
2198             args.f.func_other = s->method->ssl_shutdown;
2199
2200             return ssl_start_async_job(s, &args, ssl_io_intern);
2201         } else {
2202             return s->method->ssl_shutdown(s);
2203         }
2204     } else {
2205         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
2206         return -1;
2207     }
2208 }
2209
2210 int SSL_key_update(SSL *s, int updatetype)
2211 {
2212     /*
2213      * TODO(TLS1.3): How will applications know whether TLSv1.3 has been
2214      * negotiated, and that it is appropriate to call SSL_key_update() instead
2215      * of SSL_renegotiate().
2216      */
2217     if (!SSL_IS_TLS13(s)) {
2218         SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_WRONG_SSL_VERSION);
2219         return 0;
2220     }
2221
2222     if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
2223             && updatetype != SSL_KEY_UPDATE_REQUESTED) {
2224         SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_INVALID_KEY_UPDATE_TYPE);
2225         return 0;
2226     }
2227
2228     if (!SSL_is_init_finished(s)) {
2229         SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_STILL_IN_INIT);
2230         return 0;
2231     }
2232
2233     ossl_statem_set_in_init(s, 1);
2234     s->key_update = updatetype;
2235     return 1;
2236 }
2237
2238 int SSL_get_key_update_type(const SSL *s)
2239 {
2240     return s->key_update;
2241 }
2242
2243 int SSL_renegotiate(SSL *s)
2244 {
2245     if (SSL_IS_TLS13(s)) {
2246         SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_WRONG_SSL_VERSION);
2247         return 0;
2248     }
2249
2250     if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
2251         SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_NO_RENEGOTIATION);
2252         return 0;
2253     }
2254
2255     s->renegotiate = 1;
2256     s->new_session = 1;
2257
2258     return s->method->ssl_renegotiate(s);
2259 }
2260
2261 int SSL_renegotiate_abbreviated(SSL *s)
2262 {
2263     if (SSL_IS_TLS13(s)) {
2264         SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_WRONG_SSL_VERSION);
2265         return 0;
2266     }
2267
2268     if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
2269         SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_NO_RENEGOTIATION);
2270         return 0;
2271     }
2272
2273     s->renegotiate = 1;
2274     s->new_session = 0;
2275
2276     return s->method->ssl_renegotiate(s);
2277 }
2278
2279 int SSL_renegotiate_pending(const SSL *s)
2280 {
2281     /*
2282      * becomes true when negotiation is requested; false again once a
2283      * handshake has finished
2284      */
2285     return (s->renegotiate != 0);
2286 }
2287
2288 int SSL_new_session_ticket(SSL *s)
2289 {
2290     if (SSL_in_init(s) || SSL_IS_FIRST_HANDSHAKE(s) || !s->server
2291             || !SSL_IS_TLS13(s))
2292         return 0;
2293     s->ext.extra_tickets_expected++;
2294     return 1;
2295 }
2296
2297 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
2298 {
2299     long l;
2300
2301     switch (cmd) {
2302     case SSL_CTRL_GET_READ_AHEAD:
2303         return RECORD_LAYER_get_read_ahead(&s->rlayer);
2304     case SSL_CTRL_SET_READ_AHEAD:
2305         l = RECORD_LAYER_get_read_ahead(&s->rlayer);
2306         RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
2307         return l;
2308
2309     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2310         s->msg_callback_arg = parg;
2311         return 1;
2312
2313     case SSL_CTRL_MODE:
2314         return (s->mode |= larg);
2315     case SSL_CTRL_CLEAR_MODE:
2316         return (s->mode &= ~larg);
2317     case SSL_CTRL_GET_MAX_CERT_LIST:
2318         return (long)s->max_cert_list;
2319     case SSL_CTRL_SET_MAX_CERT_LIST:
2320         if (larg < 0)
2321             return 0;
2322         l = (long)s->max_cert_list;
2323         s->max_cert_list = (size_t)larg;
2324         return l;
2325     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2326         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2327             return 0;
2328 #ifndef OPENSSL_NO_KTLS
2329         if (s->wbio != NULL && BIO_get_ktls_send(s->wbio))
2330             return 0;
2331 #endif /* OPENSSL_NO_KTLS */
2332         s->max_send_fragment = larg;
2333         if (s->max_send_fragment < s->split_send_fragment)
2334             s->split_send_fragment = s->max_send_fragment;
2335         return 1;
2336     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2337         if ((size_t)larg > s->max_send_fragment || larg == 0)
2338             return 0;
2339         s->split_send_fragment = larg;
2340         return 1;
2341     case SSL_CTRL_SET_MAX_PIPELINES:
2342         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2343             return 0;
2344         s->max_pipelines = larg;
2345         if (larg > 1)
2346             RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
2347         return 1;
2348     case SSL_CTRL_GET_RI_SUPPORT:
2349         return s->s3.send_connection_binding;
2350     case SSL_CTRL_CERT_FLAGS:
2351         return (s->cert->cert_flags |= larg);
2352     case SSL_CTRL_CLEAR_CERT_FLAGS:
2353         return (s->cert->cert_flags &= ~larg);
2354
2355     case SSL_CTRL_GET_RAW_CIPHERLIST:
2356         if (parg) {
2357             if (s->s3.tmp.ciphers_raw == NULL)
2358                 return 0;
2359             *(unsigned char **)parg = s->s3.tmp.ciphers_raw;
2360             return (int)s->s3.tmp.ciphers_rawlen;
2361         } else {
2362             return TLS_CIPHER_LEN;
2363         }
2364     case SSL_CTRL_GET_EXTMS_SUPPORT:
2365         if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
2366             return -1;
2367         if (s->session->flags & SSL_SESS_FLAG_EXTMS)
2368             return 1;
2369         else
2370             return 0;
2371     case SSL_CTRL_SET_MIN_PROTO_VERSION:
2372         return ssl_check_allowed_versions(larg, s->max_proto_version)
2373                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2374                                         &s->min_proto_version);
2375     case SSL_CTRL_GET_MIN_PROTO_VERSION:
2376         return s->min_proto_version;
2377     case SSL_CTRL_SET_MAX_PROTO_VERSION:
2378         return ssl_check_allowed_versions(s->min_proto_version, larg)
2379                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2380                                         &s->max_proto_version);
2381     case SSL_CTRL_GET_MAX_PROTO_VERSION:
2382         return s->max_proto_version;
2383     default:
2384         return s->method->ssl_ctrl(s, cmd, larg, parg);
2385     }
2386 }
2387
2388 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
2389 {
2390     switch (cmd) {
2391     case SSL_CTRL_SET_MSG_CALLBACK:
2392         s->msg_callback = (void (*)
2393                            (int write_p, int version, int content_type,
2394                             const void *buf, size_t len, SSL *ssl,
2395                             void *arg))(fp);
2396         return 1;
2397
2398     default:
2399         return s->method->ssl_callback_ctrl(s, cmd, fp);
2400     }
2401 }
2402
2403 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
2404 {
2405     return ctx->sessions;
2406 }
2407
2408 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
2409 {
2410     long l;
2411     /* For some cases with ctx == NULL perform syntax checks */
2412     if (ctx == NULL) {
2413         switch (cmd) {
2414         case SSL_CTRL_SET_GROUPS_LIST:
2415             return tls1_set_groups_list(ctx, NULL, NULL, parg);
2416         case SSL_CTRL_SET_SIGALGS_LIST:
2417         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
2418             return tls1_set_sigalgs_list(NULL, parg, 0);
2419         default:
2420             return 0;
2421         }
2422     }
2423
2424     switch (cmd) {
2425     case SSL_CTRL_GET_READ_AHEAD:
2426         return ctx->read_ahead;
2427     case SSL_CTRL_SET_READ_AHEAD:
2428         l = ctx->read_ahead;
2429         ctx->read_ahead = larg;
2430         return l;
2431
2432     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2433         ctx->msg_callback_arg = parg;
2434         return 1;
2435
2436     case SSL_CTRL_GET_MAX_CERT_LIST:
2437         return (long)ctx->max_cert_list;
2438     case SSL_CTRL_SET_MAX_CERT_LIST:
2439         if (larg < 0)
2440             return 0;
2441         l = (long)ctx->max_cert_list;
2442         ctx->max_cert_list = (size_t)larg;
2443         return l;
2444
2445     case SSL_CTRL_SET_SESS_CACHE_SIZE:
2446         if (larg < 0)
2447             return 0;
2448         l = (long)ctx->session_cache_size;
2449         ctx->session_cache_size = (size_t)larg;
2450         return l;
2451     case SSL_CTRL_GET_SESS_CACHE_SIZE:
2452         return (long)ctx->session_cache_size;
2453     case SSL_CTRL_SET_SESS_CACHE_MODE:
2454         l = ctx->session_cache_mode;
2455         ctx->session_cache_mode = larg;
2456         return l;
2457     case SSL_CTRL_GET_SESS_CACHE_MODE:
2458         return ctx->session_cache_mode;
2459
2460     case SSL_CTRL_SESS_NUMBER:
2461         return lh_SSL_SESSION_num_items(ctx->sessions);
2462     case SSL_CTRL_SESS_CONNECT:
2463         return tsan_load(&ctx->stats.sess_connect);
2464     case SSL_CTRL_SESS_CONNECT_GOOD:
2465         return tsan_load(&ctx->stats.sess_connect_good);
2466     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
2467         return tsan_load(&ctx->stats.sess_connect_renegotiate);
2468     case SSL_CTRL_SESS_ACCEPT:
2469         return tsan_load(&ctx->stats.sess_accept);
2470     case SSL_CTRL_SESS_ACCEPT_GOOD:
2471         return tsan_load(&ctx->stats.sess_accept_good);
2472     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
2473         return tsan_load(&ctx->stats.sess_accept_renegotiate);
2474     case SSL_CTRL_SESS_HIT:
2475         return tsan_load(&ctx->stats.sess_hit);
2476     case SSL_CTRL_SESS_CB_HIT:
2477         return tsan_load(&ctx->stats.sess_cb_hit);
2478     case SSL_CTRL_SESS_MISSES:
2479         return tsan_load(&ctx->stats.sess_miss);
2480     case SSL_CTRL_SESS_TIMEOUTS:
2481         return tsan_load(&ctx->stats.sess_timeout);
2482     case SSL_CTRL_SESS_CACHE_FULL:
2483         return tsan_load(&ctx->stats.sess_cache_full);
2484     case SSL_CTRL_MODE:
2485         return (ctx->mode |= larg);
2486     case SSL_CTRL_CLEAR_MODE:
2487         return (ctx->mode &= ~larg);
2488     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2489         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2490             return 0;
2491         ctx->max_send_fragment = larg;
2492         if (ctx->max_send_fragment < ctx->split_send_fragment)
2493             ctx->split_send_fragment = ctx->max_send_fragment;
2494         return 1;
2495     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2496         if ((size_t)larg > ctx->max_send_fragment || larg == 0)
2497             return 0;
2498         ctx->split_send_fragment = larg;
2499         return 1;
2500     case SSL_CTRL_SET_MAX_PIPELINES:
2501         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2502             return 0;
2503         ctx->max_pipelines = larg;
2504         return 1;
2505     case SSL_CTRL_CERT_FLAGS:
2506         return (ctx->cert->cert_flags |= larg);
2507     case SSL_CTRL_CLEAR_CERT_FLAGS:
2508         return (ctx->cert->cert_flags &= ~larg);
2509     case SSL_CTRL_SET_MIN_PROTO_VERSION:
2510         return ssl_check_allowed_versions(larg, ctx->max_proto_version)
2511                && ssl_set_version_bound(ctx->method->version, (int)larg,
2512                                         &ctx->min_proto_version);
2513     case SSL_CTRL_GET_MIN_PROTO_VERSION:
2514         return ctx->min_proto_version;
2515     case SSL_CTRL_SET_MAX_PROTO_VERSION:
2516         return ssl_check_allowed_versions(ctx->min_proto_version, larg)
2517                && ssl_set_version_bound(ctx->method->version, (int)larg,
2518                                         &ctx->max_proto_version);
2519     case SSL_CTRL_GET_MAX_PROTO_VERSION:
2520         return ctx->max_proto_version;
2521     default:
2522         return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
2523     }
2524 }
2525
2526 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
2527 {
2528     switch (cmd) {
2529     case SSL_CTRL_SET_MSG_CALLBACK:
2530         ctx->msg_callback = (void (*)
2531                              (int write_p, int version, int content_type,
2532                               const void *buf, size_t len, SSL *ssl,
2533                               void *arg))(fp);
2534         return 1;
2535
2536     default:
2537         return ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp);
2538     }
2539 }
2540
2541 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
2542 {
2543     if (a->id > b->id)
2544         return 1;
2545     if (a->id < b->id)
2546         return -1;
2547     return 0;
2548 }
2549
2550 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
2551                           const SSL_CIPHER *const *bp)
2552 {
2553     if ((*ap)->id > (*bp)->id)
2554         return 1;
2555     if ((*ap)->id < (*bp)->id)
2556         return -1;
2557     return 0;
2558 }
2559
2560 /** return a STACK of the ciphers available for the SSL and in order of
2561  * preference */
2562 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
2563 {
2564     if (s != NULL) {
2565         if (s->cipher_list != NULL) {
2566             return s->cipher_list;
2567         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
2568             return s->ctx->cipher_list;
2569         }
2570     }
2571     return NULL;
2572 }
2573
2574 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
2575 {
2576     if ((s == NULL) || !s->server)
2577         return NULL;
2578     return s->peer_ciphers;
2579 }
2580
2581 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
2582 {
2583     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
2584     int i;
2585
2586     ciphers = SSL_get_ciphers(s);
2587     if (!ciphers)
2588         return NULL;
2589     if (!ssl_set_client_disabled(s))
2590         return NULL;
2591     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2592         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
2593         if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
2594             if (!sk)
2595                 sk = sk_SSL_CIPHER_new_null();
2596             if (!sk)
2597                 return NULL;
2598             if (!sk_SSL_CIPHER_push(sk, c)) {
2599                 sk_SSL_CIPHER_free(sk);
2600                 return NULL;
2601             }
2602         }
2603     }
2604     return sk;
2605 }
2606
2607 /** return a STACK of the ciphers available for the SSL and in order of
2608  * algorithm id */
2609 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
2610 {
2611     if (s != NULL) {
2612         if (s->cipher_list_by_id != NULL) {
2613             return s->cipher_list_by_id;
2614         } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
2615             return s->ctx->cipher_list_by_id;
2616         }
2617     }
2618     return NULL;
2619 }
2620
2621 /** The old interface to get the same thing as SSL_get_ciphers() */
2622 const char *SSL_get_cipher_list(const SSL *s, int n)
2623 {
2624     const SSL_CIPHER *c;
2625     STACK_OF(SSL_CIPHER) *sk;
2626
2627     if (s == NULL)
2628         return NULL;
2629     sk = SSL_get_ciphers(s);
2630     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2631         return NULL;
2632     c = sk_SSL_CIPHER_value(sk, n);
2633     if (c == NULL)
2634         return NULL;
2635     return c->name;
2636 }
2637
2638 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2639  * preference */
2640 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2641 {
2642     if (ctx != NULL)
2643         return ctx->cipher_list;
2644     return NULL;
2645 }
2646
2647 /*
2648  * Distinguish between ciphers controlled by set_ciphersuite() and
2649  * set_cipher_list() when counting.
2650  */
2651 static int cipher_list_tls12_num(STACK_OF(SSL_CIPHER) *sk)
2652 {
2653     int i, num = 0;
2654     const SSL_CIPHER *c;
2655
2656     if (sk == NULL)
2657         return 0;
2658     for (i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
2659         c = sk_SSL_CIPHER_value(sk, i);
2660         if (c->min_tls >= TLS1_3_VERSION)
2661             continue;
2662         num++;
2663     }
2664     return num;
2665 }
2666
2667 /** specify the ciphers to be used by default by the SSL_CTX */
2668 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2669 {
2670     STACK_OF(SSL_CIPHER) *sk;
2671
2672     sk = ssl_create_cipher_list(ctx->method, ctx->tls13_ciphersuites,
2673                                 &ctx->cipher_list, &ctx->cipher_list_by_id, str,
2674                                 ctx->cert);
2675     /*
2676      * ssl_create_cipher_list may return an empty stack if it was unable to
2677      * find a cipher matching the given rule string (for example if the rule
2678      * string specifies a cipher which has been disabled). This is not an
2679      * error as far as ssl_create_cipher_list is concerned, and hence
2680      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2681      */
2682     if (sk == NULL)
2683         return 0;
2684     else if (cipher_list_tls12_num(sk) == 0) {
2685         SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2686         return 0;
2687     }
2688     return 1;
2689 }
2690
2691 /** specify the ciphers to be used by the SSL */
2692 int SSL_set_cipher_list(SSL *s, const char *str)
2693 {
2694     STACK_OF(SSL_CIPHER) *sk;
2695
2696     sk = ssl_create_cipher_list(s->ctx->method, s->tls13_ciphersuites,
2697                                 &s->cipher_list, &s->cipher_list_by_id, str,
2698                                 s->cert);
2699     /* see comment in SSL_CTX_set_cipher_list */
2700     if (sk == NULL)
2701         return 0;
2702     else if (cipher_list_tls12_num(sk) == 0) {
2703         SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2704         return 0;
2705     }
2706     return 1;
2707 }
2708
2709 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size)
2710 {
2711     char *p;
2712     STACK_OF(SSL_CIPHER) *clntsk, *srvrsk;
2713     const SSL_CIPHER *c;
2714     int i;
2715
2716     if (!s->server
2717             || s->peer_ciphers == NULL
2718             || size < 2)
2719         return NULL;
2720
2721     p = buf;
2722     clntsk = s->peer_ciphers;
2723     srvrsk = SSL_get_ciphers(s);
2724     if (clntsk == NULL || srvrsk == NULL)
2725         return NULL;
2726
2727     if (sk_SSL_CIPHER_num(clntsk) == 0 || sk_SSL_CIPHER_num(srvrsk) == 0)
2728         return NULL;
2729
2730     for (i = 0; i < sk_SSL_CIPHER_num(clntsk); i++) {
2731         int n;
2732
2733         c = sk_SSL_CIPHER_value(clntsk, i);
2734         if (sk_SSL_CIPHER_find(srvrsk, c) < 0)
2735             continue;
2736
2737         n = strlen(c->name);
2738         if (n + 1 > size) {
2739             if (p != buf)
2740                 --p;
2741             *p = '\0';
2742             return buf;
2743         }
2744         strcpy(p, c->name);
2745         p += n;
2746         *(p++) = ':';
2747         size -= n + 1;
2748     }
2749     p[-1] = '\0';
2750     return buf;
2751 }
2752
2753 /**
2754  * Return the requested servername (SNI) value. Note that the behaviour varies
2755  * depending on:
2756  * - whether this is called by the client or the server,
2757  * - if we are before or during/after the handshake,
2758  * - if a resumption or normal handshake is being attempted/has occurred
2759  * - whether we have negotiated TLSv1.2 (or below) or TLSv1.3
2760  * 
2761  * Note that only the host_name type is defined (RFC 3546).
2762  */
2763 const char *SSL_get_servername(const SSL *s, const int type)
2764 {
2765     /*
2766      * If we don't know if we are the client or the server yet then we assume
2767      * client.
2768      */
2769     int server = s->handshake_func == NULL ? 0 : s->server;
2770     if (type != TLSEXT_NAMETYPE_host_name)
2771         return NULL;
2772
2773     if (server) {
2774         /**
2775          * Server side
2776          * In TLSv1.3 on the server SNI is not associated with the session
2777          * but in TLSv1.2 or below it is.
2778          *
2779          * Before the handshake:
2780          *  - return NULL
2781          *
2782          * During/after the handshake (TLSv1.2 or below resumption occurred):
2783          * - If a servername was accepted by the server in the original
2784          *   handshake then it will return that servername, or NULL otherwise.
2785          *
2786          * During/after the handshake (TLSv1.2 or below resumption did not occur):
2787          * - The function will return the servername requested by the client in
2788          *   this handshake or NULL if none was requested.
2789          */
2790          if (s->hit && !SSL_IS_TLS13(s))
2791             return s->session->ext.hostname;
2792     } else {
2793         /**
2794          * Client side
2795          *
2796          * Before the handshake:
2797          *  - If a servername has been set via a call to
2798          *    SSL_set_tlsext_host_name() then it will return that servername
2799          *  - If one has not been set, but a TLSv1.2 resumption is being
2800          *    attempted and the session from the original handshake had a
2801          *    servername accepted by the server then it will return that
2802          *    servername
2803          *  - Otherwise it returns NULL
2804          *
2805          * During/after the handshake (TLSv1.2 or below resumption occurred):
2806          * - If the session from the orignal handshake had a servername accepted
2807          *   by the server then it will return that servername.
2808          * - Otherwise it returns the servername set via
2809          *   SSL_set_tlsext_host_name() (or NULL if it was not called).
2810          *
2811          * During/after the handshake (TLSv1.2 or below resumption did not occur):
2812          * - It will return the servername set via SSL_set_tlsext_host_name()
2813          *   (or NULL if it was not called).
2814          */
2815         if (SSL_in_before(s)) {
2816             if (s->ext.hostname == NULL
2817                     && s->session != NULL
2818                     && s->session->ssl_version != TLS1_3_VERSION)
2819                 return s->session->ext.hostname;
2820         } else {
2821             if (!SSL_IS_TLS13(s) && s->hit && s->session->ext.hostname != NULL)
2822                 return s->session->ext.hostname;
2823         }
2824     }
2825
2826     return s->ext.hostname;
2827 }
2828
2829 int SSL_get_servername_type(const SSL *s)
2830 {
2831     if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)
2832         return TLSEXT_NAMETYPE_host_name;
2833     return -1;
2834 }
2835
2836 /*
2837  * SSL_select_next_proto implements the standard protocol selection. It is
2838  * expected that this function is called from the callback set by
2839  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2840  * vector of 8-bit, length prefixed byte strings. The length byte itself is
2841  * not included in the length. A byte string of length 0 is invalid. No byte
2842  * string may be truncated. The current, but experimental algorithm for
2843  * selecting the protocol is: 1) If the server doesn't support NPN then this
2844  * is indicated to the callback. In this case, the client application has to
2845  * abort the connection or have a default application level protocol. 2) If
2846  * the server supports NPN, but advertises an empty list then the client
2847  * selects the first protocol in its list, but indicates via the API that this
2848  * fallback case was enacted. 3) Otherwise, the client finds the first
2849  * protocol in the server's list that it supports and selects this protocol.
2850  * This is because it's assumed that the server has better information about
2851  * which protocol a client should use. 4) If the client doesn't support any
2852  * of the server's advertised protocols, then this is treated the same as
2853  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2854  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2855  */
2856 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2857                           const unsigned char *server,
2858                           unsigned int server_len,
2859                           const unsigned char *client, unsigned int client_len)
2860 {
2861     unsigned int i, j;
2862     const unsigned char *result;
2863     int status = OPENSSL_NPN_UNSUPPORTED;
2864
2865     /*
2866      * For each protocol in server preference order, see if we support it.
2867      */
2868     for (i = 0; i < server_len;) {
2869         for (j = 0; j < client_len;) {
2870             if (server[i] == client[j] &&
2871                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2872                 /* We found a match */
2873                 result = &server[i];
2874                 status = OPENSSL_NPN_NEGOTIATED;
2875                 goto found;
2876             }
2877             j += client[j];
2878             j++;
2879         }
2880         i += server[i];
2881         i++;
2882     }
2883
2884     /* There's no overlap between our protocols and the server's list. */
2885     result = client;
2886     status = OPENSSL_NPN_NO_OVERLAP;
2887
2888  found:
2889     *out = (unsigned char *)result + 1;
2890     *outlen = result[0];
2891     return status;
2892 }
2893
2894 #ifndef OPENSSL_NO_NEXTPROTONEG
2895 /*
2896  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2897  * client's requested protocol for this connection and returns 0. If the
2898  * client didn't request any protocol, then *data is set to NULL. Note that
2899  * the client can request any protocol it chooses. The value returned from
2900  * this function need not be a member of the list of supported protocols
2901  * provided by the callback.
2902  */
2903 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2904                                     unsigned *len)
2905 {
2906     *data = s->ext.npn;
2907     if (*data == NULL) {
2908         *len = 0;
2909     } else {
2910         *len = (unsigned int)s->ext.npn_len;
2911     }
2912 }
2913
2914 /*
2915  * SSL_CTX_set_npn_advertised_cb sets a callback that is called when
2916  * a TLS server needs a list of supported protocols for Next Protocol
2917  * Negotiation. The returned list must be in wire format.  The list is
2918  * returned by setting |out| to point to it and |outlen| to its length. This
2919  * memory will not be modified, but one should assume that the SSL* keeps a
2920  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2921  * wishes to advertise. Otherwise, no such extension will be included in the
2922  * ServerHello.
2923  */
2924 void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
2925                                    SSL_CTX_npn_advertised_cb_func cb,
2926                                    void *arg)
2927 {
2928     ctx->ext.npn_advertised_cb = cb;
2929     ctx->ext.npn_advertised_cb_arg = arg;
2930 }
2931
2932 /*
2933  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2934  * client needs to select a protocol from the server's provided list. |out|
2935  * must be set to point to the selected protocol (which may be within |in|).
2936  * The length of the protocol name must be written into |outlen|. The
2937  * server's advertised protocols are provided in |in| and |inlen|. The
2938  * callback can assume that |in| is syntactically valid. The client must
2939  * select a protocol. It is fatal to the connection if this callback returns
2940  * a value other than SSL_TLSEXT_ERR_OK.
2941  */
2942 void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
2943                                SSL_CTX_npn_select_cb_func cb,
2944                                void *arg)
2945 {
2946     ctx->ext.npn_select_cb = cb;
2947     ctx->ext.npn_select_cb_arg = arg;
2948 }
2949 #endif
2950
2951 /*
2952  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2953  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2954  * length-prefixed strings). Returns 0 on success.
2955  */
2956 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2957                             unsigned int protos_len)
2958 {
2959     OPENSSL_free(ctx->ext.alpn);
2960     ctx->ext.alpn = OPENSSL_memdup(protos, protos_len);
2961     if (ctx->ext.alpn == NULL) {
2962         SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2963         return 1;
2964     }
2965     ctx->ext.alpn_len = protos_len;
2966
2967     return 0;
2968 }
2969
2970 /*
2971  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2972  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2973  * length-prefixed strings). Returns 0 on success.
2974  */
2975 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2976                         unsigned int protos_len)
2977 {
2978     OPENSSL_free(ssl->ext.alpn);
2979     ssl->ext.alpn = OPENSSL_memdup(protos, protos_len);
2980     if (ssl->ext.alpn == NULL) {
2981         SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2982         return 1;
2983     }
2984     ssl->ext.alpn_len = protos_len;
2985
2986     return 0;
2987 }
2988
2989 /*
2990  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2991  * called during ClientHello processing in order to select an ALPN protocol
2992  * from the client's list of offered protocols.
2993  */
2994 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2995                                 SSL_CTX_alpn_select_cb_func cb,
2996                                 void *arg)
2997 {
2998     ctx->ext.alpn_select_cb = cb;
2999     ctx->ext.alpn_select_cb_arg = arg;
3000 }
3001
3002 /*
3003  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
3004  * On return it sets |*data| to point to |*len| bytes of protocol name
3005  * (not including the leading length-prefix byte). If the server didn't
3006  * respond with a negotiated protocol then |*len| will be zero.
3007  */
3008 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
3009                             unsigned int *len)
3010 {
3011     *data = ssl->s3.alpn_selected;
3012     if (*data == NULL)
3013         *len = 0;
3014     else
3015         *len = (unsigned int)ssl->s3.alpn_selected_len;
3016 }
3017
3018 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
3019                                const char *label, size_t llen,
3020                                const unsigned char *context, size_t contextlen,
3021                                int use_context)
3022 {
3023     if (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER)
3024         return -1;
3025
3026     return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
3027                                                        llen, context,
3028                                                        contextlen, use_context);
3029 }
3030
3031 int SSL_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
3032                                      const char *label, size_t llen,
3033                                      const unsigned char *context,
3034                                      size_t contextlen)
3035 {
3036     if (s->version != TLS1_3_VERSION)
3037         return 0;
3038
3039     return tls13_export_keying_material_early(s, out, olen, label, llen,
3040                                               context, contextlen);
3041 }
3042
3043 static unsigned long ssl_session_hash(const SSL_SESSION *a)
3044 {
3045     const unsigned char *session_id = a->session_id;
3046     unsigned long l;
3047     unsigned char tmp_storage[4];
3048
3049     if (a->session_id_length < sizeof(tmp_storage)) {
3050         memset(tmp_storage, 0, sizeof(tmp_storage));
3051         memcpy(tmp_storage, a->session_id, a->session_id_length);
3052         session_id = tmp_storage;
3053     }
3054
3055     l = (unsigned long)
3056         ((unsigned long)session_id[0]) |
3057         ((unsigned long)session_id[1] << 8L) |
3058         ((unsigned long)session_id[2] << 16L) |
3059         ((unsigned long)session_id[3] << 24L);
3060     return l;
3061 }
3062
3063 /*
3064  * NB: If this function (or indeed the hash function which uses a sort of
3065  * coarser function than this one) is changed, ensure
3066  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
3067  * being able to construct an SSL_SESSION that will collide with any existing
3068  * session with a matching session ID.
3069  */
3070 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
3071 {
3072     if (a->ssl_version != b->ssl_version)
3073         return 1;
3074     if (a->session_id_length != b->session_id_length)
3075         return 1;
3076     return memcmp(a->session_id, b->session_id, a->session_id_length);
3077 }
3078
3079 /*
3080  * These wrapper functions should remain rather than redeclaring
3081  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
3082  * variable. The reason is that the functions aren't static, they're exposed
3083  * via ssl.h.
3084  */
3085
3086 SSL_CTX *SSL_CTX_new_with_libctx(OPENSSL_CTX *libctx, const char *propq,
3087                                  const SSL_METHOD *meth)
3088 {
3089     SSL_CTX *ret = NULL;
3090
3091     if (meth == NULL) {
3092         SSLerr(0, SSL_R_NULL_SSL_METHOD_PASSED);
3093         return NULL;
3094     }
3095
3096     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
3097         return NULL;
3098
3099     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
3100         SSLerr(0, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
3101         goto err;
3102     }
3103     ret = OPENSSL_zalloc(sizeof(*ret));
3104     if (ret == NULL)
3105         goto err;
3106
3107     ret->libctx = libctx;
3108     if (propq != NULL) {
3109         ret->propq = OPENSSL_strdup(propq);
3110         if (ret->propq == NULL)
3111             goto err;
3112     }
3113
3114     ret->method = meth;
3115     ret->min_proto_version = 0;
3116     ret->max_proto_version = 0;
3117     ret->mode = SSL_MODE_AUTO_RETRY;
3118     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
3119     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
3120     /* We take the system default. */
3121     ret->session_timeout = meth->get_timeout();
3122     ret->references = 1;
3123     ret->lock = CRYPTO_THREAD_lock_new();
3124     if (ret->lock == NULL) {
3125         SSLerr(0, ERR_R_MALLOC_FAILURE);
3126         OPENSSL_free(ret);
3127         return NULL;
3128     }
3129     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
3130     ret->verify_mode = SSL_VERIFY_NONE;
3131     if ((ret->cert = ssl_cert_new()) == NULL)
3132         goto err;
3133
3134     ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
3135     if (ret->sessions == NULL)
3136         goto err;
3137     ret->cert_store = X509_STORE_new();
3138     if (ret->cert_store == NULL)
3139         goto err;
3140 #ifndef OPENSSL_NO_CT
3141     ret->ctlog_store = CTLOG_STORE_new_with_libctx(libctx, propq);
3142     if (ret->ctlog_store == NULL)
3143         goto err;
3144 #endif
3145
3146     /* initialize cipher/digest methods table */
3147     if (!ssl_load_ciphers(ret))
3148         goto err2;
3149     /* initialise sig algs */
3150     if (!ssl_setup_sig_algs(ret))
3151         goto err2;
3152
3153
3154     if (!ssl_load_groups(ret))
3155         goto err2;
3156
3157     if (!SSL_CTX_set_ciphersuites(ret, OSSL_default_ciphersuites()))
3158         goto err;
3159
3160     if (!ssl_create_cipher_list(ret->method,
3161                                 ret->tls13_ciphersuites,
3162                                 &ret->cipher_list, &ret->cipher_list_by_id,
3163                                 OSSL_default_cipher_list(), ret->cert)
3164         || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
3165         SSLerr(0, SSL_R_LIBRARY_HAS_NO_CIPHERS);
3166         goto err2;
3167     }
3168
3169     ret->param = X509_VERIFY_PARAM_new();
3170     if (ret->param == NULL)
3171         goto err;
3172
3173     /*
3174      * If these aren't available from the provider we'll get NULL returns.
3175      * That's fine but will cause errors later if SSLv3 is negotiated
3176      */
3177     ret->md5 = ssl_evp_md_fetch(libctx, NID_md5, propq);
3178     ret->sha1 = ssl_evp_md_fetch(libctx, NID_sha1, propq);
3179
3180     if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL)
3181         goto err;
3182
3183     if ((ret->client_ca_names = sk_X509_NAME_new_null()) == NULL)
3184         goto err;
3185
3186     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data))
3187         goto err;
3188
3189     if ((ret->ext.secure = OPENSSL_secure_zalloc(sizeof(*ret->ext.secure))) == NULL)
3190         goto err;
3191
3192     /* No compression for DTLS */
3193     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
3194         ret->comp_methods = SSL_COMP_get_compression_methods();
3195
3196     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
3197     ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
3198
3199     /* Setup RFC5077 ticket keys */
3200     if ((RAND_bytes_ex(libctx, ret->ext.tick_key_name,
3201                        sizeof(ret->ext.tick_key_name)) <= 0)
3202         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_hmac_key,
3203                                sizeof(ret->ext.secure->tick_hmac_key)) <= 0)
3204         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_aes_key,
3205                                sizeof(ret->ext.secure->tick_aes_key)) <= 0))
3206         ret->options |= SSL_OP_NO_TICKET;
3207
3208     if (RAND_priv_bytes_ex(libctx, ret->ext.cookie_hmac_key,
3209                            sizeof(ret->ext.cookie_hmac_key)) <= 0)
3210         goto err;
3211
3212 #ifndef OPENSSL_NO_SRP
3213     if (!SSL_CTX_SRP_CTX_init(ret))
3214         goto err;
3215 #endif
3216 #ifndef OPENSSL_NO_ENGINE
3217 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
3218 #  define eng_strx(x)     #x
3219 #  define eng_str(x)      eng_strx(x)
3220     /* Use specific client engine automatically... ignore errors */
3221     {
3222         ENGINE *eng;
3223         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
3224         if (!eng) {
3225             ERR_clear_error();
3226             ENGINE_load_builtin_engines();
3227             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
3228         }
3229         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
3230             ERR_clear_error();
3231     }
3232 # endif
3233 #endif
3234     /*
3235      * Default is to connect to non-RI servers. When RI is more widely
3236      * deployed might change this.
3237      */
3238     ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
3239     /*
3240      * Disable compression by default to prevent CRIME. Applications can
3241      * re-enable compression by configuring
3242      * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
3243      * or by using the SSL_CONF library. Similarly we also enable TLSv1.3
3244      * middlebox compatibility by default. This may be disabled by default in
3245      * a later OpenSSL version.
3246      */
3247     ret->options |= SSL_OP_NO_COMPRESSION | SSL_OP_ENABLE_MIDDLEBOX_COMPAT;
3248
3249     ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
3250
3251     /*
3252      * We cannot usefully set a default max_early_data here (which gets
3253      * propagated in SSL_new(), for the following reason: setting the
3254      * SSL field causes tls_construct_stoc_early_data() to tell the
3255      * client that early data will be accepted when constructing a TLS 1.3
3256      * session ticket, and the client will accordingly send us early data
3257      * when using that ticket (if the client has early data to send).
3258      * However, in order for the early data to actually be consumed by
3259      * the application, the application must also have calls to
3260      * SSL_read_early_data(); otherwise we'll just skip past the early data
3261      * and ignore it.  So, since the application must add calls to
3262      * SSL_read_early_data(), we also require them to add
3263      * calls to SSL_CTX_set_max_early_data() in order to use early data,
3264      * eliminating the bandwidth-wasting early data in the case described
3265      * above.
3266      */
3267     ret->max_early_data = 0;
3268
3269     /*
3270      * Default recv_max_early_data is a fully loaded single record. Could be
3271      * split across multiple records in practice. We set this differently to
3272      * max_early_data so that, in the default case, we do not advertise any
3273      * support for early_data, but if a client were to send us some (e.g.
3274      * because of an old, stale ticket) then we will tolerate it and skip over
3275      * it.
3276      */
3277     ret->recv_max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
3278
3279     /* By default we send two session tickets automatically in TLSv1.3 */
3280     ret->num_tickets = 2;
3281
3282     ssl_ctx_system_config(ret);
3283
3284     return ret;
3285  err:
3286     SSLerr(0, ERR_R_MALLOC_FAILURE);
3287  err2:
3288     SSL_CTX_free(ret);
3289     return NULL;
3290 }
3291
3292 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
3293 {
3294     return SSL_CTX_new_with_libctx(NULL, NULL, meth);
3295 }
3296
3297 int SSL_CTX_up_ref(SSL_CTX *ctx)
3298 {
3299     int i;
3300
3301     if (CRYPTO_UP_REF(&ctx->references, &i, ctx->lock) <= 0)
3302         return 0;
3303
3304     REF_PRINT_COUNT("SSL_CTX", ctx);
3305     REF_ASSERT_ISNT(i < 2);
3306     return ((i > 1) ? 1 : 0);
3307 }
3308
3309 void SSL_CTX_free(SSL_CTX *a)
3310 {
3311     int i;
3312     size_t j;
3313
3314     if (a == NULL)
3315         return;
3316
3317     CRYPTO_DOWN_REF(&a->references, &i, a->lock);
3318     REF_PRINT_COUNT("SSL_CTX", a);
3319     if (i > 0)
3320         return;
3321     REF_ASSERT_ISNT(i < 0);
3322
3323     X509_VERIFY_PARAM_free(a->param);
3324     dane_ctx_final(&a->dane);
3325
3326     /*
3327      * Free internal session cache. However: the remove_cb() may reference
3328      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
3329      * after the sessions were flushed.
3330      * As the ex_data handling routines might also touch the session cache,
3331      * the most secure solution seems to be: empty (flush) the cache, then
3332      * free ex_data, then finally free the cache.
3333      * (See ticket [openssl.org #212].)
3334      */
3335     if (a->sessions != NULL)
3336         SSL_CTX_flush_sessions(a, 0);
3337
3338     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
3339     lh_SSL_SESSION_free(a->sessions);
3340     X509_STORE_free(a->cert_store);
3341 #ifndef OPENSSL_NO_CT
3342     CTLOG_STORE_free(a->ctlog_store);
3343 #endif
3344     sk_SSL_CIPHER_free(a->cipher_list);
3345     sk_SSL_CIPHER_free(a->cipher_list_by_id);
3346     sk_SSL_CIPHER_free(a->tls13_ciphersuites);
3347     ssl_cert_free(a->cert);
3348     sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
3349     sk_X509_NAME_pop_free(a->client_ca_names, X509_NAME_free);
3350     sk_X509_pop_free(a->extra_certs, X509_free);
3351     a->comp_methods = NULL;
3352 #ifndef OPENSSL_NO_SRTP
3353     sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
3354 #endif
3355 #ifndef OPENSSL_NO_SRP
3356     SSL_CTX_SRP_CTX_free(a);
3357 #endif
3358 #ifndef OPENSSL_NO_ENGINE
3359     ENGINE_finish(a->client_cert_engine);
3360 #endif
3361
3362 #ifndef OPENSSL_NO_EC
3363     OPENSSL_free(a->ext.ecpointformats);
3364 #endif
3365     OPENSSL_free(a->ext.supportedgroups);
3366     OPENSSL_free(a->ext.alpn);
3367     OPENSSL_secure_free(a->ext.secure);
3368
3369     ssl_evp_md_free(a->md5);
3370     ssl_evp_md_free(a->sha1);
3371
3372     for (j = 0; j < SSL_ENC_NUM_IDX; j++)
3373         ssl_evp_cipher_free(a->ssl_cipher_methods[j]);
3374     for (j = 0; j < SSL_MD_NUM_IDX; j++)
3375         ssl_evp_md_free(a->ssl_digest_methods[j]);
3376     for (j = 0; j < a->group_list_len; j++) {
3377         OPENSSL_free(a->group_list[j].tlsname);
3378         OPENSSL_free(a->group_list[j].realname);
3379         OPENSSL_free(a->group_list[j].algorithm);
3380     }
3381     OPENSSL_free(a->group_list);
3382
3383     OPENSSL_free(a->sigalg_lookup_cache);
3384
3385     CRYPTO_THREAD_lock_free(a->lock);
3386
3387     OPENSSL_free(a->propq);
3388
3389     OPENSSL_free(a);
3390 }
3391
3392 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
3393 {
3394     ctx->default_passwd_callback = cb;
3395 }
3396
3397 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
3398 {
3399     ctx->default_passwd_callback_userdata = u;
3400 }
3401
3402 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
3403 {
3404     return ctx->default_passwd_callback;
3405 }
3406
3407 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
3408 {
3409     return ctx->default_passwd_callback_userdata;
3410 }
3411
3412 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
3413 {
3414     s->default_passwd_callback = cb;
3415 }
3416
3417 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
3418 {
3419     s->default_passwd_callback_userdata = u;
3420 }
3421
3422 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
3423 {
3424     return s->default_passwd_callback;
3425 }
3426
3427 void *SSL_get_default_passwd_cb_userdata(SSL *s)
3428 {
3429     return s->default_passwd_callback_userdata;
3430 }
3431
3432 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
3433                                       int (*cb) (X509_STORE_CTX *, void *),
3434                                       void *arg)
3435 {
3436     ctx->app_verify_callback = cb;
3437     ctx->app_verify_arg = arg;
3438 }
3439
3440 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
3441                         int (*cb) (int, X509_STORE_CTX *))
3442 {
3443     ctx->verify_mode = mode;
3444     ctx->default_verify_callback = cb;
3445 }
3446
3447 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
3448 {
3449     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
3450 }
3451
3452 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
3453 {
3454     ssl_cert_set_cert_cb(c->cert, cb, arg);
3455 }
3456
3457 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
3458 {
3459     ssl_cert_set_cert_cb(s->cert, cb, arg);
3460 }
3461
3462 void ssl_set_masks(SSL *s)
3463 {
3464     CERT *c = s->cert;
3465     uint32_t *pvalid = s->s3.tmp.valid_flags;
3466     int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
3467     unsigned long mask_k, mask_a;
3468 #ifndef OPENSSL_NO_EC
3469     int have_ecc_cert, ecdsa_ok;
3470 #endif
3471     if (c == NULL)
3472         return;
3473
3474 #ifndef OPENSSL_NO_DH
3475     dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
3476 #else
3477     dh_tmp = 0;
3478 #endif
3479
3480     rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
3481     rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
3482     dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
3483 #ifndef OPENSSL_NO_EC
3484     have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
3485 #endif
3486     mask_k = 0;
3487     mask_a = 0;
3488
3489     OSSL_TRACE4(TLS_CIPHER, "dh_tmp=%d rsa_enc=%d rsa_sign=%d dsa_sign=%d\n",
3490                dh_tmp, rsa_enc, rsa_sign, dsa_sign);
3491
3492 #ifndef OPENSSL_NO_GOST
3493     if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
3494         mask_k |= SSL_kGOST | SSL_kGOST18;
3495         mask_a |= SSL_aGOST12;
3496     }
3497     if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
3498         mask_k |= SSL_kGOST | SSL_kGOST18;
3499         mask_a |= SSL_aGOST12;
3500     }
3501     if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
3502         mask_k |= SSL_kGOST;
3503         mask_a |= SSL_aGOST01;
3504     }
3505 #endif
3506
3507     if (rsa_enc)
3508         mask_k |= SSL_kRSA;
3509
3510     if (dh_tmp)
3511         mask_k |= SSL_kDHE;
3512
3513     /*
3514      * If we only have an RSA-PSS certificate allow RSA authentication
3515      * if TLS 1.2 and peer supports it.
3516      */
3517
3518     if (rsa_enc || rsa_sign || (ssl_has_cert(s, SSL_PKEY_RSA_PSS_SIGN)
3519                 && pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_EXPLICIT_SIGN
3520                 && TLS1_get_version(s) == TLS1_2_VERSION))
3521         mask_a |= SSL_aRSA;
3522
3523     if (dsa_sign) {
3524         mask_a |= SSL_aDSS;
3525     }
3526
3527     mask_a |= SSL_aNULL;
3528
3529     /*
3530      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
3531      * depending on the key usage extension.
3532      */
3533 #ifndef OPENSSL_NO_EC
3534     if (have_ecc_cert) {
3535         uint32_t ex_kusage;
3536         ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
3537         ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
3538         if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
3539             ecdsa_ok = 0;
3540         if (ecdsa_ok)
3541             mask_a |= SSL_aECDSA;
3542     }
3543     /* Allow Ed25519 for TLS 1.2 if peer supports it */
3544     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
3545             && pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
3546             && TLS1_get_version(s) == TLS1_2_VERSION)
3547             mask_a |= SSL_aECDSA;
3548
3549     /* Allow Ed448 for TLS 1.2 if peer supports it */
3550     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED448)
3551             && pvalid[SSL_PKEY_ED448] & CERT_PKEY_EXPLICIT_SIGN
3552             && TLS1_get_version(s) == TLS1_2_VERSION)
3553             mask_a |= SSL_aECDSA;
3554 #endif
3555
3556 #ifndef OPENSSL_NO_EC
3557     mask_k |= SSL_kECDHE;
3558 #endif
3559
3560 #ifndef OPENSSL_NO_PSK
3561     mask_k |= SSL_kPSK;
3562     mask_a |= SSL_aPSK;
3563     if (mask_k & SSL_kRSA)
3564         mask_k |= SSL_kRSAPSK;
3565     if (mask_k & SSL_kDHE)
3566         mask_k |= SSL_kDHEPSK;
3567     if (mask_k & SSL_kECDHE)
3568         mask_k |= SSL_kECDHEPSK;
3569 #endif
3570
3571     s->s3.tmp.mask_k = mask_k;
3572     s->s3.tmp.mask_a = mask_a;
3573 }
3574
3575 #ifndef OPENSSL_NO_EC
3576
3577 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
3578 {
3579     if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
3580         /* key usage, if present, must allow signing */
3581         if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
3582             SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
3583                    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
3584             return 0;
3585         }
3586     }
3587     return 1;                   /* all checks are ok */
3588 }
3589
3590 #endif
3591
3592 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
3593                                    size_t *serverinfo_length)
3594 {
3595     CERT_PKEY *cpk = s->s3.tmp.cert;
3596     *serverinfo_length = 0;
3597
3598     if (cpk == NULL || cpk->serverinfo == NULL)
3599         return 0;
3600
3601     *serverinfo = cpk->serverinfo;
3602     *serverinfo_length = cpk->serverinfo_length;
3603     return 1;
3604 }
3605
3606 void ssl_update_cache(SSL *s, int mode)
3607 {
3608     int i;
3609
3610     /*
3611      * If the session_id_length is 0, we are not supposed to cache it, and it
3612      * would be rather hard to do anyway :-)
3613      */
3614     if (s->session->session_id_length == 0)
3615         return;
3616
3617     /*
3618      * If sid_ctx_length is 0 there is no specific application context
3619      * associated with this session, so when we try to resume it and
3620      * SSL_VERIFY_PEER is requested to verify the client identity, we have no
3621      * indication that this is actually a session for the proper application
3622      * context, and the *handshake* will fail, not just the resumption attempt.
3623      * Do not cache (on the server) these sessions that are not resumable
3624      * (clients can set SSL_VERIFY_PEER without needing a sid_ctx set).
3625      */
3626     if (s->server && s->session->sid_ctx_length == 0
3627             && (s->verify_mode & SSL_VERIFY_PEER) != 0)
3628         return;
3629
3630     i = s->session_ctx->session_cache_mode;
3631     if ((i & mode) != 0
3632         && (!s->hit || SSL_IS_TLS13(s))) {
3633         /*
3634          * Add the session to the internal cache. In server side TLSv1.3 we
3635          * normally don't do this because by default it's a full stateless ticket
3636          * with only a dummy session id so there is no reason to cache it,
3637          * unless:
3638          * - we are doing early_data, in which case we cache so that we can
3639          *   detect replays
3640          * - the application has set a remove_session_cb so needs to know about
3641          *   session timeout events
3642          * - SSL_OP_NO_TICKET is set in which case it is a stateful ticket
3643          */
3644         if ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0
3645                 && (!SSL_IS_TLS13(s)
3646                     || !s->server
3647                     || (s->max_early_data > 0
3648                         && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0)
3649                     || s->session_ctx->remove_session_cb != NULL
3650                     || (s->options & SSL_OP_NO_TICKET) != 0))
3651             SSL_CTX_add_session(s->session_ctx, s->session);
3652
3653         /*
3654          * Add the session to the external cache. We do this even in server side
3655          * TLSv1.3 without early data because some applications just want to
3656          * know about the creation of a session and aren't doing a full cache.
3657          */
3658         if (s->session_ctx->new_session_cb != NULL) {
3659             SSL_SESSION_up_ref(s->session);
3660             if (!s->session_ctx->new_session_cb(s, s->session))
3661                 SSL_SESSION_free(s->session);
3662         }
3663     }
3664
3665     /* auto flush every 255 connections */
3666     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
3667         TSAN_QUALIFIER int *stat;
3668         if (mode & SSL_SESS_CACHE_CLIENT)
3669             stat = &s->session_ctx->stats.sess_connect_good;
3670         else
3671             stat = &s->session_ctx->stats.sess_accept_good;
3672         if ((tsan_load(stat) & 0xff) == 0xff)
3673             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
3674     }
3675 }
3676
3677 const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx)
3678 {
3679     return ctx->method;
3680 }
3681
3682 const SSL_METHOD *SSL_get_ssl_method(const SSL *s)
3683 {
3684     return s->method;
3685 }
3686
3687 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
3688 {
3689     int ret = 1;
3690
3691     if (s->method != meth) {
3692         const SSL_METHOD *sm = s->method;
3693         int (*hf) (SSL *) = s->handshake_func;
3694
3695         if (sm->version == meth->version)
3696             s->method = meth;
3697         else {
3698             sm->ssl_free(s);
3699             s->method = meth;
3700             ret = s->method->ssl_new(s);
3701         }
3702
3703         if (hf == sm->ssl_connect)
3704             s->handshake_func = meth->ssl_connect;
3705         else if (hf == sm->ssl_accept)
3706             s->handshake_func = meth->ssl_accept;
3707     }
3708     return ret;
3709 }
3710
3711 int SSL_get_error(const SSL *s, int i)
3712 {
3713     int reason;
3714     unsigned long l;
3715     BIO *bio;
3716
3717     if (i > 0)
3718         return SSL_ERROR_NONE;
3719
3720     /*
3721      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
3722      * where we do encode the error
3723      */
3724     if ((l = ERR_peek_error()) != 0) {
3725         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
3726             return SSL_ERROR_SYSCALL;
3727         else
3728             return SSL_ERROR_SSL;
3729     }
3730
3731     if (SSL_want_read(s)) {
3732         bio = SSL_get_rbio(s);
3733         if (BIO_should_read(bio))
3734             return SSL_ERROR_WANT_READ;
3735         else if (BIO_should_write(bio))
3736             /*
3737              * This one doesn't make too much sense ... We never try to write
3738              * to the rbio, and an application program where rbio and wbio
3739              * are separate couldn't even know what it should wait for.
3740              * However if we ever set s->rwstate incorrectly (so that we have
3741              * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
3742              * wbio *are* the same, this test works around that bug; so it
3743              * might be safer to keep it.
3744              */
3745             return SSL_ERROR_WANT_WRITE;
3746         else if (BIO_should_io_special(bio)) {
3747             reason = BIO_get_retry_reason(bio);
3748             if (reason == BIO_RR_CONNECT)
3749                 return SSL_ERROR_WANT_CONNECT;
3750             else if (reason == BIO_RR_ACCEPT)
3751                 return SSL_ERROR_WANT_ACCEPT;
3752             else
3753                 return SSL_ERROR_SYSCALL; /* unknown */
3754         }
3755     }
3756
3757     if (SSL_want_write(s)) {
3758         /* Access wbio directly - in order to use the buffered bio if present */
3759         bio = s->wbio;
3760         if (BIO_should_write(bio))
3761             return SSL_ERROR_WANT_WRITE;
3762         else if (BIO_should_read(bio))
3763             /*
3764              * See above (SSL_want_read(s) with BIO_should_write(bio))
3765              */
3766             return SSL_ERROR_WANT_READ;
3767         else if (BIO_should_io_special(bio)) {
3768             reason = BIO_get_retry_reason(bio);
3769             if (reason == BIO_RR_CONNECT)
3770                 return SSL_ERROR_WANT_CONNECT;
3771             else if (reason == BIO_RR_ACCEPT)
3772                 return SSL_ERROR_WANT_ACCEPT;
3773             else
3774                 return SSL_ERROR_SYSCALL;
3775         }
3776     }
3777     if (SSL_want_x509_lookup(s))
3778         return SSL_ERROR_WANT_X509_LOOKUP;
3779     if (SSL_want_async(s))
3780         return SSL_ERROR_WANT_ASYNC;
3781     if (SSL_want_async_job(s))
3782         return SSL_ERROR_WANT_ASYNC_JOB;
3783     if (SSL_want_client_hello_cb(s))
3784         return SSL_ERROR_WANT_CLIENT_HELLO_CB;
3785
3786     if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
3787         (s->s3.warn_alert == SSL_AD_CLOSE_NOTIFY))
3788         return SSL_ERROR_ZERO_RETURN;
3789
3790     return SSL_ERROR_SYSCALL;
3791 }
3792
3793 static int ssl_do_handshake_intern(void *vargs)
3794 {
3795     struct ssl_async_args *args;
3796     SSL *s;
3797
3798     args = (struct ssl_async_args *)vargs;
3799     s = args->s;
3800
3801     return s->handshake_func(s);
3802 }
3803
3804 int SSL_do_handshake(SSL *s)
3805 {
3806     int ret = 1;
3807
3808     if (s->handshake_func == NULL) {
3809         SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3810         return -1;
3811     }
3812
3813     ossl_statem_check_finish_init(s, -1);
3814
3815     s->method->ssl_renegotiate_check(s, 0);
3816
3817     if (SSL_in_init(s) || SSL_in_before(s)) {
3818         if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3819             struct ssl_async_args args;
3820
3821             args.s = s;
3822
3823             ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3824         } else {
3825             ret = s->handshake_func(s);
3826         }
3827     }
3828     return ret;
3829 }
3830
3831 void SSL_set_accept_state(SSL *s)
3832 {
3833     s->server = 1;
3834     s->shutdown = 0;
3835     ossl_statem_clear(s);
3836     s->handshake_func = s->method->ssl_accept;
3837     clear_ciphers(s);
3838 }
3839
3840 void SSL_set_connect_state(SSL *s)
3841 {
3842     s->server = 0;
3843     s->shutdown = 0;
3844     ossl_statem_clear(s);
3845     s->handshake_func = s->method->ssl_connect;
3846     clear_ciphers(s);
3847 }
3848
3849 int ssl_undefined_function(SSL *s)
3850 {
3851     SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3852     return 0;
3853 }
3854
3855 int ssl_undefined_void_function(void)
3856 {
3857     SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3858            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3859     return 0;
3860 }
3861
3862 int ssl_undefined_const_function(const SSL *s)
3863 {
3864     return 0;
3865 }
3866
3867 const SSL_METHOD *ssl_bad_method(int ver)
3868 {
3869     SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3870     return NULL;
3871 }
3872
3873 const char *ssl_protocol_to_string(int version)
3874 {
3875     switch(version)
3876     {
3877     case TLS1_3_VERSION:
3878         return "TLSv1.3";
3879
3880     case TLS1_2_VERSION:
3881         return "TLSv1.2";
3882
3883     case TLS1_1_VERSION:
3884         return "TLSv1.1";
3885
3886     case TLS1_VERSION:
3887         return "TLSv1";
3888
3889     case SSL3_VERSION:
3890         return "SSLv3";
3891
3892     case DTLS1_BAD_VER:
3893         return "DTLSv0.9";
3894
3895     case DTLS1_VERSION:
3896         return "DTLSv1";
3897
3898     case DTLS1_2_VERSION:
3899         return "DTLSv1.2";
3900
3901     default:
3902         return "unknown";
3903     }
3904 }
3905
3906 const char *SSL_get_version(const SSL *s)
3907 {
3908     return ssl_protocol_to_string(s->version);
3909 }
3910
3911 static int dup_ca_names(STACK_OF(X509_NAME) **dst, STACK_OF(X509_NAME) *src)
3912 {
3913     STACK_OF(X509_NAME) *sk;
3914     X509_NAME *xn;
3915     int i;
3916
3917     if (src == NULL) {
3918         *dst = NULL;
3919         return 1;
3920     }
3921
3922     if ((sk = sk_X509_NAME_new_null()) == NULL)
3923         return 0;
3924     for (i = 0; i < sk_X509_NAME_num(src); i++) {
3925         xn = X509_NAME_dup(sk_X509_NAME_value(src, i));
3926         if (xn == NULL) {
3927             sk_X509_NAME_pop_free(sk, X509_NAME_free);
3928             return 0;
3929         }
3930         if (sk_X509_NAME_insert(sk, xn, i) == 0) {
3931             X509_NAME_free(xn);
3932             sk_X509_NAME_pop_free(sk, X509_NAME_free);
3933             return 0;
3934         }
3935     }
3936     *dst = sk;
3937
3938     return 1;
3939 }
3940
3941 SSL *SSL_dup(SSL *s)
3942 {
3943     SSL *ret;
3944     int i;
3945
3946     /* If we're not quiescent, just up_ref! */
3947     if (!SSL_in_init(s) || !SSL_in_before(s)) {
3948         CRYPTO_UP_REF(&s->references, &i, s->lock);
3949         return s;
3950     }
3951
3952     /*
3953      * Otherwise, copy configuration state, and session if set.
3954      */
3955     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3956         return NULL;
3957
3958     if (s->session != NULL) {
3959         /*
3960          * Arranges to share the same session via up_ref.  This "copies"
3961          * session-id, SSL_METHOD, sid_ctx, and 'cert'
3962          */
3963         if (!SSL_copy_session_id(ret, s))
3964             goto err;
3965     } else {
3966         /*
3967          * No session has been established yet, so we have to expect that
3968          * s->cert or ret->cert will be changed later -- they should not both
3969          * point to the same object, and thus we can't use
3970          * SSL_copy_session_id.
3971          */
3972         if (!SSL_set_ssl_method(ret, s->method))
3973             goto err;
3974
3975         if (s->cert != NULL) {
3976             ssl_cert_free(ret->cert);
3977             ret->cert = ssl_cert_dup(s->cert);
3978             if (ret->cert == NULL)
3979                 goto err;
3980         }
3981
3982         if (!SSL_set_session_id_context(ret, s->sid_ctx,
3983                                         (int)s->sid_ctx_length))
3984             goto err;
3985     }
3986
3987     if (!ssl_dane_dup(ret, s))
3988         goto err;
3989     ret->version = s->version;
3990     ret->options = s->options;
3991     ret->min_proto_version = s->min_proto_version;
3992     ret->max_proto_version = s->max_proto_version;
3993     ret->mode = s->mode;
3994     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3995     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3996     ret->msg_callback = s->msg_callback;
3997     ret->msg_callback_arg = s->msg_callback_arg;
3998     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3999     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
4000     ret->generate_session_id = s->generate_session_id;
4001
4002     SSL_set_info_callback(ret, SSL_get_info_callback(s));
4003
4004     /* copy app data, a little dangerous perhaps */
4005     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
4006         goto err;
4007
4008     ret->server = s->server;
4009     if (s->handshake_func) {
4010         if (s->server)
4011             SSL_set_accept_state(ret);
4012         else
4013             SSL_set_connect_state(ret);
4014     }
4015     ret->shutdown = s->shutdown;
4016     ret->hit = s->hit;
4017
4018     ret->default_passwd_callback = s->default_passwd_callback;
4019     ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
4020
4021     X509_VERIFY_PARAM_inherit(ret->param, s->param);
4022
4023     /* dup the cipher_list and cipher_list_by_id stacks */
4024     if (s->cipher_list != NULL) {
4025         if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
4026             goto err;
4027     }
4028     if (s->cipher_list_by_id != NULL)
4029         if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
4030             == NULL)
4031             goto err;
4032
4033     /* Dup the client_CA list */
4034     if (!dup_ca_names(&ret->ca_names, s->ca_names)
4035             || !dup_ca_names(&ret->client_ca_names, s->client_ca_names))
4036         goto err;
4037
4038     return ret;
4039
4040  err:
4041     SSL_free(ret);
4042     return NULL;
4043 }
4044
4045 void ssl_clear_cipher_ctx(SSL *s)
4046 {
4047     if (s->enc_read_ctx != NULL) {
4048         EVP_CIPHER_CTX_free(s->enc_read_ctx);
4049         s->enc_read_ctx = NULL;
4050     }
4051     if (s->enc_write_ctx != NULL) {
4052         EVP_CIPHER_CTX_free(s->enc_write_ctx);
4053         s->enc_write_ctx = NULL;
4054     }
4055 #ifndef OPENSSL_NO_COMP
4056     COMP_CTX_free(s->expand);
4057     s->expand = NULL;
4058     COMP_CTX_free(s->compress);
4059     s->compress = NULL;
4060 #endif
4061 }
4062
4063 X509 *SSL_get_certificate(const SSL *s)
4064 {
4065     if (s->cert != NULL)
4066         return s->cert->key->x509;
4067     else
4068         return NULL;
4069 }
4070
4071 EVP_PKEY *SSL_get_privatekey(const SSL *s)
4072 {
4073     if (s->cert != NULL)
4074         return s->cert->key->privatekey;
4075     else
4076         return NULL;
4077 }
4078
4079 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
4080 {
4081     if (ctx->cert != NULL)
4082         return ctx->cert->key->x509;
4083     else
4084         return NULL;
4085 }
4086
4087 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
4088 {
4089     if (ctx->cert != NULL)
4090         return ctx->cert->key->privatekey;
4091     else
4092         return NULL;
4093 }
4094
4095 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
4096 {
4097     if ((s->session != NULL) && (s->session->cipher != NULL))
4098         return s->session->cipher;
4099     return NULL;
4100 }
4101
4102 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s)
4103 {
4104     return s->s3.tmp.new_cipher;
4105 }
4106
4107 const COMP_METHOD *SSL_get_current_compression(const SSL *s)
4108 {
4109 #ifndef OPENSSL_NO_COMP
4110     return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
4111 #else
4112     return NULL;
4113 #endif
4114 }
4115
4116 const COMP_METHOD *SSL_get_current_expansion(const SSL *s)
4117 {
4118 #ifndef OPENSSL_NO_COMP
4119     return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
4120 #else
4121     return NULL;
4122 #endif
4123 }
4124
4125 int ssl_init_wbio_buffer(SSL *s)
4126 {
4127     BIO *bbio;
4128
4129     if (s->bbio != NULL) {
4130         /* Already buffered. */
4131         return 1;
4132     }
4133
4134     bbio = BIO_new(BIO_f_buffer());
4135     if (bbio == NULL || !BIO_set_read_buffer_size(bbio, 1)) {
4136         BIO_free(bbio);
4137         SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
4138         return 0;
4139     }
4140     s->bbio = bbio;
4141     s->wbio = BIO_push(bbio, s->wbio);
4142
4143     return 1;
4144 }
4145
4146 int ssl_free_wbio_buffer(SSL *s)
4147 {
4148     /* callers ensure s is never null */
4149     if (s->bbio == NULL)
4150         return 1;
4151
4152     s->wbio = BIO_pop(s->wbio);
4153     BIO_free(s->bbio);
4154     s->bbio = NULL;
4155
4156     return 1;
4157 }
4158
4159 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
4160 {
4161     ctx->quiet_shutdown = mode;
4162 }
4163
4164 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
4165 {
4166     return ctx->quiet_shutdown;
4167 }
4168
4169 void SSL_set_quiet_shutdown(SSL *s, int mode)
4170 {
4171     s->quiet_shutdown = mode;
4172 }
4173
4174 int SSL_get_quiet_shutdown(const SSL *s)
4175 {
4176     return s->quiet_shutdown;
4177 }
4178
4179 void SSL_set_shutdown(SSL *s, int mode)
4180 {
4181     s->shutdown = mode;
4182 }
4183
4184 int SSL_get_shutdown(const SSL *s)
4185 {
4186     return s->shutdown;
4187 }
4188
4189 int SSL_version(const SSL *s)
4190 {
4191     return s->version;
4192 }
4193
4194 int SSL_client_version(const SSL *s)
4195 {
4196     return s->client_version;
4197 }
4198
4199 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
4200 {
4201     return ssl->ctx;
4202 }
4203
4204 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
4205 {
4206     CERT *new_cert;
4207     if (ssl->ctx == ctx)
4208         return ssl->ctx;
4209     if (ctx == NULL)
4210         ctx = ssl->session_ctx;
4211     new_cert = ssl_cert_dup(ctx->cert);
4212     if (new_cert == NULL) {
4213         return NULL;
4214     }
4215
4216     if (!custom_exts_copy_flags(&new_cert->custext, &ssl->cert->custext)) {
4217         ssl_cert_free(new_cert);
4218         return NULL;
4219     }
4220
4221     ssl_cert_free(ssl->cert);
4222     ssl->cert = new_cert;
4223
4224     /*
4225      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
4226      * so setter APIs must prevent invalid lengths from entering the system.
4227      */
4228     if (!ossl_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx)))
4229         return NULL;
4230
4231     /*
4232      * If the session ID context matches that of the parent SSL_CTX,
4233      * inherit it from the new SSL_CTX as well. If however the context does
4234      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
4235      * leave it unchanged.
4236      */
4237     if ((ssl->ctx != NULL) &&
4238         (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
4239         (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
4240         ssl->sid_ctx_length = ctx->sid_ctx_length;
4241         memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
4242     }
4243
4244     SSL_CTX_up_ref(ctx);
4245     SSL_CTX_free(ssl->ctx);     /* decrement reference count */
4246     ssl->ctx = ctx;
4247
4248     return ssl->ctx;
4249 }
4250
4251 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
4252 {
4253     return X509_STORE_set_default_paths(ctx->cert_store);
4254 }
4255
4256 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
4257 {
4258     X509_LOOKUP *lookup;
4259
4260     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
4261     if (lookup == NULL)
4262         return 0;
4263
4264     /* We ignore errors, in case the directory doesn't exist */
4265     ERR_set_mark();
4266
4267     X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
4268
4269     ERR_pop_to_mark();
4270
4271     return 1;
4272 }
4273
4274 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
4275 {
4276     X509_LOOKUP *lookup;
4277
4278     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
4279     if (lookup == NULL)
4280         return 0;
4281
4282     /* We ignore errors, in case the directory doesn't exist */
4283     ERR_set_mark();
4284
4285     X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
4286
4287     ERR_pop_to_mark();
4288
4289     return 1;
4290 }
4291
4292 int SSL_CTX_set_default_verify_store(SSL_CTX *ctx)
4293 {
4294     X509_LOOKUP *lookup;
4295
4296     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_store());
4297     if (lookup == NULL)
4298         return 0;
4299
4300     /* We ignore errors, in case the directory doesn't exist */
4301     ERR_set_mark();
4302
4303     X509_LOOKUP_add_store(lookup, NULL);
4304
4305     ERR_pop_to_mark();
4306
4307     return 1;
4308 }
4309
4310 int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile)
4311 {
4312     return X509_STORE_load_file(ctx->cert_store, CAfile);
4313 }
4314
4315 int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath)
4316 {
4317     return X509_STORE_load_path(ctx->cert_store, CApath);
4318 }
4319
4320 int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore)
4321 {
4322     return X509_STORE_load_store(ctx->cert_store, CAstore);
4323 }
4324
4325 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
4326                                   const char *CApath)
4327 {
4328     if (CAfile == NULL && CApath == NULL)
4329         return 0;
4330     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
4331         return 0;
4332     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
4333         return 0;
4334     return 1;
4335 }
4336
4337 void SSL_set_info_callback(SSL *ssl,
4338                            void (*cb) (const SSL *ssl, int type, int val))
4339 {
4340     ssl->info_callback = cb;
4341 }
4342
4343 /*
4344  * One compiler (Diab DCC) doesn't like argument names in returned function
4345  * pointer.
4346  */
4347 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
4348                                                int /* type */ ,
4349                                                int /* val */ ) {
4350     return ssl->info_callback;
4351 }
4352
4353 void SSL_set_verify_result(SSL *ssl, long arg)
4354 {
4355     ssl->verify_result = arg;
4356 }
4357
4358 long SSL_get_verify_result(const SSL *ssl)
4359 {
4360     return ssl->verify_result;
4361 }
4362
4363 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
4364 {
4365     if (outlen == 0)
4366         return sizeof(ssl->s3.client_random);
4367     if (outlen > sizeof(ssl->s3.client_random))
4368         outlen = sizeof(ssl->s3.client_random);
4369     memcpy(out, ssl->s3.client_random, outlen);
4370     return outlen;
4371 }
4372
4373 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
4374 {
4375     if (outlen == 0)
4376         return sizeof(ssl->s3.server_random);
4377     if (outlen > sizeof(ssl->s3.server_random))
4378         outlen = sizeof(ssl->s3.server_random);
4379     memcpy(out, ssl->s3.server_random, outlen);
4380     return outlen;
4381 }
4382
4383 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
4384                                   unsigned char *out, size_t outlen)
4385 {
4386     if (outlen == 0)
4387         return session->master_key_length;
4388     if (outlen > session->master_key_length)
4389         outlen = session->master_key_length;
4390     memcpy(out, session->master_key, outlen);
4391     return outlen;
4392 }
4393
4394 int SSL_SESSION_set1_master_key(SSL_SESSION *sess, const unsigned char *in,
4395                                 size_t len)
4396 {
4397     if (len > sizeof(sess->master_key))
4398         return 0;
4399
4400     memcpy(sess->master_key, in, len);
4401     sess->master_key_length = len;
4402     return 1;
4403 }
4404
4405
4406 int SSL_set_ex_data(SSL *s, int idx, void *arg)
4407 {
4408     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
4409 }
4410
4411 void *SSL_get_ex_data(const SSL *s, int idx)
4412 {
4413     return CRYPTO_get_ex_data(&s->ex_data, idx);
4414 }
4415
4416 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
4417 {
4418     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
4419 }
4420
4421 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
4422 {
4423     return CRYPTO_get_ex_data(&s->ex_data, idx);
4424 }
4425
4426 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
4427 {
4428     return ctx->cert_store;
4429 }
4430
4431 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
4432 {
4433     X509_STORE_free(ctx->cert_store);
4434     ctx->cert_store = store;
4435 }
4436
4437 void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
4438 {
4439     if (store != NULL)
4440         X509_STORE_up_ref(store);
4441     SSL_CTX_set_cert_store(ctx, store);
4442 }
4443
4444 int SSL_want(const SSL *s)
4445 {
4446     return s->rwstate;
4447 }
4448
4449 /**
4450  * \brief Set the callback for generating temporary DH keys.
4451  * \param ctx the SSL context.
4452  * \param dh the callback
4453  */
4454
4455 #ifndef OPENSSL_NO_DH
4456 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
4457                                  DH *(*dh) (SSL *ssl, int is_export,
4458                                             int keylength))
4459 {
4460     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
4461 }
4462
4463 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
4464                                                   int keylength))
4465 {
4466     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
4467 }
4468 #endif
4469
4470 #ifndef OPENSSL_NO_PSK
4471 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
4472 {
4473     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
4474         SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
4475         return 0;
4476     }
4477     OPENSSL_free(ctx->cert->psk_identity_hint);
4478     if (identity_hint != NULL) {
4479         ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
4480         if (ctx->cert->psk_identity_hint == NULL)
4481             return 0;
4482     } else
4483         ctx->cert->psk_identity_hint = NULL;
4484     return 1;
4485 }
4486
4487 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
4488 {
4489     if (s == NULL)
4490         return 0;
4491
4492     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
4493         SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
4494         return 0;
4495     }
4496     OPENSSL_free(s->cert->psk_identity_hint);
4497     if (identity_hint != NULL) {
4498         s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
4499         if (s->cert->psk_identity_hint == NULL)
4500             return 0;
4501     } else
4502         s->cert->psk_identity_hint = NULL;
4503     return 1;
4504 }
4505
4506 const char *SSL_get_psk_identity_hint(const SSL *s)
4507 {
4508     if (s == NULL || s->session == NULL)
4509         return NULL;
4510     return s->session->psk_identity_hint;
4511 }
4512
4513 const char *SSL_get_psk_identity(const SSL *s)
4514 {
4515     if (s == NULL || s->session == NULL)
4516         return NULL;
4517     return s->session->psk_identity;
4518 }
4519
4520 void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
4521 {
4522     s->psk_client_callback = cb;
4523 }
4524
4525 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
4526 {
4527     ctx->psk_client_callback = cb;
4528 }
4529
4530 void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
4531 {
4532     s->psk_server_callback = cb;
4533 }
4534
4535 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
4536 {
4537     ctx->psk_server_callback = cb;
4538 }
4539 #endif
4540
4541 void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb)
4542 {
4543     s->psk_find_session_cb = cb;
4544 }
4545
4546 void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
4547                                            SSL_psk_find_session_cb_func cb)
4548 {
4549     ctx->psk_find_session_cb = cb;
4550 }
4551
4552 void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
4553 {
4554     s->psk_use_session_cb = cb;
4555 }
4556
4557 void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
4558                                            SSL_psk_use_session_cb_func cb)
4559 {
4560     ctx->psk_use_session_cb = cb;
4561 }
4562
4563 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
4564                               void (*cb) (int write_p, int version,
4565                                           int content_type, const void *buf,
4566                                           size_t len, SSL *ssl, void *arg))
4567 {
4568     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
4569 }
4570
4571 void SSL_set_msg_callback(SSL *ssl,
4572                           void (*cb) (int write_p, int version,
4573                                       int content_type, const void *buf,
4574                                       size_t len, SSL *ssl, void *arg))
4575 {
4576     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
4577 }
4578
4579 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
4580                                                 int (*cb) (SSL *ssl,
4581                                                            int
4582                                                            is_forward_secure))
4583 {
4584     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
4585                           (void (*)(void))cb);
4586 }
4587
4588 void SSL_set_not_resumable_session_callback(SSL *ssl,
4589                                             int (*cb) (SSL *ssl,
4590                                                        int is_forward_secure))
4591 {
4592     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
4593                       (void (*)(void))cb);
4594 }
4595
4596 void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
4597                                          size_t (*cb) (SSL *ssl, int type,
4598                                                        size_t len, void *arg))
4599 {
4600     ctx->record_padding_cb = cb;
4601 }
4602
4603 void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
4604 {
4605     ctx->record_padding_arg = arg;
4606 }
4607
4608 void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx)
4609 {
4610     return ctx->record_padding_arg;
4611 }
4612
4613 int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
4614 {
4615     /* block size of 0 or 1 is basically no padding */
4616     if (block_size == 1)
4617         ctx->block_padding = 0;
4618     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
4619         ctx->block_padding = block_size;
4620     else
4621         return 0;
4622     return 1;
4623 }
4624
4625 int SSL_set_record_padding_callback(SSL *ssl,
4626                                      size_t (*cb) (SSL *ssl, int type,
4627                                                    size_t len, void *arg))
4628 {
4629     BIO *b;
4630
4631     b = SSL_get_wbio(ssl);
4632     if (b == NULL || !BIO_get_ktls_send(b)) {
4633         ssl->record_padding_cb = cb;
4634         return 1;
4635     }
4636     return 0;
4637 }
4638
4639 void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
4640 {
4641     ssl->record_padding_arg = arg;
4642 }
4643
4644 void *SSL_get_record_padding_callback_arg(const SSL *ssl)
4645 {
4646     return ssl->record_padding_arg;
4647 }
4648
4649 int SSL_set_block_padding(SSL *ssl, size_t block_size)
4650 {
4651     /* block size of 0 or 1 is basically no padding */
4652     if (block_size == 1)
4653         ssl->block_padding = 0;
4654     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
4655         ssl->block_padding = block_size;
4656     else
4657         return 0;
4658     return 1;
4659 }
4660
4661 int SSL_set_num_tickets(SSL *s, size_t num_tickets)
4662 {
4663     s->num_tickets = num_tickets;
4664
4665     return 1;
4666 }
4667
4668 size_t SSL_get_num_tickets(const SSL *s)
4669 {
4670     return s->num_tickets;
4671 }
4672
4673 int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets)
4674 {
4675     ctx->num_tickets = num_tickets;
4676
4677     return 1;
4678 }
4679
4680 size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx)
4681 {
4682     return ctx->num_tickets;
4683 }
4684
4685 /*
4686  * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
4687  * variable, freeing EVP_MD_CTX previously stored in that variable, if any.
4688  * If EVP_MD pointer is passed, initializes ctx with this |md|.
4689  * Returns the newly allocated ctx;
4690  */
4691
4692 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
4693 {
4694     ssl_clear_hash_ctx(hash);
4695     *hash = EVP_MD_CTX_new();
4696     if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
4697         EVP_MD_CTX_free(*hash);
4698         *hash = NULL;
4699         return NULL;
4700     }
4701     return *hash;
4702 }
4703
4704 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
4705 {
4706
4707     EVP_MD_CTX_free(*hash);
4708     *hash = NULL;
4709 }
4710
4711 /* Retrieve handshake hashes */
4712 int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
4713                        size_t *hashlen)
4714 {
4715     EVP_MD_CTX *ctx = NULL;
4716     EVP_MD_CTX *hdgst = s->s3.handshake_dgst;
4717     int hashleni = EVP_MD_CTX_size(hdgst);
4718     int ret = 0;
4719
4720     if (hashleni < 0 || (size_t)hashleni > outlen) {
4721         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_HANDSHAKE_HASH,
4722                  ERR_R_INTERNAL_ERROR);
4723         goto err;
4724     }
4725
4726     ctx = EVP_MD_CTX_new();
4727     if (ctx == NULL)
4728         goto err;
4729
4730     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
4731         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0) {
4732         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_HANDSHAKE_HASH,
4733                  ERR_R_INTERNAL_ERROR);
4734         goto err;
4735     }
4736
4737     *hashlen = hashleni;
4738
4739     ret = 1;
4740  err:
4741     EVP_MD_CTX_free(ctx);
4742     return ret;
4743 }
4744
4745 int SSL_session_reused(const SSL *s)
4746 {
4747     return s->hit;
4748 }
4749
4750 int SSL_is_server(const SSL *s)
4751 {
4752     return s->server;
4753 }
4754
4755 #ifndef OPENSSL_NO_DEPRECATED_1_1_0
4756 void SSL_set_debug(SSL *s, int debug)
4757 {
4758     /* Old function was do-nothing anyway... */
4759     (void)s;
4760     (void)debug;
4761 }
4762 #endif
4763
4764 void SSL_set_security_level(SSL *s, int level)
4765 {
4766     s->cert->sec_level = level;
4767 }
4768
4769 int SSL_get_security_level(const SSL *s)
4770 {
4771     return s->cert->sec_level;
4772 }
4773
4774 void SSL_set_security_callback(SSL *s,
4775                                int (*cb) (const SSL *s, const SSL_CTX *ctx,
4776                                           int op, int bits, int nid,
4777                                           void *other, void *ex))
4778 {
4779     s->cert->sec_cb = cb;
4780 }
4781
4782 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
4783                                                 const SSL_CTX *ctx, int op,
4784                                                 int bits, int nid, void *other,
4785                                                 void *ex) {
4786     return s->cert->sec_cb;
4787 }
4788
4789 void SSL_set0_security_ex_data(SSL *s, void *ex)
4790 {
4791     s->cert->sec_ex = ex;
4792 }
4793
4794 void *SSL_get0_security_ex_data(const SSL *s)
4795 {
4796     return s->cert->sec_ex;
4797 }
4798
4799 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
4800 {
4801     ctx->cert->sec_level = level;
4802 }
4803
4804 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
4805 {
4806     return ctx->cert->sec_level;
4807 }
4808
4809 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
4810                                    int (*cb) (const SSL *s, const SSL_CTX *ctx,
4811                                               int op, int bits, int nid,
4812                                               void *other, void *ex))
4813 {
4814     ctx->cert->sec_cb = cb;
4815 }
4816
4817 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
4818                                                           const SSL_CTX *ctx,
4819                                                           int op, int bits,
4820                                                           int nid,
4821                                                           void *other,
4822                                                           void *ex) {
4823     return ctx->cert->sec_cb;
4824 }
4825
4826 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
4827 {
4828     ctx->cert->sec_ex = ex;
4829 }
4830
4831 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
4832 {
4833     return ctx->cert->sec_ex;
4834 }
4835
4836 /*
4837  * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
4838  * can return unsigned long, instead of the generic long return value from the
4839  * control interface.
4840  */
4841 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
4842 {
4843     return ctx->options;
4844 }
4845
4846 unsigned long SSL_get_options(const SSL *s)
4847 {
4848     return s->options;
4849 }
4850
4851 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
4852 {
4853     return ctx->options |= op;
4854 }
4855
4856 unsigned long SSL_set_options(SSL *s, unsigned long op)
4857 {
4858     return s->options |= op;
4859 }
4860
4861 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
4862 {
4863     return ctx->options &= ~op;
4864 }
4865
4866 unsigned long SSL_clear_options(SSL *s, unsigned long op)
4867 {
4868     return s->options &= ~op;
4869 }
4870
4871 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
4872 {
4873     return s->verified_chain;
4874 }
4875
4876 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
4877
4878 #ifndef OPENSSL_NO_CT
4879
4880 /*
4881  * Moves SCTs from the |src| stack to the |dst| stack.
4882  * The source of each SCT will be set to |origin|.
4883  * If |dst| points to a NULL pointer, a new stack will be created and owned by
4884  * the caller.
4885  * Returns the number of SCTs moved, or a negative integer if an error occurs.
4886  */
4887 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
4888                         sct_source_t origin)
4889 {
4890     int scts_moved = 0;
4891     SCT *sct = NULL;
4892
4893     if (*dst == NULL) {
4894         *dst = sk_SCT_new_null();
4895         if (*dst == NULL) {
4896             SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
4897             goto err;
4898         }
4899     }
4900
4901     while ((sct = sk_SCT_pop(src)) != NULL) {
4902         if (SCT_set_source(sct, origin) != 1)
4903             goto err;
4904
4905         if (sk_SCT_push(*dst, sct) <= 0)
4906             goto err;
4907         scts_moved += 1;
4908     }
4909
4910     return scts_moved;
4911  err:
4912     if (sct != NULL)
4913         sk_SCT_push(src, sct);  /* Put the SCT back */
4914     return -1;
4915 }
4916
4917 /*
4918  * Look for data collected during ServerHello and parse if found.
4919  * Returns the number of SCTs extracted.
4920  */
4921 static int ct_extract_tls_extension_scts(SSL *s)
4922 {
4923     int scts_extracted = 0;
4924
4925     if (s->ext.scts != NULL) {
4926         const unsigned char *p = s->ext.scts;
4927         STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
4928
4929         scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
4930
4931         SCT_LIST_free(scts);
4932     }
4933
4934     return scts_extracted;
4935 }
4936
4937 /*
4938  * Checks for an OCSP response and then attempts to extract any SCTs found if it
4939  * contains an SCT X509 extension. They will be stored in |s->scts|.
4940  * Returns:
4941  * - The number of SCTs extracted, assuming an OCSP response exists.
4942  * - 0 if no OCSP response exists or it contains no SCTs.
4943  * - A negative integer if an error occurs.
4944  */
4945 static int ct_extract_ocsp_response_scts(SSL *s)
4946 {
4947 # ifndef OPENSSL_NO_OCSP
4948     int scts_extracted = 0;
4949     const unsigned char *p;
4950     OCSP_BASICRESP *br = NULL;
4951     OCSP_RESPONSE *rsp = NULL;
4952     STACK_OF(SCT) *scts = NULL;
4953     int i;
4954
4955     if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
4956         goto err;
4957
4958     p = s->ext.ocsp.resp;
4959     rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
4960     if (rsp == NULL)
4961         goto err;
4962
4963     br = OCSP_response_get1_basic(rsp);
4964     if (br == NULL)
4965         goto err;
4966
4967     for (i = 0; i < OCSP_resp_count(br); ++i) {
4968         OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
4969
4970         if (single == NULL)
4971             continue;
4972
4973         scts =
4974             OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
4975         scts_extracted =
4976             ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
4977         if (scts_extracted < 0)
4978             goto err;
4979     }
4980  err:
4981     SCT_LIST_free(scts);
4982     OCSP_BASICRESP_free(br);
4983     OCSP_RESPONSE_free(rsp);
4984     return scts_extracted;
4985 # else
4986     /* Behave as if no OCSP response exists */
4987     return 0;
4988 # endif
4989 }
4990
4991 /*
4992  * Attempts to extract SCTs from the peer certificate.
4993  * Return the number of SCTs extracted, or a negative integer if an error
4994  * occurs.
4995  */
4996 static int ct_extract_x509v3_extension_scts(SSL *s)
4997 {
4998     int scts_extracted = 0;
4999     X509 *cert = s->session != NULL ? s->session->peer : NULL;
5000
5001     if (cert != NULL) {
5002         STACK_OF(SCT) *scts =
5003             X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
5004
5005         scts_extracted =
5006             ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
5007
5008         SCT_LIST_free(scts);
5009     }
5010
5011     return scts_extracted;
5012 }
5013
5014 /*
5015  * Attempts to find all received SCTs by checking TLS extensions, the OCSP
5016  * response (if it exists) and X509v3 extensions in the certificate.
5017  * Returns NULL if an error occurs.
5018  */
5019 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
5020 {
5021     if (!s->scts_parsed) {
5022         if (ct_extract_tls_extension_scts(s) < 0 ||
5023             ct_extract_ocsp_response_scts(s) < 0 ||
5024             ct_extract_x509v3_extension_scts(s) < 0)
5025             goto err;
5026
5027         s->scts_parsed = 1;
5028     }
5029     return s->scts;
5030  err:
5031     return NULL;
5032 }
5033
5034 static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
5035                          const STACK_OF(SCT) *scts, void *unused_arg)
5036 {
5037     return 1;
5038 }
5039
5040 static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
5041                      const STACK_OF(SCT) *scts, void *unused_arg)
5042 {
5043     int count = scts != NULL ? sk_SCT_num(scts) : 0;
5044     int i;
5045
5046     for (i = 0; i < count; ++i) {
5047         SCT *sct = sk_SCT_value(scts, i);
5048         int status = SCT_get_validation_status(sct);
5049
5050         if (status == SCT_VALIDATION_STATUS_VALID)
5051             return 1;
5052     }
5053     SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
5054     return 0;
5055 }
5056
5057 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
5058                                    void *arg)
5059 {
5060     /*
5061      * Since code exists that uses the custom extension handler for CT, look
5062      * for this and throw an error if they have already registered to use CT.
5063      */
5064     if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
5065                                                           TLSEXT_TYPE_signed_certificate_timestamp))
5066     {
5067         SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
5068                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
5069         return 0;
5070     }
5071
5072     if (callback != NULL) {
5073         /*
5074          * If we are validating CT, then we MUST accept SCTs served via OCSP
5075          */
5076         if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
5077             return 0;
5078     }
5079
5080     s->ct_validation_callback = callback;
5081     s->ct_validation_callback_arg = arg;
5082
5083     return 1;
5084 }
5085
5086 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
5087                                        ssl_ct_validation_cb callback, void *arg)
5088 {
5089     /*
5090      * Since code exists that uses the custom extension handler for CT, look for
5091      * this and throw an error if they have already registered to use CT.
5092      */
5093     if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
5094                                                           TLSEXT_TYPE_signed_certificate_timestamp))
5095     {
5096         SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
5097                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
5098         return 0;
5099     }
5100
5101     ctx->ct_validation_callback = callback;
5102     ctx->ct_validation_callback_arg = arg;
5103     return 1;
5104 }
5105
5106 int SSL_ct_is_enabled(const SSL *s)
5107 {
5108     return s->ct_validation_callback != NULL;
5109 }
5110
5111 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
5112 {
5113     return ctx->ct_validation_callback != NULL;
5114 }
5115
5116 int ssl_validate_ct(SSL *s)
5117 {
5118     int ret = 0;
5119     X509 *cert = s->session != NULL ? s->session->peer : NULL;
5120     X509 *issuer;
5121     SSL_DANE *dane = &s->dane;
5122     CT_POLICY_EVAL_CTX *ctx = NULL;
5123     const STACK_OF(SCT) *scts;
5124
5125     /*
5126      * If no callback is set, the peer is anonymous, or its chain is invalid,
5127      * skip SCT validation - just return success.  Applications that continue
5128      * handshakes without certificates, with unverified chains, or pinned leaf
5129      * certificates are outside the scope of the WebPKI and CT.
5130      *
5131      * The above exclusions notwithstanding the vast majority of peers will
5132      * have rather ordinary certificate chains validated by typical
5133      * applications that perform certificate verification and therefore will
5134      * process SCTs when enabled.
5135      */
5136     if (s->ct_validation_callback == NULL || cert == NULL ||
5137         s->verify_result != X509_V_OK ||
5138         s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
5139         return 1;
5140
5141     /*
5142      * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
5143      * trust-anchors.  See https://tools.ietf.org/html/rfc7671#section-4.2
5144      */
5145     if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
5146         switch (dane->mtlsa->usage) {
5147         case DANETLS_USAGE_DANE_TA:
5148         case DANETLS_USAGE_DANE_EE:
5149             return 1;
5150         }
5151     }
5152
5153     ctx = CT_POLICY_EVAL_CTX_new_with_libctx(s->ctx->libctx, s->ctx->propq);
5154     if (ctx == NULL) {
5155         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_VALIDATE_CT,
5156                  ERR_R_MALLOC_FAILURE);
5157         goto end;
5158     }
5159
5160     issuer = sk_X509_value(s->verified_chain, 1);
5161     CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
5162     CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
5163     CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx, s->ctx->ctlog_store);
5164     CT_POLICY_EVAL_CTX_set_time(
5165             ctx, (uint64_t)SSL_SESSION_get_time(SSL_get0_session(s)) * 1000);
5166
5167     scts = SSL_get0_peer_scts(s);
5168
5169     /*
5170      * This function returns success (> 0) only when all the SCTs are valid, 0
5171      * when some are invalid, and < 0 on various internal errors (out of
5172      * memory, etc.).  Having some, or even all, invalid SCTs is not sufficient
5173      * reason to abort the handshake, that decision is up to the callback.
5174      * Therefore, we error out only in the unexpected case that the return
5175      * value is negative.
5176      *
5177      * XXX: One might well argue that the return value of this function is an
5178      * unfortunate design choice.  Its job is only to determine the validation
5179      * status of each of the provided SCTs.  So long as it correctly separates
5180      * the wheat from the chaff it should return success.  Failure in this case
5181      * ought to correspond to an inability to carry out its duties.
5182      */
5183     if (SCT_LIST_validate(scts, ctx) < 0) {
5184         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_SSL_VALIDATE_CT,
5185                  SSL_R_SCT_VERIFICATION_FAILED);
5186         goto end;
5187     }
5188
5189     ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
5190     if (ret < 0)
5191         ret = 0;                /* This function returns 0 on failure */
5192     if (!ret)
5193         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_SSL_VALIDATE_CT,
5194                  SSL_R_CALLBACK_FAILED);
5195
5196  end:
5197     CT_POLICY_EVAL_CTX_free(ctx);
5198     /*
5199      * With SSL_VERIFY_NONE the session may be cached and re-used despite a
5200      * failure return code here.  Also the application may wish the complete
5201      * the handshake, and then disconnect cleanly at a higher layer, after
5202      * checking the verification status of the completed connection.
5203      *
5204      * We therefore force a certificate verification failure which will be
5205      * visible via SSL_get_verify_result() and cached as part of any resumed
5206      * session.
5207      *
5208      * Note: the permissive callback is for information gathering only, always
5209      * returns success, and does not affect verification status.  Only the
5210      * strict callback or a custom application-specified callback can trigger
5211      * connection failure or record a verification error.
5212      */
5213     if (ret <= 0)
5214         s->verify_result = X509_V_ERR_NO_VALID_SCTS;
5215     return ret;
5216 }
5217
5218 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
5219 {
5220     switch (validation_mode) {
5221     default:
5222         SSLerr(SSL_F_SSL_CTX_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
5223         return 0;
5224     case SSL_CT_VALIDATION_PERMISSIVE:
5225         return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
5226     case SSL_CT_VALIDATION_STRICT:
5227         return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
5228     }
5229 }
5230
5231 int SSL_enable_ct(SSL *s, int validation_mode)
5232 {
5233     switch (validation_mode) {
5234     default:
5235         SSLerr(SSL_F_SSL_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
5236         return 0;
5237     case SSL_CT_VALIDATION_PERMISSIVE:
5238         return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
5239     case SSL_CT_VALIDATION_STRICT:
5240         return SSL_set_ct_validation_callback(s, ct_strict, NULL);
5241     }
5242 }
5243
5244 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
5245 {
5246     return CTLOG_STORE_load_default_file(ctx->ctlog_store);
5247 }
5248
5249 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
5250 {
5251     return CTLOG_STORE_load_file(ctx->ctlog_store, path);
5252 }
5253
5254 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE * logs)
5255 {
5256     CTLOG_STORE_free(ctx->ctlog_store);
5257     ctx->ctlog_store = logs;
5258 }
5259
5260 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
5261 {
5262     return ctx->ctlog_store;
5263 }
5264
5265 #endif  /* OPENSSL_NO_CT */
5266
5267 void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
5268                                  void *arg)
5269 {
5270     c->client_hello_cb = cb;
5271     c->client_hello_cb_arg = arg;
5272 }
5273
5274 int SSL_client_hello_isv2(SSL *s)
5275 {
5276     if (s->clienthello == NULL)
5277         return 0;
5278     return s->clienthello->isv2;
5279 }
5280
5281 unsigned int SSL_client_hello_get0_legacy_version(SSL *s)
5282 {
5283     if (s->clienthello == NULL)
5284         return 0;
5285     return s->clienthello->legacy_version;
5286 }
5287
5288 size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out)
5289 {
5290     if (s->clienthello == NULL)
5291         return 0;
5292     if (out != NULL)
5293         *out = s->clienthello->random;
5294     return SSL3_RANDOM_SIZE;
5295 }
5296
5297 size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out)
5298 {
5299     if (s->clienthello == NULL)
5300         return 0;
5301     if (out != NULL)
5302         *out = s->clienthello->session_id;
5303     return s->clienthello->session_id_len;
5304 }
5305
5306 size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out)
5307 {
5308     if (s->clienthello == NULL)
5309         return 0;
5310     if (out != NULL)
5311         *out = PACKET_data(&s->clienthello->ciphersuites);
5312     return PACKET_remaining(&s->clienthello->ciphersuites);
5313 }
5314
5315 size_t SSL_client_hello_get0_compression_methods(SSL *s, const unsigned char **out)
5316 {
5317     if (s->clienthello == NULL)
5318         return 0;
5319     if (out != NULL)
5320         *out = s->clienthello->compressions;
5321     return s->clienthello->compressions_len;
5322 }
5323
5324 int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen)
5325 {
5326     RAW_EXTENSION *ext;
5327     int *present;
5328     size_t num = 0, i;
5329
5330     if (s->clienthello == NULL || out == NULL || outlen == NULL)
5331         return 0;
5332     for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
5333         ext = s->clienthello->pre_proc_exts + i;
5334         if (ext->present)
5335             num++;
5336     }
5337     if (num == 0) {
5338         *out = NULL;
5339         *outlen = 0;
5340         return 1;
5341     }
5342     if ((present = OPENSSL_malloc(sizeof(*present) * num)) == NULL) {
5343         SSLerr(SSL_F_SSL_CLIENT_HELLO_GET1_EXTENSIONS_PRESENT,
5344                ERR_R_MALLOC_FAILURE);
5345         return 0;
5346     }
5347     for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
5348         ext = s->clienthello->pre_proc_exts + i;
5349         if (ext->present) {
5350             if (ext->received_order >= num)
5351                 goto err;
5352             present[ext->received_order] = ext->type;
5353         }
5354     }
5355     *out = present;
5356     *outlen = num;
5357     return 1;
5358  err:
5359     OPENSSL_free(present);
5360     return 0;
5361 }
5362
5363 int SSL_client_hello_get0_ext(SSL *s, unsigned int type, const unsigned char **out,
5364                        size_t *outlen)
5365 {
5366     size_t i;
5367     RAW_EXTENSION *r;
5368
5369     if (s->clienthello == NULL)
5370         return 0;
5371     for (i = 0; i < s->clienthello->pre_proc_exts_len; ++i) {
5372         r = s->clienthello->pre_proc_exts + i;
5373         if (r->present && r->type == type) {
5374             if (out != NULL)
5375                 *out = PACKET_data(&r->data);
5376             if (outlen != NULL)
5377                 *outlen = PACKET_remaining(&r->data);
5378             return 1;
5379         }
5380     }
5381     return 0;
5382 }
5383
5384 int SSL_free_buffers(SSL *ssl)
5385 {
5386     RECORD_LAYER *rl = &ssl->rlayer;
5387
5388     if (RECORD_LAYER_read_pending(rl) || RECORD_LAYER_write_pending(rl))
5389         return 0;
5390
5391     RECORD_LAYER_release(rl);
5392     return 1;
5393 }
5394
5395 int SSL_alloc_buffers(SSL *ssl)
5396 {
5397     return ssl3_setup_buffers(ssl);
5398 }
5399
5400 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
5401 {
5402     ctx->keylog_callback = cb;
5403 }
5404
5405 SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
5406 {
5407     return ctx->keylog_callback;
5408 }
5409
5410 static int nss_keylog_int(const char *prefix,
5411                           SSL *ssl,
5412                           const uint8_t *parameter_1,
5413                           size_t parameter_1_len,
5414                           const uint8_t *parameter_2,
5415                           size_t parameter_2_len)
5416 {
5417     char *out = NULL;
5418     char *cursor = NULL;
5419     size_t out_len = 0;
5420     size_t i;
5421     size_t prefix_len;
5422
5423     if (ssl->ctx->keylog_callback == NULL)
5424         return 1;
5425
5426     /*
5427      * Our output buffer will contain the following strings, rendered with
5428      * space characters in between, terminated by a NULL character: first the
5429      * prefix, then the first parameter, then the second parameter. The
5430      * meaning of each parameter depends on the specific key material being
5431      * logged. Note that the first and second parameters are encoded in
5432      * hexadecimal, so we need a buffer that is twice their lengths.
5433      */
5434     prefix_len = strlen(prefix);
5435     out_len = prefix_len + (2 * parameter_1_len) + (2 * parameter_2_len) + 3;
5436     if ((out = cursor = OPENSSL_malloc(out_len)) == NULL) {
5437         SSLfatal(ssl, SSL_AD_INTERNAL_ERROR, SSL_F_NSS_KEYLOG_INT,
5438                  ERR_R_MALLOC_FAILURE);
5439         return 0;
5440     }
5441
5442     strcpy(cursor, prefix);
5443     cursor += prefix_len;
5444     *cursor++ = ' ';
5445
5446     for (i = 0; i < parameter_1_len; i++) {
5447         sprintf(cursor, "%02x", parameter_1[i]);
5448         cursor += 2;
5449     }
5450     *cursor++ = ' ';
5451
5452     for (i = 0; i < parameter_2_len; i++) {
5453         sprintf(cursor, "%02x", parameter_2[i]);
5454         cursor += 2;
5455     }
5456     *cursor = '\0';
5457
5458     ssl->ctx->keylog_callback(ssl, (const char *)out);
5459     OPENSSL_clear_free(out, out_len);
5460     return 1;
5461
5462 }
5463
5464 int ssl_log_rsa_client_key_exchange(SSL *ssl,
5465                                     const uint8_t *encrypted_premaster,
5466                                     size_t encrypted_premaster_len,
5467                                     const uint8_t *premaster,
5468                                     size_t premaster_len)
5469 {
5470     if (encrypted_premaster_len < 8) {
5471         SSLfatal(ssl, SSL_AD_INTERNAL_ERROR,
5472                  SSL_F_SSL_LOG_RSA_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
5473         return 0;
5474     }
5475
5476     /* We only want the first 8 bytes of the encrypted premaster as a tag. */
5477     return nss_keylog_int("RSA",
5478                           ssl,
5479                           encrypted_premaster,
5480                           8,
5481                           premaster,
5482                           premaster_len);
5483 }
5484
5485 int ssl_log_secret(SSL *ssl,
5486                    const char *label,
5487                    const uint8_t *secret,
5488                    size_t secret_len)
5489 {
5490     return nss_keylog_int(label,
5491                           ssl,
5492                           ssl->s3.client_random,
5493                           SSL3_RANDOM_SIZE,
5494                           secret,
5495                           secret_len);
5496 }
5497
5498 #define SSLV2_CIPHER_LEN    3
5499
5500 int ssl_cache_cipherlist(SSL *s, PACKET *cipher_suites, int sslv2format)
5501 {
5502     int n;
5503
5504     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
5505
5506     if (PACKET_remaining(cipher_suites) == 0) {
5507         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL_CACHE_CIPHERLIST,
5508                  SSL_R_NO_CIPHERS_SPECIFIED);
5509         return 0;
5510     }
5511
5512     if (PACKET_remaining(cipher_suites) % n != 0) {
5513         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL_CACHE_CIPHERLIST,
5514                  SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
5515         return 0;
5516     }
5517
5518     OPENSSL_free(s->s3.tmp.ciphers_raw);
5519     s->s3.tmp.ciphers_raw = NULL;
5520     s->s3.tmp.ciphers_rawlen = 0;
5521
5522     if (sslv2format) {
5523         size_t numciphers = PACKET_remaining(cipher_suites) / n;
5524         PACKET sslv2ciphers = *cipher_suites;
5525         unsigned int leadbyte;
5526         unsigned char *raw;
5527
5528         /*
5529          * We store the raw ciphers list in SSLv3+ format so we need to do some
5530          * preprocessing to convert the list first. If there are any SSLv2 only
5531          * ciphersuites with a non-zero leading byte then we are going to
5532          * slightly over allocate because we won't store those. But that isn't a
5533          * problem.
5534          */
5535         raw = OPENSSL_malloc(numciphers * TLS_CIPHER_LEN);
5536         s->s3.tmp.ciphers_raw = raw;
5537         if (raw == NULL) {
5538             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_CACHE_CIPHERLIST,
5539                      ERR_R_MALLOC_FAILURE);
5540             return 0;
5541         }
5542         for (s->s3.tmp.ciphers_rawlen = 0;
5543              PACKET_remaining(&sslv2ciphers) > 0;
5544              raw += TLS_CIPHER_LEN) {
5545             if (!PACKET_get_1(&sslv2ciphers, &leadbyte)
5546                     || (leadbyte == 0
5547                         && !PACKET_copy_bytes(&sslv2ciphers, raw,
5548                                               TLS_CIPHER_LEN))
5549                     || (leadbyte != 0
5550                         && !PACKET_forward(&sslv2ciphers, TLS_CIPHER_LEN))) {
5551                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL_CACHE_CIPHERLIST,
5552                          SSL_R_BAD_PACKET);
5553                 OPENSSL_free(s->s3.tmp.ciphers_raw);
5554                 s->s3.tmp.ciphers_raw = NULL;
5555                 s->s3.tmp.ciphers_rawlen = 0;
5556                 return 0;
5557             }
5558             if (leadbyte == 0)
5559                 s->s3.tmp.ciphers_rawlen += TLS_CIPHER_LEN;
5560         }
5561     } else if (!PACKET_memdup(cipher_suites, &s->s3.tmp.ciphers_raw,
5562                            &s->s3.tmp.ciphers_rawlen)) {
5563         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_CACHE_CIPHERLIST,
5564                  ERR_R_INTERNAL_ERROR);
5565         return 0;
5566     }
5567     return 1;
5568 }
5569
5570 int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
5571                              int isv2format, STACK_OF(SSL_CIPHER) **sk,
5572                              STACK_OF(SSL_CIPHER) **scsvs)
5573 {
5574     PACKET pkt;
5575
5576     if (!PACKET_buf_init(&pkt, bytes, len))
5577         return 0;
5578     return bytes_to_cipher_list(s, &pkt, sk, scsvs, isv2format, 0);
5579 }
5580
5581 int bytes_to_cipher_list(SSL *s, PACKET *cipher_suites,
5582                          STACK_OF(SSL_CIPHER) **skp,
5583                          STACK_OF(SSL_CIPHER) **scsvs_out,
5584                          int sslv2format, int fatal)
5585 {
5586     const SSL_CIPHER *c;
5587     STACK_OF(SSL_CIPHER) *sk = NULL;
5588     STACK_OF(SSL_CIPHER) *scsvs = NULL;
5589     int n;
5590     /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
5591     unsigned char cipher[SSLV2_CIPHER_LEN];
5592
5593     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
5594
5595     if (PACKET_remaining(cipher_suites) == 0) {
5596         if (fatal)
5597             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_BYTES_TO_CIPHER_LIST,
5598                      SSL_R_NO_CIPHERS_SPECIFIED);
5599         else
5600             SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
5601         return 0;
5602     }
5603
5604     if (PACKET_remaining(cipher_suites) % n != 0) {
5605         if (fatal)
5606             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_BYTES_TO_CIPHER_LIST,
5607                      SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
5608         else
5609             SSLerr(SSL_F_BYTES_TO_CIPHER_LIST,
5610                    SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
5611         return 0;
5612     }
5613
5614     sk = sk_SSL_CIPHER_new_null();
5615     scsvs = sk_SSL_CIPHER_new_null();
5616     if (sk == NULL || scsvs == NULL) {
5617         if (fatal)
5618             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_BYTES_TO_CIPHER_LIST,
5619                      ERR_R_MALLOC_FAILURE);
5620         else
5621             SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
5622         goto err;
5623     }
5624
5625     while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
5626         /*
5627          * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
5628          * first byte set to zero, while true SSLv2 ciphers have a non-zero
5629          * first byte. We don't support any true SSLv2 ciphers, so skip them.
5630          */
5631         if (sslv2format && cipher[0] != '\0')
5632             continue;
5633
5634         /* For SSLv2-compat, ignore leading 0-byte. */
5635         c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher, 1);
5636         if (c != NULL) {
5637             if ((c->valid && !sk_SSL_CIPHER_push(sk, c)) ||
5638                 (!c->valid && !sk_SSL_CIPHER_push(scsvs, c))) {
5639                 if (fatal)
5640                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
5641                              SSL_F_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
5642                 else
5643                     SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
5644                 goto err;
5645             }
5646         }
5647     }
5648     if (PACKET_remaining(cipher_suites) > 0) {
5649         if (fatal)
5650             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_BYTES_TO_CIPHER_LIST,
5651                      SSL_R_BAD_LENGTH);
5652         else
5653             SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, SSL_R_BAD_LENGTH);
5654         goto err;
5655     }
5656
5657     if (skp != NULL)
5658         *skp = sk;
5659     else
5660         sk_SSL_CIPHER_free(sk);
5661     if (scsvs_out != NULL)
5662         *scsvs_out = scsvs;
5663     else
5664         sk_SSL_CIPHER_free(scsvs);
5665     return 1;
5666  err:
5667     sk_SSL_CIPHER_free(sk);
5668     sk_SSL_CIPHER_free(scsvs);
5669     return 0;
5670 }
5671
5672 int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
5673 {
5674     ctx->max_early_data = max_early_data;
5675
5676     return 1;
5677 }
5678
5679 uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
5680 {
5681     return ctx->max_early_data;
5682 }
5683
5684 int SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
5685 {
5686     s->max_early_data = max_early_data;
5687
5688     return 1;
5689 }
5690
5691 uint32_t SSL_get_max_early_data(const SSL *s)
5692 {
5693     return s->max_early_data;
5694 }
5695
5696 int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data)
5697 {
5698     ctx->recv_max_early_data = recv_max_early_data;
5699
5700     return 1;
5701 }
5702
5703 uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx)
5704 {
5705     return ctx->recv_max_early_data;
5706 }
5707
5708 int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data)
5709 {
5710     s->recv_max_early_data = recv_max_early_data;
5711
5712     return 1;
5713 }
5714
5715 uint32_t SSL_get_recv_max_early_data(const SSL *s)
5716 {
5717     return s->recv_max_early_data;
5718 }
5719
5720 __owur unsigned int ssl_get_max_send_fragment(const SSL *ssl)
5721 {
5722     /* Return any active Max Fragment Len extension */
5723     if (ssl->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session))
5724         return GET_MAX_FRAGMENT_LENGTH(ssl->session);
5725
5726     /* return current SSL connection setting */
5727     return ssl->max_send_fragment;
5728 }
5729
5730 __owur unsigned int ssl_get_split_send_fragment(const SSL *ssl)
5731 {
5732     /* Return a value regarding an active Max Fragment Len extension */
5733     if (ssl->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session)
5734         && ssl->split_send_fragment > GET_MAX_FRAGMENT_LENGTH(ssl->session))
5735         return GET_MAX_FRAGMENT_LENGTH(ssl->session);
5736
5737     /* else limit |split_send_fragment| to current |max_send_fragment| */
5738     if (ssl->split_send_fragment > ssl->max_send_fragment)
5739         return ssl->max_send_fragment;
5740
5741     /* return current SSL connection setting */
5742     return ssl->split_send_fragment;
5743 }
5744
5745 int SSL_stateless(SSL *s)
5746 {
5747     int ret;
5748
5749     /* Ensure there is no state left over from a previous invocation */
5750     if (!SSL_clear(s))
5751         return 0;
5752
5753     ERR_clear_error();
5754
5755     s->s3.flags |= TLS1_FLAGS_STATELESS;
5756     ret = SSL_accept(s);
5757     s->s3.flags &= ~TLS1_FLAGS_STATELESS;
5758
5759     if (ret > 0 && s->ext.cookieok)
5760         return 1;
5761
5762     if (s->hello_retry_request == SSL_HRR_PENDING && !ossl_statem_in_error(s))
5763         return 0;
5764
5765     return -1;
5766 }
5767
5768 void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val)
5769 {
5770     ctx->pha_enabled = val;
5771 }
5772
5773 void SSL_set_post_handshake_auth(SSL *ssl, int val)
5774 {
5775     ssl->pha_enabled = val;
5776 }
5777
5778 int SSL_verify_client_post_handshake(SSL *ssl)
5779 {
5780     if (!SSL_IS_TLS13(ssl)) {
5781         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_WRONG_SSL_VERSION);
5782         return 0;
5783     }
5784     if (!ssl->server) {
5785         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_NOT_SERVER);
5786         return 0;
5787     }
5788
5789     if (!SSL_is_init_finished(ssl)) {
5790         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_STILL_IN_INIT);
5791         return 0;
5792     }
5793
5794     switch (ssl->post_handshake_auth) {
5795     case SSL_PHA_NONE:
5796         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_EXTENSION_NOT_RECEIVED);
5797         return 0;
5798     default:
5799     case SSL_PHA_EXT_SENT:
5800         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, ERR_R_INTERNAL_ERROR);
5801         return 0;
5802     case SSL_PHA_EXT_RECEIVED:
5803         break;
5804     case SSL_PHA_REQUEST_PENDING:
5805         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_REQUEST_PENDING);
5806         return 0;
5807     case SSL_PHA_REQUESTED:
5808         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_REQUEST_SENT);
5809         return 0;
5810     }
5811
5812     ssl->post_handshake_auth = SSL_PHA_REQUEST_PENDING;
5813
5814     /* checks verify_mode and algorithm_auth */
5815     if (!send_certificate_request(ssl)) {
5816         ssl->post_handshake_auth = SSL_PHA_EXT_RECEIVED; /* restore on error */
5817         SSLerr(SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE, SSL_R_INVALID_CONFIG);
5818         return 0;
5819     }
5820
5821     ossl_statem_set_in_init(ssl, 1);
5822     return 1;
5823 }
5824
5825 int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
5826                                   SSL_CTX_generate_session_ticket_fn gen_cb,
5827                                   SSL_CTX_decrypt_session_ticket_fn dec_cb,
5828                                   void *arg)
5829 {
5830     ctx->generate_ticket_cb = gen_cb;
5831     ctx->decrypt_ticket_cb = dec_cb;
5832     ctx->ticket_cb_data = arg;
5833     return 1;
5834 }
5835
5836 void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
5837                                      SSL_allow_early_data_cb_fn cb,
5838                                      void *arg)
5839 {
5840     ctx->allow_early_data_cb = cb;
5841     ctx->allow_early_data_cb_data = arg;
5842 }
5843
5844 void SSL_set_allow_early_data_cb(SSL *s,
5845                                  SSL_allow_early_data_cb_fn cb,
5846                                  void *arg)
5847 {
5848     s->allow_early_data_cb = cb;
5849     s->allow_early_data_cb_data = arg;
5850 }
5851
5852 const EVP_CIPHER *ssl_evp_cipher_fetch(OPENSSL_CTX *libctx,
5853                                        int nid,
5854                                        const char *properties)
5855 {
5856     EVP_CIPHER *ciph;
5857
5858 #ifndef OPENSSL_NO_ENGINE
5859     ENGINE *eng;
5860
5861     /*
5862      * If there is an Engine available for this cipher we use the "implicit"
5863      * form to ensure we use that engine later.
5864      */
5865     eng = ENGINE_get_cipher_engine(nid);
5866     if (eng != NULL) {
5867         ENGINE_finish(eng);
5868         return EVP_get_cipherbynid(nid);
5869     }
5870 #endif
5871
5872     /* Otherwise we do an explicit fetch. This may fail and that could be ok */
5873     ERR_set_mark();
5874     ciph = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(nid), properties);
5875     ERR_pop_to_mark();
5876     return ciph;
5877 }
5878
5879
5880 int ssl_evp_cipher_up_ref(const EVP_CIPHER *cipher)
5881 {
5882     /* Don't up-ref an implicit EVP_CIPHER */
5883     if (EVP_CIPHER_provider(cipher) == NULL)
5884         return 1;
5885
5886     /*
5887      * The cipher was explicitly fetched and therefore it is safe to cast
5888      * away the const
5889      */
5890     return EVP_CIPHER_up_ref((EVP_CIPHER *)cipher);
5891 }
5892
5893 void ssl_evp_cipher_free(const EVP_CIPHER *cipher)
5894 {
5895     if (cipher == NULL)
5896         return;
5897
5898     if (EVP_CIPHER_provider(cipher) != NULL) {
5899         /*
5900          * The cipher was explicitly fetched and therefore it is safe to cast
5901          * away the const
5902          */
5903         EVP_CIPHER_free((EVP_CIPHER *)cipher);
5904     }
5905 }
5906
5907 const EVP_MD *ssl_evp_md_fetch(OPENSSL_CTX *libctx,
5908                                int nid,
5909                                const char *properties)
5910 {
5911     EVP_MD *md;
5912
5913 #ifndef OPENSSL_NO_ENGINE
5914     ENGINE *eng;
5915
5916     /*
5917      * If there is an Engine available for this digest we use the "implicit"
5918      * form to ensure we use that engine later.
5919      */
5920     eng = ENGINE_get_digest_engine(nid);
5921     if (eng != NULL) {
5922         ENGINE_finish(eng);
5923         return EVP_get_digestbynid(nid);
5924     }
5925 #endif
5926
5927     /* Otherwise we do an explicit fetch */
5928     ERR_set_mark();
5929     md = EVP_MD_fetch(libctx, OBJ_nid2sn(nid), properties);
5930     ERR_pop_to_mark();
5931     return md;
5932 }
5933
5934 int ssl_evp_md_up_ref(const EVP_MD *md)
5935 {
5936     /* Don't up-ref an implicit EVP_MD */
5937     if (EVP_MD_provider(md) == NULL)
5938         return 1;
5939
5940     /*
5941      * The digest was explicitly fetched and therefore it is safe to cast
5942      * away the const
5943      */
5944     return EVP_MD_up_ref((EVP_MD *)md);
5945 }
5946
5947 void ssl_evp_md_free(const EVP_MD *md)
5948 {
5949     if (md == NULL)
5950         return;
5951
5952     if (EVP_MD_provider(md) != NULL) {
5953         /*
5954          * The digest was explicitly fetched and therefore it is safe to cast
5955          * away the const
5956          */
5957         EVP_MD_free((EVP_MD *)md);
5958     }
5959 }