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