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