cf59d2dfa57268a8ee62304a69c10f760ce5cfb2
[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 certifiate 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, size_t *written)
2516 {
2517     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2518
2519 #ifndef OPENSSL_NO_QUIC
2520     if (IS_QUIC(s))
2521         return s->method->ssl_write(s, buf, num, written);
2522 #endif
2523
2524     if (sc == NULL)
2525         return 0;
2526
2527     if (sc->handshake_func == NULL) {
2528         ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
2529         return -1;
2530     }
2531
2532     if (sc->shutdown & SSL_SENT_SHUTDOWN) {
2533         sc->rwstate = SSL_NOTHING;
2534         ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
2535         return -1;
2536     }
2537
2538     if (sc->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
2539                 || sc->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY
2540                 || sc->early_data_state == SSL_EARLY_DATA_READ_RETRY) {
2541         ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2542         return 0;
2543     }
2544     /* If we are a client and haven't sent the Finished we better do that */
2545     ossl_statem_check_finish_init(sc, 1);
2546
2547     if ((sc->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
2548         int ret;
2549         struct ssl_async_args args;
2550
2551         args.s = s;
2552         args.buf = (void *)buf;
2553         args.num = num;
2554         args.type = WRITEFUNC;
2555         args.f.func_write = s->method->ssl_write;
2556
2557         ret = ssl_start_async_job(s, &args, ssl_io_intern);
2558         *written = sc->asyncrw;
2559         return ret;
2560     } else {
2561         return s->method->ssl_write(s, buf, num, written);
2562     }
2563 }
2564
2565 ossl_ssize_t SSL_sendfile(SSL *s, int fd, off_t offset, size_t size, int flags)
2566 {
2567     ossl_ssize_t ret;
2568     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
2569
2570     if (sc == NULL)
2571         return 0;
2572
2573     if (sc->handshake_func == NULL) {
2574         ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
2575         return -1;
2576     }
2577
2578     if (sc->shutdown & SSL_SENT_SHUTDOWN) {
2579         sc->rwstate = SSL_NOTHING;
2580         ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
2581         return -1;
2582     }
2583
2584     if (!BIO_get_ktls_send(sc->wbio)) {
2585         ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
2586         return -1;
2587     }
2588
2589     /* If we have an alert to send, lets send it */
2590     if (sc->s3.alert_dispatch > 0) {
2591         ret = (ossl_ssize_t)s->method->ssl_dispatch_alert(s);
2592         if (ret <= 0) {
2593             /* SSLfatal() already called if appropriate */
2594             return ret;
2595         }
2596         /* if it went, fall through and send more stuff */
2597     }
2598
2599     sc->rwstate = SSL_WRITING;
2600     if (BIO_flush(sc->wbio) <= 0) {
2601         if (!BIO_should_retry(sc->wbio)) {
2602             sc->rwstate = SSL_NOTHING;
2603         } else {
2604 #ifdef EAGAIN
2605             set_sys_error(EAGAIN);
2606 #endif
2607         }
2608         return -1;
2609     }
2610
2611 #ifdef OPENSSL_NO_KTLS
2612     ERR_raise_data(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR,
2613                    "can't call ktls_sendfile(), ktls disabled");
2614     return -1;
2615 #else
2616     ret = ktls_sendfile(SSL_get_wfd(s), fd, offset, size, flags);
2617     if (ret < 0) {
2618 #if defined(EAGAIN) && defined(EINTR) && defined(EBUSY)
2619         if ((get_last_sys_error() == EAGAIN) ||
2620             (get_last_sys_error() == EINTR) ||
2621             (get_last_sys_error() == EBUSY))
2622             BIO_set_retry_write(sc->wbio);
2623         else
2624 #endif
2625             ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
2626         return ret;
2627     }
2628     sc->rwstate = SSL_NOTHING;
2629     return ret;
2630 #endif
2631 }
2632
2633 int SSL_write(SSL *s, const void *buf, int num)
2634 {
2635     int ret;
2636     size_t written;
2637
2638     if (num < 0) {
2639         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
2640         return -1;
2641     }
2642
2643     ret = ssl_write_internal(s, buf, (size_t)num, &written);
2644
2645     /*
2646      * The cast is safe here because ret should be <= INT_MAX because num is
2647      * <= INT_MAX
2648      */
2649     if (ret > 0)
2650         ret = (int)written;
2651
2652     return ret;
2653 }
2654
2655 int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
2656 {
2657     int ret = ssl_write_internal(s, buf, num, written);
2658
2659     if (ret < 0)
2660         ret = 0;
2661     return ret;
2662 }
2663
2664 int SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
2665 {
2666     int ret, early_data_state;
2667     size_t writtmp;
2668     uint32_t partialwrite;
2669     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
2670
2671     /* TODO(QUIC 0RTT): This will need special handling for QUIC */
2672     if (sc == NULL)
2673         return 0;
2674
2675     switch (sc->early_data_state) {
2676     case SSL_EARLY_DATA_NONE:
2677         if (sc->server
2678                 || !SSL_in_before(s)
2679                 || ((sc->session == NULL || sc->session->ext.max_early_data == 0)
2680                      && (sc->psk_use_session_cb == NULL))) {
2681             ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2682             return 0;
2683         }
2684         /* fall through */
2685
2686     case SSL_EARLY_DATA_CONNECT_RETRY:
2687         sc->early_data_state = SSL_EARLY_DATA_CONNECTING;
2688         ret = SSL_connect(s);
2689         if (ret <= 0) {
2690             /* NBIO or error */
2691             sc->early_data_state = SSL_EARLY_DATA_CONNECT_RETRY;
2692             return 0;
2693         }
2694         /* fall through */
2695
2696     case SSL_EARLY_DATA_WRITE_RETRY:
2697         sc->early_data_state = SSL_EARLY_DATA_WRITING;
2698         /*
2699          * We disable partial write for early data because we don't keep track
2700          * of how many bytes we've written between the SSL_write_ex() call and
2701          * the flush if the flush needs to be retried)
2702          */
2703         partialwrite = sc->mode & SSL_MODE_ENABLE_PARTIAL_WRITE;
2704         sc->mode &= ~SSL_MODE_ENABLE_PARTIAL_WRITE;
2705         ret = SSL_write_ex(s, buf, num, &writtmp);
2706         sc->mode |= partialwrite;
2707         if (!ret) {
2708             sc->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
2709             return ret;
2710         }
2711         sc->early_data_state = SSL_EARLY_DATA_WRITE_FLUSH;
2712         /* fall through */
2713
2714     case SSL_EARLY_DATA_WRITE_FLUSH:
2715         /* The buffering BIO is still in place so we need to flush it */
2716         if (statem_flush(sc) != 1)
2717             return 0;
2718         *written = num;
2719         sc->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
2720         return 1;
2721
2722     case SSL_EARLY_DATA_FINISHED_READING:
2723     case SSL_EARLY_DATA_READ_RETRY:
2724         early_data_state = sc->early_data_state;
2725         /* We are a server writing to an unauthenticated client */
2726         sc->early_data_state = SSL_EARLY_DATA_UNAUTH_WRITING;
2727         ret = SSL_write_ex(s, buf, num, written);
2728         /* The buffering BIO is still in place */
2729         if (ret)
2730             (void)BIO_flush(sc->wbio);
2731         sc->early_data_state = early_data_state;
2732         return ret;
2733
2734     default:
2735         ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2736         return 0;
2737     }
2738 }
2739
2740 int SSL_shutdown(SSL *s)
2741 {
2742     /*
2743      * Note that this function behaves differently from what one might
2744      * expect.  Return values are 0 for no success (yet), 1 for success; but
2745      * calling it once is usually not enough, even if blocking I/O is used
2746      * (see ssl3_shutdown).
2747      */
2748     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2749
2750 #ifndef OPENSSL_NO_QUIC
2751     if (IS_QUIC(s))
2752         return ossl_quic_conn_shutdown(s, 0, NULL, 0);
2753 #endif
2754
2755     if (sc == NULL)
2756         return -1;
2757
2758     if (sc->handshake_func == NULL) {
2759         ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
2760         return -1;
2761     }
2762
2763     if (!SSL_in_init(s)) {
2764         if ((sc->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
2765             struct ssl_async_args args;
2766
2767             memset(&args, 0, sizeof(args));
2768             args.s = s;
2769             args.type = OTHERFUNC;
2770             args.f.func_other = s->method->ssl_shutdown;
2771
2772             return ssl_start_async_job(s, &args, ssl_io_intern);
2773         } else {
2774             return s->method->ssl_shutdown(s);
2775         }
2776     } else {
2777         ERR_raise(ERR_LIB_SSL, SSL_R_SHUTDOWN_WHILE_IN_INIT);
2778         return -1;
2779     }
2780 }
2781
2782 int SSL_key_update(SSL *s, int updatetype)
2783 {
2784     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2785
2786 #ifndef OPENSSL_NO_QUIC
2787     if (IS_QUIC(s))
2788         return ossl_quic_key_update(s, updatetype);
2789 #endif
2790
2791     if (sc == NULL)
2792         return 0;
2793
2794     if (!SSL_CONNECTION_IS_TLS13(sc)) {
2795         ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
2796         return 0;
2797     }
2798
2799     if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
2800             && updatetype != SSL_KEY_UPDATE_REQUESTED) {
2801         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_KEY_UPDATE_TYPE);
2802         return 0;
2803     }
2804
2805     if (!SSL_is_init_finished(s)) {
2806         ERR_raise(ERR_LIB_SSL, SSL_R_STILL_IN_INIT);
2807         return 0;
2808     }
2809
2810     if (RECORD_LAYER_write_pending(&sc->rlayer)) {
2811         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_WRITE_RETRY);
2812         return 0;
2813     }
2814
2815     ossl_statem_set_in_init(sc, 1);
2816     sc->key_update = updatetype;
2817     return 1;
2818 }
2819
2820 int SSL_get_key_update_type(const SSL *s)
2821 {
2822     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
2823
2824 #ifndef OPENSSL_NO_QUIC
2825     if (IS_QUIC(s))
2826         return ossl_quic_get_key_update_type(s);
2827 #endif
2828
2829     if (sc == NULL)
2830         return 0;
2831
2832     return sc->key_update;
2833 }
2834
2835 /*
2836  * Can we accept a renegotiation request?  If yes, set the flag and
2837  * return 1 if yes. If not, raise error and return 0.
2838  */
2839 static int can_renegotiate(const SSL_CONNECTION *sc)
2840 {
2841     if (SSL_CONNECTION_IS_TLS13(sc)) {
2842         ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
2843         return 0;
2844     }
2845
2846     if ((sc->options & SSL_OP_NO_RENEGOTIATION) != 0) {
2847         ERR_raise(ERR_LIB_SSL, SSL_R_NO_RENEGOTIATION);
2848         return 0;
2849     }
2850
2851     return 1;
2852 }
2853
2854 int SSL_renegotiate(SSL *s)
2855 {
2856     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
2857
2858     if (sc == NULL)
2859         return 0;
2860
2861     if (!can_renegotiate(sc))
2862         return 0;
2863
2864     sc->renegotiate = 1;
2865     sc->new_session = 1;
2866     return s->method->ssl_renegotiate(s);
2867 }
2868
2869 int SSL_renegotiate_abbreviated(SSL *s)
2870 {
2871     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
2872
2873     if (sc == NULL)
2874         return 0;
2875
2876     if (!can_renegotiate(sc))
2877         return 0;
2878
2879     sc->renegotiate = 1;
2880     sc->new_session = 0;
2881     return s->method->ssl_renegotiate(s);
2882 }
2883
2884 int SSL_renegotiate_pending(const SSL *s)
2885 {
2886     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
2887
2888     if (sc == NULL)
2889         return 0;
2890
2891     /*
2892      * becomes true when negotiation is requested; false again once a
2893      * handshake has finished
2894      */
2895     return (sc->renegotiate != 0);
2896 }
2897
2898 int SSL_new_session_ticket(SSL *s)
2899 {
2900     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2901
2902     if (sc == NULL)
2903         return 0;
2904
2905     /* If we are in init because we're sending tickets, okay to send more. */
2906     if ((SSL_in_init(s) && sc->ext.extra_tickets_expected == 0)
2907             || SSL_IS_FIRST_HANDSHAKE(sc) || !sc->server
2908             || !SSL_CONNECTION_IS_TLS13(sc))
2909         return 0;
2910     sc->ext.extra_tickets_expected++;
2911     if (!RECORD_LAYER_write_pending(&sc->rlayer) && !SSL_in_init(s))
2912         ossl_statem_set_in_init(sc, 1);
2913     return 1;
2914 }
2915
2916 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
2917 {
2918     return ossl_ctrl_internal(s, cmd, larg, parg, /*no_quic=*/0);
2919 }
2920
2921 long ossl_ctrl_internal(SSL *s, int cmd, long larg, void *parg, int no_quic)
2922 {
2923     long l;
2924     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2925
2926     if (sc == NULL)
2927         return 0;
2928
2929     /*
2930      * Routing of ctrl calls for QUIC is a little counterintuitive:
2931      *
2932      *   - Firstly (no_quic=0), we pass the ctrl directly to our QUIC
2933      *     implementation in case it wants to handle the ctrl specially.
2934      *
2935      *   - If our QUIC implementation does not care about the ctrl, it
2936      *     will reenter this function with no_quic=1 and we will try to handle
2937      *     it directly using the QCSO SSL object stub (not the handshake layer
2938      *     SSL object). This is important for e.g. the version configuration
2939      *     ctrls below, which must use s->defltmeth (and not sc->defltmeth).
2940      *
2941      *   - If we don't handle a ctrl here specially, then processing is
2942      *     redirected to the handshake layer SSL object.
2943      */
2944     if (!no_quic && IS_QUIC(s))
2945         return s->method->ssl_ctrl(s, cmd, larg, parg);
2946
2947     switch (cmd) {
2948     case SSL_CTRL_GET_READ_AHEAD:
2949         return RECORD_LAYER_get_read_ahead(&sc->rlayer);
2950     case SSL_CTRL_SET_READ_AHEAD:
2951         l = RECORD_LAYER_get_read_ahead(&sc->rlayer);
2952         RECORD_LAYER_set_read_ahead(&sc->rlayer, larg);
2953         return l;
2954
2955     case SSL_CTRL_MODE:
2956     {
2957         OSSL_PARAM options[2], *opts = options;
2958
2959         sc->mode |= larg;
2960
2961         *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
2962                                               &sc->mode);
2963         *opts = OSSL_PARAM_construct_end();
2964
2965         /* Ignore return value */
2966         sc->rlayer.rrlmethod->set_options(sc->rlayer.rrl, options);
2967
2968         return sc->mode;
2969     }
2970     case SSL_CTRL_CLEAR_MODE:
2971         return (sc->mode &= ~larg);
2972     case SSL_CTRL_GET_MAX_CERT_LIST:
2973         return (long)sc->max_cert_list;
2974     case SSL_CTRL_SET_MAX_CERT_LIST:
2975         if (larg < 0)
2976             return 0;
2977         l = (long)sc->max_cert_list;
2978         sc->max_cert_list = (size_t)larg;
2979         return l;
2980     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2981         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2982             return 0;
2983 #ifndef OPENSSL_NO_KTLS
2984         if (sc->wbio != NULL && BIO_get_ktls_send(sc->wbio))
2985             return 0;
2986 #endif /* OPENSSL_NO_KTLS */
2987         sc->max_send_fragment = larg;
2988         if (sc->max_send_fragment < sc->split_send_fragment)
2989             sc->split_send_fragment = sc->max_send_fragment;
2990         sc->rlayer.wrlmethod->set_max_frag_len(sc->rlayer.wrl, larg);
2991         return 1;
2992     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2993         if ((size_t)larg > sc->max_send_fragment || larg == 0)
2994             return 0;
2995         sc->split_send_fragment = larg;
2996         return 1;
2997     case SSL_CTRL_SET_MAX_PIPELINES:
2998         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2999             return 0;
3000         sc->max_pipelines = larg;
3001         if (sc->rlayer.rrlmethod->set_max_pipelines != NULL)
3002             sc->rlayer.rrlmethod->set_max_pipelines(sc->rlayer.rrl, (size_t)larg);
3003         return 1;
3004     case SSL_CTRL_GET_RI_SUPPORT:
3005         return sc->s3.send_connection_binding;
3006     case SSL_CTRL_SET_RETRY_VERIFY:
3007         sc->rwstate = SSL_RETRY_VERIFY;
3008         return 1;
3009     case SSL_CTRL_CERT_FLAGS:
3010         return (sc->cert->cert_flags |= larg);
3011     case SSL_CTRL_CLEAR_CERT_FLAGS:
3012         return (sc->cert->cert_flags &= ~larg);
3013
3014     case SSL_CTRL_GET_RAW_CIPHERLIST:
3015         if (parg) {
3016             if (sc->s3.tmp.ciphers_raw == NULL)
3017                 return 0;
3018             *(unsigned char **)parg = sc->s3.tmp.ciphers_raw;
3019             return (int)sc->s3.tmp.ciphers_rawlen;
3020         } else {
3021             return TLS_CIPHER_LEN;
3022         }
3023     case SSL_CTRL_GET_EXTMS_SUPPORT:
3024         if (!sc->session || SSL_in_init(s) || ossl_statem_get_in_handshake(sc))
3025             return -1;
3026         if (sc->session->flags & SSL_SESS_FLAG_EXTMS)
3027             return 1;
3028         else
3029             return 0;
3030     case SSL_CTRL_SET_MIN_PROTO_VERSION:
3031         return ssl_check_allowed_versions(larg, sc->max_proto_version)
3032                && ssl_set_version_bound(s->defltmeth->version, (int)larg,
3033                                         &sc->min_proto_version);
3034     case SSL_CTRL_GET_MIN_PROTO_VERSION:
3035         return sc->min_proto_version;
3036     case SSL_CTRL_SET_MAX_PROTO_VERSION:
3037         return ssl_check_allowed_versions(sc->min_proto_version, larg)
3038                && ssl_set_version_bound(s->defltmeth->version, (int)larg,
3039                                         &sc->max_proto_version);
3040     case SSL_CTRL_GET_MAX_PROTO_VERSION:
3041         return sc->max_proto_version;
3042     default:
3043         if (IS_QUIC(s))
3044             return SSL_ctrl((SSL *)sc, cmd, larg, parg);
3045         else
3046             return s->method->ssl_ctrl(s, cmd, larg, parg);
3047     }
3048 }
3049
3050 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
3051 {
3052     return s->method->ssl_callback_ctrl(s, cmd, fp);
3053 }
3054
3055 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
3056 {
3057     return ctx->sessions;
3058 }
3059
3060 static int ssl_tsan_load(SSL_CTX *ctx, TSAN_QUALIFIER int *stat)
3061 {
3062     int res = 0;
3063
3064     if (ssl_tsan_lock(ctx)) {
3065         res = tsan_load(stat);
3066         ssl_tsan_unlock(ctx);
3067     }
3068     return res;
3069 }
3070
3071 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
3072 {
3073     long l;
3074     /* For some cases with ctx == NULL perform syntax checks */
3075     if (ctx == NULL) {
3076         switch (cmd) {
3077         case SSL_CTRL_SET_GROUPS_LIST:
3078             return tls1_set_groups_list(ctx, NULL, NULL, parg);
3079         case SSL_CTRL_SET_SIGALGS_LIST:
3080         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
3081             return tls1_set_sigalgs_list(NULL, parg, 0);
3082         default:
3083             return 0;
3084         }
3085     }
3086
3087     switch (cmd) {
3088     case SSL_CTRL_GET_READ_AHEAD:
3089         return ctx->read_ahead;
3090     case SSL_CTRL_SET_READ_AHEAD:
3091         l = ctx->read_ahead;
3092         ctx->read_ahead = larg;
3093         return l;
3094
3095     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
3096         ctx->msg_callback_arg = parg;
3097         return 1;
3098
3099     case SSL_CTRL_GET_MAX_CERT_LIST:
3100         return (long)ctx->max_cert_list;
3101     case SSL_CTRL_SET_MAX_CERT_LIST:
3102         if (larg < 0)
3103             return 0;
3104         l = (long)ctx->max_cert_list;
3105         ctx->max_cert_list = (size_t)larg;
3106         return l;
3107
3108     case SSL_CTRL_SET_SESS_CACHE_SIZE:
3109         if (larg < 0)
3110             return 0;
3111         l = (long)ctx->session_cache_size;
3112         ctx->session_cache_size = (size_t)larg;
3113         return l;
3114     case SSL_CTRL_GET_SESS_CACHE_SIZE:
3115         return (long)ctx->session_cache_size;
3116     case SSL_CTRL_SET_SESS_CACHE_MODE:
3117         l = ctx->session_cache_mode;
3118         ctx->session_cache_mode = larg;
3119         return l;
3120     case SSL_CTRL_GET_SESS_CACHE_MODE:
3121         return ctx->session_cache_mode;
3122
3123     case SSL_CTRL_SESS_NUMBER:
3124         return lh_SSL_SESSION_num_items(ctx->sessions);
3125     case SSL_CTRL_SESS_CONNECT:
3126         return ssl_tsan_load(ctx, &ctx->stats.sess_connect);
3127     case SSL_CTRL_SESS_CONNECT_GOOD:
3128         return ssl_tsan_load(ctx, &ctx->stats.sess_connect_good);
3129     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
3130         return ssl_tsan_load(ctx, &ctx->stats.sess_connect_renegotiate);
3131     case SSL_CTRL_SESS_ACCEPT:
3132         return ssl_tsan_load(ctx, &ctx->stats.sess_accept);
3133     case SSL_CTRL_SESS_ACCEPT_GOOD:
3134         return ssl_tsan_load(ctx, &ctx->stats.sess_accept_good);
3135     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
3136         return ssl_tsan_load(ctx, &ctx->stats.sess_accept_renegotiate);
3137     case SSL_CTRL_SESS_HIT:
3138         return ssl_tsan_load(ctx, &ctx->stats.sess_hit);
3139     case SSL_CTRL_SESS_CB_HIT:
3140         return ssl_tsan_load(ctx, &ctx->stats.sess_cb_hit);
3141     case SSL_CTRL_SESS_MISSES:
3142         return ssl_tsan_load(ctx, &ctx->stats.sess_miss);
3143     case SSL_CTRL_SESS_TIMEOUTS:
3144         return ssl_tsan_load(ctx, &ctx->stats.sess_timeout);
3145     case SSL_CTRL_SESS_CACHE_FULL:
3146         return ssl_tsan_load(ctx, &ctx->stats.sess_cache_full);
3147     case SSL_CTRL_MODE:
3148         return (ctx->mode |= larg);
3149     case SSL_CTRL_CLEAR_MODE:
3150         return (ctx->mode &= ~larg);
3151     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
3152         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
3153             return 0;
3154         ctx->max_send_fragment = larg;
3155         if (ctx->max_send_fragment < ctx->split_send_fragment)
3156             ctx->split_send_fragment = ctx->max_send_fragment;
3157         return 1;
3158     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
3159         if ((size_t)larg > ctx->max_send_fragment || larg == 0)
3160             return 0;
3161         ctx->split_send_fragment = larg;
3162         return 1;
3163     case SSL_CTRL_SET_MAX_PIPELINES:
3164         if (larg < 1 || larg > SSL_MAX_PIPELINES)
3165             return 0;
3166         ctx->max_pipelines = larg;
3167         return 1;
3168     case SSL_CTRL_CERT_FLAGS:
3169         return (ctx->cert->cert_flags |= larg);
3170     case SSL_CTRL_CLEAR_CERT_FLAGS:
3171         return (ctx->cert->cert_flags &= ~larg);
3172     case SSL_CTRL_SET_MIN_PROTO_VERSION:
3173         return ssl_check_allowed_versions(larg, ctx->max_proto_version)
3174                && ssl_set_version_bound(ctx->method->version, (int)larg,
3175                                         &ctx->min_proto_version);
3176     case SSL_CTRL_GET_MIN_PROTO_VERSION:
3177         return ctx->min_proto_version;
3178     case SSL_CTRL_SET_MAX_PROTO_VERSION:
3179         return ssl_check_allowed_versions(ctx->min_proto_version, larg)
3180                && ssl_set_version_bound(ctx->method->version, (int)larg,
3181                                         &ctx->max_proto_version);
3182     case SSL_CTRL_GET_MAX_PROTO_VERSION:
3183         return ctx->max_proto_version;
3184     default:
3185         return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
3186     }
3187 }
3188
3189 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
3190 {
3191     switch (cmd) {
3192     case SSL_CTRL_SET_MSG_CALLBACK:
3193         ctx->msg_callback = (void (*)
3194                              (int write_p, int version, int content_type,
3195                               const void *buf, size_t len, SSL *ssl,
3196                               void *arg))(fp);
3197         return 1;
3198
3199     default:
3200         return ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp);
3201     }
3202 }
3203
3204 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
3205 {
3206     if (a->id > b->id)
3207         return 1;
3208     if (a->id < b->id)
3209         return -1;
3210     return 0;
3211 }
3212
3213 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
3214                           const SSL_CIPHER *const *bp)
3215 {
3216     if ((*ap)->id > (*bp)->id)
3217         return 1;
3218     if ((*ap)->id < (*bp)->id)
3219         return -1;
3220     return 0;
3221 }
3222
3223 /*
3224  * return a STACK of the ciphers available for the SSL and in order of
3225  * preference
3226  */
3227 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
3228 {
3229     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3230
3231     if (sc != NULL) {
3232         if (sc->cipher_list != NULL) {
3233             return sc->cipher_list;
3234         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
3235             return s->ctx->cipher_list;
3236         }
3237     }
3238     return NULL;
3239 }
3240
3241 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
3242 {
3243     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3244
3245     if (sc == NULL || !sc->server)
3246         return NULL;
3247     return sc->peer_ciphers;
3248 }
3249
3250 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
3251 {
3252     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
3253     int i;
3254     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3255
3256     if (sc == NULL)
3257         return NULL;
3258
3259     ciphers = SSL_get_ciphers(s);
3260     if (!ciphers)
3261         return NULL;
3262     if (!ssl_set_client_disabled(sc))
3263         return NULL;
3264     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
3265         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
3266         if (!ssl_cipher_disabled(sc, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
3267             if (!sk)
3268                 sk = sk_SSL_CIPHER_new_null();
3269             if (!sk)
3270                 return NULL;
3271             if (!sk_SSL_CIPHER_push(sk, c)) {
3272                 sk_SSL_CIPHER_free(sk);
3273                 return NULL;
3274             }
3275         }
3276     }
3277     return sk;
3278 }
3279
3280 /** return a STACK of the ciphers available for the SSL and in order of
3281  * algorithm id */
3282 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL_CONNECTION *s)
3283 {
3284     if (s != NULL) {
3285         if (s->cipher_list_by_id != NULL)
3286             return s->cipher_list_by_id;
3287         else if (s->ssl.ctx != NULL
3288                  && s->ssl.ctx->cipher_list_by_id != NULL)
3289             return s->ssl.ctx->cipher_list_by_id;
3290     }
3291     return NULL;
3292 }
3293
3294 /** The old interface to get the same thing as SSL_get_ciphers() */
3295 const char *SSL_get_cipher_list(const SSL *s, int n)
3296 {
3297     const SSL_CIPHER *c;
3298     STACK_OF(SSL_CIPHER) *sk;
3299
3300     if (s == NULL)
3301         return NULL;
3302     sk = SSL_get_ciphers(s);
3303     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
3304         return NULL;
3305     c = sk_SSL_CIPHER_value(sk, n);
3306     if (c == NULL)
3307         return NULL;
3308     return c->name;
3309 }
3310
3311 /** return a STACK of the ciphers available for the SSL_CTX and in order of
3312  * preference */
3313 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
3314 {
3315     if (ctx != NULL)
3316         return ctx->cipher_list;
3317     return NULL;
3318 }
3319
3320 /*
3321  * Distinguish between ciphers controlled by set_ciphersuite() and
3322  * set_cipher_list() when counting.
3323  */
3324 static int cipher_list_tls12_num(STACK_OF(SSL_CIPHER) *sk)
3325 {
3326     int i, num = 0;
3327     const SSL_CIPHER *c;
3328
3329     if (sk == NULL)
3330         return 0;
3331     for (i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
3332         c = sk_SSL_CIPHER_value(sk, i);
3333         if (c->min_tls >= TLS1_3_VERSION)
3334             continue;
3335         num++;
3336     }
3337     return num;
3338 }
3339
3340 /** specify the ciphers to be used by default by the SSL_CTX */
3341 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
3342 {
3343     STACK_OF(SSL_CIPHER) *sk;
3344
3345     sk = ssl_create_cipher_list(ctx, ctx->tls13_ciphersuites,
3346                                 &ctx->cipher_list, &ctx->cipher_list_by_id, str,
3347                                 ctx->cert);
3348     /*
3349      * ssl_create_cipher_list may return an empty stack if it was unable to
3350      * find a cipher matching the given rule string (for example if the rule
3351      * string specifies a cipher which has been disabled). This is not an
3352      * error as far as ssl_create_cipher_list is concerned, and hence
3353      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
3354      */
3355     if (sk == NULL)
3356         return 0;
3357     else if (cipher_list_tls12_num(sk) == 0) {
3358         ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
3359         return 0;
3360     }
3361     return 1;
3362 }
3363
3364 /** specify the ciphers to be used by the SSL */
3365 int SSL_set_cipher_list(SSL *s, const char *str)
3366 {
3367     STACK_OF(SSL_CIPHER) *sk;
3368     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3369
3370     if (sc == NULL)
3371         return 0;
3372
3373     sk = ssl_create_cipher_list(s->ctx, sc->tls13_ciphersuites,
3374                                 &sc->cipher_list, &sc->cipher_list_by_id, str,
3375                                 sc->cert);
3376     /* see comment in SSL_CTX_set_cipher_list */
3377     if (sk == NULL)
3378         return 0;
3379     else if (cipher_list_tls12_num(sk) == 0) {
3380         ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
3381         return 0;
3382     }
3383     return 1;
3384 }
3385
3386 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size)
3387 {
3388     char *p;
3389     STACK_OF(SSL_CIPHER) *clntsk, *srvrsk;
3390     const SSL_CIPHER *c;
3391     int i;
3392     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3393
3394     if (sc == NULL)
3395         return NULL;
3396
3397     if (!sc->server
3398             || sc->peer_ciphers == NULL
3399             || size < 2)
3400         return NULL;
3401
3402     p = buf;
3403     clntsk = sc->peer_ciphers;
3404     srvrsk = SSL_get_ciphers(s);
3405     if (clntsk == NULL || srvrsk == NULL)
3406         return NULL;
3407
3408     if (sk_SSL_CIPHER_num(clntsk) == 0 || sk_SSL_CIPHER_num(srvrsk) == 0)
3409         return NULL;
3410
3411     for (i = 0; i < sk_SSL_CIPHER_num(clntsk); i++) {
3412         int n;
3413
3414         c = sk_SSL_CIPHER_value(clntsk, i);
3415         if (sk_SSL_CIPHER_find(srvrsk, c) < 0)
3416             continue;
3417
3418         n = OPENSSL_strnlen(c->name, size);
3419         if (n >= size) {
3420             if (p != buf)
3421                 --p;
3422             *p = '\0';
3423             return buf;
3424         }
3425         memcpy(p, c->name, n);
3426         p += n;
3427         *(p++) = ':';
3428         size -= n + 1;
3429     }
3430     p[-1] = '\0';
3431     return buf;
3432 }
3433
3434 /**
3435  * Return the requested servername (SNI) value. Note that the behaviour varies
3436  * depending on:
3437  * - whether this is called by the client or the server,
3438  * - if we are before or during/after the handshake,
3439  * - if a resumption or normal handshake is being attempted/has occurred
3440  * - whether we have negotiated TLSv1.2 (or below) or TLSv1.3
3441  *
3442  * Note that only the host_name type is defined (RFC 3546).
3443  */
3444 const char *SSL_get_servername(const SSL *s, const int type)
3445 {
3446     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3447     int server;
3448
3449     if (sc == NULL)
3450         return NULL;
3451
3452     /*
3453      * If we don't know if we are the client or the server yet then we assume
3454      * client.
3455      */
3456     server = sc->handshake_func == NULL ? 0 : sc->server;
3457
3458     if (type != TLSEXT_NAMETYPE_host_name)
3459         return NULL;
3460
3461     if (server) {
3462         /**
3463          * Server side
3464          * In TLSv1.3 on the server SNI is not associated with the session
3465          * but in TLSv1.2 or below it is.
3466          *
3467          * Before the handshake:
3468          *  - return NULL
3469          *
3470          * During/after the handshake (TLSv1.2 or below resumption occurred):
3471          * - If a servername was accepted by the server in the original
3472          *   handshake then it will return that servername, or NULL otherwise.
3473          *
3474          * During/after the handshake (TLSv1.2 or below resumption did not occur):
3475          * - The function will return the servername requested by the client in
3476          *   this handshake or NULL if none was requested.
3477          */
3478          if (sc->hit && !SSL_CONNECTION_IS_TLS13(sc))
3479             return sc->session->ext.hostname;
3480     } else {
3481         /**
3482          * Client side
3483          *
3484          * Before the handshake:
3485          *  - If a servername has been set via a call to
3486          *    SSL_set_tlsext_host_name() then it will return that servername
3487          *  - If one has not been set, but a TLSv1.2 resumption is being
3488          *    attempted and the session from the original handshake had a
3489          *    servername accepted by the server then it will return that
3490          *    servername
3491          *  - Otherwise it returns NULL
3492          *
3493          * During/after the handshake (TLSv1.2 or below resumption occurred):
3494          * - If the session from the original handshake had a servername accepted
3495          *   by the server then it will return that servername.
3496          * - Otherwise it returns the servername set via
3497          *   SSL_set_tlsext_host_name() (or NULL if it was not called).
3498          *
3499          * During/after the handshake (TLSv1.2 or below resumption did not occur):
3500          * - It will return the servername set via SSL_set_tlsext_host_name()
3501          *   (or NULL if it was not called).
3502          */
3503         if (SSL_in_before(s)) {
3504             if (sc->ext.hostname == NULL
3505                     && sc->session != NULL
3506                     && sc->session->ssl_version != TLS1_3_VERSION)
3507                 return sc->session->ext.hostname;
3508         } else {
3509             if (!SSL_CONNECTION_IS_TLS13(sc) && sc->hit
3510                 && sc->session->ext.hostname != NULL)
3511                 return sc->session->ext.hostname;
3512         }
3513     }
3514
3515     return sc->ext.hostname;
3516 }
3517
3518 int SSL_get_servername_type(const SSL *s)
3519 {
3520     if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)
3521         return TLSEXT_NAMETYPE_host_name;
3522     return -1;
3523 }
3524
3525 /*
3526  * SSL_select_next_proto implements the standard protocol selection. It is
3527  * expected that this function is called from the callback set by
3528  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
3529  * vector of 8-bit, length prefixed byte strings. The length byte itself is
3530  * not included in the length. A byte string of length 0 is invalid. No byte
3531  * string may be truncated. The current, but experimental algorithm for
3532  * selecting the protocol is: 1) If the server doesn't support NPN then this
3533  * is indicated to the callback. In this case, the client application has to
3534  * abort the connection or have a default application level protocol. 2) If
3535  * the server supports NPN, but advertises an empty list then the client
3536  * selects the first protocol in its list, but indicates via the API that this
3537  * fallback case was enacted. 3) Otherwise, the client finds the first
3538  * protocol in the server's list that it supports and selects this protocol.
3539  * This is because it's assumed that the server has better information about
3540  * which protocol a client should use. 4) If the client doesn't support any
3541  * of the server's advertised protocols, then this is treated the same as
3542  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
3543  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
3544  */
3545 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
3546                           const unsigned char *server,
3547                           unsigned int server_len,
3548                           const unsigned char *client, unsigned int client_len)
3549 {
3550     unsigned int i, j;
3551     const unsigned char *result;
3552     int status = OPENSSL_NPN_UNSUPPORTED;
3553
3554     /*
3555      * For each protocol in server preference order, see if we support it.
3556      */
3557     for (i = 0; i < server_len;) {
3558         for (j = 0; j < client_len;) {
3559             if (server[i] == client[j] &&
3560                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
3561                 /* We found a match */
3562                 result = &server[i];
3563                 status = OPENSSL_NPN_NEGOTIATED;
3564                 goto found;
3565             }
3566             j += client[j];
3567             j++;
3568         }
3569         i += server[i];
3570         i++;
3571     }
3572
3573     /* There's no overlap between our protocols and the server's list. */
3574     result = client;
3575     status = OPENSSL_NPN_NO_OVERLAP;
3576
3577  found:
3578     *out = (unsigned char *)result + 1;
3579     *outlen = result[0];
3580     return status;
3581 }
3582
3583 #ifndef OPENSSL_NO_NEXTPROTONEG
3584 /*
3585  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
3586  * client's requested protocol for this connection and returns 0. If the
3587  * client didn't request any protocol, then *data is set to NULL. Note that
3588  * the client can request any protocol it chooses. The value returned from
3589  * this function need not be a member of the list of supported protocols
3590  * provided by the callback.
3591  */
3592 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
3593                                     unsigned *len)
3594 {
3595     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3596
3597     if (sc == NULL) {
3598         /* We have no other way to indicate error */
3599         *data = NULL;
3600         *len = 0;
3601         return;
3602     }
3603
3604     *data = sc->ext.npn;
3605     if (*data == NULL) {
3606         *len = 0;
3607     } else {
3608         *len = (unsigned int)sc->ext.npn_len;
3609     }
3610 }
3611
3612 /*
3613  * SSL_CTX_set_npn_advertised_cb sets a callback that is called when
3614  * a TLS server needs a list of supported protocols for Next Protocol
3615  * Negotiation. The returned list must be in wire format.  The list is
3616  * returned by setting |out| to point to it and |outlen| to its length. This
3617  * memory will not be modified, but one should assume that the SSL* keeps a
3618  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
3619  * wishes to advertise. Otherwise, no such extension will be included in the
3620  * ServerHello.
3621  */
3622 void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
3623                                    SSL_CTX_npn_advertised_cb_func cb,
3624                                    void *arg)
3625 {
3626     if (IS_QUIC_CTX(ctx))
3627         /* NPN not allowed for QUIC */
3628         return;
3629
3630     ctx->ext.npn_advertised_cb = cb;
3631     ctx->ext.npn_advertised_cb_arg = arg;
3632 }
3633
3634 /*
3635  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
3636  * client needs to select a protocol from the server's provided list. |out|
3637  * must be set to point to the selected protocol (which may be within |in|).
3638  * The length of the protocol name must be written into |outlen|. The
3639  * server's advertised protocols are provided in |in| and |inlen|. The
3640  * callback can assume that |in| is syntactically valid. The client must
3641  * select a protocol. It is fatal to the connection if this callback returns
3642  * a value other than SSL_TLSEXT_ERR_OK.
3643  */
3644 void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
3645                                SSL_CTX_npn_select_cb_func cb,
3646                                void *arg)
3647 {
3648     if (IS_QUIC_CTX(ctx))
3649         /* NPN not allowed for QUIC */
3650         return;
3651
3652     ctx->ext.npn_select_cb = cb;
3653     ctx->ext.npn_select_cb_arg = arg;
3654 }
3655 #endif
3656
3657 static int alpn_value_ok(const unsigned char *protos, unsigned int protos_len)
3658 {
3659     unsigned int idx;
3660
3661     if (protos_len < 2 || protos == NULL)
3662         return 0;
3663
3664     for (idx = 0; idx < protos_len; idx += protos[idx] + 1) {
3665         if (protos[idx] == 0)
3666             return 0;
3667     }
3668     return idx == protos_len;
3669 }
3670 /*
3671  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
3672  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
3673  * length-prefixed strings). Returns 0 on success.
3674  */
3675 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
3676                             unsigned int protos_len)
3677 {
3678     unsigned char *alpn;
3679
3680     if (protos_len == 0 || protos == NULL) {
3681         OPENSSL_free(ctx->ext.alpn);
3682         ctx->ext.alpn = NULL;
3683         ctx->ext.alpn_len = 0;
3684         return 0;
3685     }
3686     /* Not valid per RFC */
3687     if (!alpn_value_ok(protos, protos_len))
3688         return 1;
3689
3690     alpn = OPENSSL_memdup(protos, protos_len);
3691     if (alpn == NULL)
3692         return 1;
3693     OPENSSL_free(ctx->ext.alpn);
3694     ctx->ext.alpn = alpn;
3695     ctx->ext.alpn_len = protos_len;
3696
3697     return 0;
3698 }
3699
3700 /*
3701  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
3702  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
3703  * length-prefixed strings). Returns 0 on success.
3704  */
3705 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
3706                         unsigned int protos_len)
3707 {
3708     unsigned char *alpn;
3709     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
3710
3711     if (sc == NULL)
3712         return 1;
3713
3714     if (protos_len == 0 || protos == NULL) {
3715         OPENSSL_free(sc->ext.alpn);
3716         sc->ext.alpn = NULL;
3717         sc->ext.alpn_len = 0;
3718         return 0;
3719     }
3720     /* Not valid per RFC */
3721     if (!alpn_value_ok(protos, protos_len))
3722         return 1;
3723
3724     alpn = OPENSSL_memdup(protos, protos_len);
3725     if (alpn == NULL)
3726         return 1;
3727     OPENSSL_free(sc->ext.alpn);
3728     sc->ext.alpn = alpn;
3729     sc->ext.alpn_len = protos_len;
3730
3731     return 0;
3732 }
3733
3734 /*
3735  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
3736  * called during ClientHello processing in order to select an ALPN protocol
3737  * from the client's list of offered protocols.
3738  */
3739 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
3740                                 SSL_CTX_alpn_select_cb_func cb,
3741                                 void *arg)
3742 {
3743     ctx->ext.alpn_select_cb = cb;
3744     ctx->ext.alpn_select_cb_arg = arg;
3745 }
3746
3747 /*
3748  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
3749  * On return it sets |*data| to point to |*len| bytes of protocol name
3750  * (not including the leading length-prefix byte). If the server didn't
3751  * respond with a negotiated protocol then |*len| will be zero.
3752  */
3753 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
3754                             unsigned int *len)
3755 {
3756     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
3757
3758     if (sc == NULL) {
3759         /* We have no other way to indicate error */
3760         *data = NULL;
3761         *len = 0;
3762         return;
3763     }
3764
3765     *data = sc->s3.alpn_selected;
3766     if (*data == NULL)
3767         *len = 0;
3768     else
3769         *len = (unsigned int)sc->s3.alpn_selected_len;
3770 }
3771
3772 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
3773                                const char *label, size_t llen,
3774                                const unsigned char *context, size_t contextlen,
3775                                int use_context)
3776 {
3777     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3778
3779     if (sc == NULL)
3780         return -1;
3781
3782     if (sc->session == NULL
3783         || (sc->version < TLS1_VERSION && sc->version != DTLS1_BAD_VER))
3784         return -1;
3785
3786     return s->method->ssl3_enc->export_keying_material(sc, out, olen, label,
3787                                                        llen, context,
3788                                                        contextlen, use_context);
3789 }
3790
3791 int SSL_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
3792                                      const char *label, size_t llen,
3793                                      const unsigned char *context,
3794                                      size_t contextlen)
3795 {
3796     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3797
3798     if (sc == NULL)
3799         return -1;
3800
3801     if (sc->version != TLS1_3_VERSION)
3802         return 0;
3803
3804     return tls13_export_keying_material_early(sc, out, olen, label, llen,
3805                                               context, contextlen);
3806 }
3807
3808 static unsigned long ssl_session_hash(const SSL_SESSION *a)
3809 {
3810     const unsigned char *session_id = a->session_id;
3811     unsigned long l;
3812     unsigned char tmp_storage[4];
3813
3814     if (a->session_id_length < sizeof(tmp_storage)) {
3815         memset(tmp_storage, 0, sizeof(tmp_storage));
3816         memcpy(tmp_storage, a->session_id, a->session_id_length);
3817         session_id = tmp_storage;
3818     }
3819
3820     l = (unsigned long)
3821         ((unsigned long)session_id[0]) |
3822         ((unsigned long)session_id[1] << 8L) |
3823         ((unsigned long)session_id[2] << 16L) |
3824         ((unsigned long)session_id[3] << 24L);
3825     return l;
3826 }
3827
3828 /*
3829  * NB: If this function (or indeed the hash function which uses a sort of
3830  * coarser function than this one) is changed, ensure
3831  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
3832  * being able to construct an SSL_SESSION that will collide with any existing
3833  * session with a matching session ID.
3834  */
3835 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
3836 {
3837     if (a->ssl_version != b->ssl_version)
3838         return 1;
3839     if (a->session_id_length != b->session_id_length)
3840         return 1;
3841     return memcmp(a->session_id, b->session_id, a->session_id_length);
3842 }
3843
3844 /*
3845  * These wrapper functions should remain rather than redeclaring
3846  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
3847  * variable. The reason is that the functions aren't static, they're exposed
3848  * via ssl.h.
3849  */
3850
3851 SSL_CTX *SSL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
3852                         const SSL_METHOD *meth)
3853 {
3854     SSL_CTX *ret = NULL;
3855 #ifndef OPENSSL_NO_COMP_ALG
3856     int i;
3857 #endif
3858
3859     if (meth == NULL) {
3860         ERR_raise(ERR_LIB_SSL, SSL_R_NULL_SSL_METHOD_PASSED);
3861         return NULL;
3862     }
3863
3864     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
3865         return NULL;
3866
3867     /* Doing this for the run once effect */
3868     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
3869         ERR_raise(ERR_LIB_SSL, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
3870         goto err;
3871     }
3872
3873     ret = OPENSSL_zalloc(sizeof(*ret));
3874     if (ret == NULL)
3875         return NULL;
3876
3877     /* Init the reference counting before any call to SSL_CTX_free */
3878     if (!CRYPTO_NEW_REF(&ret->references, 1)) {
3879         OPENSSL_free(ret);
3880         return NULL;
3881     }
3882
3883     ret->lock = CRYPTO_THREAD_lock_new();
3884     if (ret->lock == NULL) {
3885         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3886         goto err;
3887     }
3888
3889 #ifdef TSAN_REQUIRES_LOCKING
3890     ret->tsan_lock = CRYPTO_THREAD_lock_new();
3891     if (ret->tsan_lock == NULL) {
3892         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3893         goto err;
3894     }
3895 #endif
3896
3897     ret->libctx = libctx;
3898     if (propq != NULL) {
3899         ret->propq = OPENSSL_strdup(propq);
3900         if (ret->propq == NULL)
3901             goto err;
3902     }
3903
3904     ret->method = meth;
3905     ret->min_proto_version = 0;
3906     ret->max_proto_version = 0;
3907     ret->mode = SSL_MODE_AUTO_RETRY;
3908     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
3909     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
3910     /* We take the system default. */
3911     ret->session_timeout = meth->get_timeout();
3912     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
3913     ret->verify_mode = SSL_VERIFY_NONE;
3914
3915     ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
3916     if (ret->sessions == NULL) {
3917         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3918         goto err;
3919     }
3920     ret->cert_store = X509_STORE_new();
3921     if (ret->cert_store == NULL) {
3922         ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
3923         goto err;
3924     }
3925 #ifndef OPENSSL_NO_CT
3926     ret->ctlog_store = CTLOG_STORE_new_ex(libctx, propq);
3927     if (ret->ctlog_store == NULL) {
3928         ERR_raise(ERR_LIB_SSL, ERR_R_CT_LIB);
3929         goto err;
3930     }
3931 #endif
3932
3933     /* initialize cipher/digest methods table */
3934     if (!ssl_load_ciphers(ret)) {
3935         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3936         goto err;
3937     }
3938
3939     if (!ssl_load_groups(ret)) {
3940         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3941         goto err;
3942     }
3943
3944     /* load provider sigalgs */
3945     if (!ssl_load_sigalgs(ret)) {
3946         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3947         goto err;
3948     }
3949
3950     /* initialise sig algs */
3951     if (!ssl_setup_sigalgs(ret)) {
3952         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3953         goto err;
3954     }
3955
3956     if (!SSL_CTX_set_ciphersuites(ret, OSSL_default_ciphersuites())) {
3957         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3958         goto err;
3959     }
3960
3961     if ((ret->cert = ssl_cert_new(SSL_PKEY_NUM + ret->sigalg_list_len)) == NULL) {
3962         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3963         goto err;
3964     }
3965
3966     if (!ssl_create_cipher_list(ret,
3967                                 ret->tls13_ciphersuites,
3968                                 &ret->cipher_list, &ret->cipher_list_by_id,
3969                                 OSSL_default_cipher_list(), ret->cert)
3970         || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
3971         ERR_raise(ERR_LIB_SSL, SSL_R_LIBRARY_HAS_NO_CIPHERS);
3972         goto err;
3973     }
3974
3975     ret->param = X509_VERIFY_PARAM_new();
3976     if (ret->param == NULL) {
3977         ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
3978         goto err;
3979     }
3980
3981     /*
3982      * If these aren't available from the provider we'll get NULL returns.
3983      * That's fine but will cause errors later if SSLv3 is negotiated
3984      */
3985     ret->md5 = ssl_evp_md_fetch(libctx, NID_md5, propq);
3986     ret->sha1 = ssl_evp_md_fetch(libctx, NID_sha1, propq);
3987
3988     if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL) {
3989         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3990         goto err;
3991     }
3992
3993     if ((ret->client_ca_names = sk_X509_NAME_new_null()) == NULL) {
3994         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3995         goto err;
3996     }
3997
3998     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data)) {
3999         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
4000         goto err;
4001     }
4002
4003     if ((ret->ext.secure = OPENSSL_secure_zalloc(sizeof(*ret->ext.secure))) == NULL)
4004         goto err;
4005
4006     /* No compression for DTLS */
4007     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
4008         ret->comp_methods = SSL_COMP_get_compression_methods();
4009
4010     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
4011     ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
4012
4013     /* Setup RFC5077 ticket keys */
4014     if ((RAND_bytes_ex(libctx, ret->ext.tick_key_name,
4015                        sizeof(ret->ext.tick_key_name), 0) <= 0)
4016         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_hmac_key,
4017                                sizeof(ret->ext.secure->tick_hmac_key), 0) <= 0)
4018         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_aes_key,
4019                                sizeof(ret->ext.secure->tick_aes_key), 0) <= 0))
4020         ret->options |= SSL_OP_NO_TICKET;
4021
4022     if (RAND_priv_bytes_ex(libctx, ret->ext.cookie_hmac_key,
4023                            sizeof(ret->ext.cookie_hmac_key), 0) <= 0) {
4024         ERR_raise(ERR_LIB_SSL, ERR_R_RAND_LIB);
4025         goto err;
4026     }
4027
4028 #ifndef OPENSSL_NO_SRP
4029     if (!ssl_ctx_srp_ctx_init_intern(ret)) {
4030         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
4031         goto err;
4032     }
4033 #endif
4034 #ifndef OPENSSL_NO_ENGINE
4035 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
4036 #  define eng_strx(x)     #x
4037 #  define eng_str(x)      eng_strx(x)
4038     /* Use specific client engine automatically... ignore errors */
4039     {
4040         ENGINE *eng;
4041         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
4042         if (!eng) {
4043             ERR_clear_error();
4044             ENGINE_load_builtin_engines();
4045             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
4046         }
4047         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
4048             ERR_clear_error();
4049     }
4050 # endif
4051 #endif
4052
4053 #ifndef OPENSSL_NO_COMP_ALG
4054     /*
4055      * Set the default order: brotli, zlib, zstd
4056      * Including only those enabled algorithms
4057      */
4058     memset(ret->cert_comp_prefs, 0, sizeof(ret->cert_comp_prefs));
4059     i = 0;
4060     if (ossl_comp_has_alg(TLSEXT_comp_cert_brotli))
4061         ret->cert_comp_prefs[i++] = TLSEXT_comp_cert_brotli;
4062     if (ossl_comp_has_alg(TLSEXT_comp_cert_zlib))
4063         ret->cert_comp_prefs[i++] = TLSEXT_comp_cert_zlib;
4064     if (ossl_comp_has_alg(TLSEXT_comp_cert_zstd))
4065         ret->cert_comp_prefs[i++] = TLSEXT_comp_cert_zstd;
4066 #endif
4067     /*
4068      * Disable compression by default to prevent CRIME. Applications can
4069      * re-enable compression by configuring
4070      * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
4071      * or by using the SSL_CONF library. Similarly we also enable TLSv1.3
4072      * middlebox compatibility by default. This may be disabled by default in
4073      * a later OpenSSL version.
4074      */
4075     ret->options |= SSL_OP_NO_COMPRESSION | SSL_OP_ENABLE_MIDDLEBOX_COMPAT;
4076
4077     ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
4078
4079     /*
4080      * We cannot usefully set a default max_early_data here (which gets
4081      * propagated in SSL_new(), for the following reason: setting the
4082      * SSL field causes tls_construct_stoc_early_data() to tell the
4083      * client that early data will be accepted when constructing a TLS 1.3
4084      * session ticket, and the client will accordingly send us early data
4085      * when using that ticket (if the client has early data to send).
4086      * However, in order for the early data to actually be consumed by
4087      * the application, the application must also have calls to
4088      * SSL_read_early_data(); otherwise we'll just skip past the early data
4089      * and ignore it.  So, since the application must add calls to
4090      * SSL_read_early_data(), we also require them to add
4091      * calls to SSL_CTX_set_max_early_data() in order to use early data,
4092      * eliminating the bandwidth-wasting early data in the case described
4093      * above.
4094      */
4095     ret->max_early_data = 0;
4096
4097     /*
4098      * Default recv_max_early_data is a fully loaded single record. Could be
4099      * split across multiple records in practice. We set this differently to
4100      * max_early_data so that, in the default case, we do not advertise any
4101      * support for early_data, but if a client were to send us some (e.g.
4102      * because of an old, stale ticket) then we will tolerate it and skip over
4103      * it.
4104      */
4105     ret->recv_max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
4106
4107     /* By default we send two session tickets automatically in TLSv1.3 */
4108     ret->num_tickets = 2;
4109
4110     ssl_ctx_system_config(ret);
4111
4112     return ret;
4113  err:
4114     SSL_CTX_free(ret);
4115     return NULL;
4116 }
4117
4118 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
4119 {
4120     return SSL_CTX_new_ex(NULL, NULL, meth);
4121 }
4122
4123 int SSL_CTX_up_ref(SSL_CTX *ctx)
4124 {
4125     int i;
4126
4127     if (CRYPTO_UP_REF(&ctx->references, &i) <= 0)
4128         return 0;
4129
4130     REF_PRINT_COUNT("SSL_CTX", ctx);
4131     REF_ASSERT_ISNT(i < 2);
4132     return ((i > 1) ? 1 : 0);
4133 }
4134
4135 void SSL_CTX_free(SSL_CTX *a)
4136 {
4137     int i;
4138     size_t j;
4139
4140     if (a == NULL)
4141         return;
4142
4143     CRYPTO_DOWN_REF(&a->references, &i);
4144     REF_PRINT_COUNT("SSL_CTX", a);
4145     if (i > 0)
4146         return;
4147     REF_ASSERT_ISNT(i < 0);
4148
4149     X509_VERIFY_PARAM_free(a->param);
4150     dane_ctx_final(&a->dane);
4151
4152     /*
4153      * Free internal session cache. However: the remove_cb() may reference
4154      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
4155      * after the sessions were flushed.
4156      * As the ex_data handling routines might also touch the session cache,
4157      * the most secure solution seems to be: empty (flush) the cache, then
4158      * free ex_data, then finally free the cache.
4159      * (See ticket [openssl.org #212].)
4160      */
4161     if (a->sessions != NULL)
4162         SSL_CTX_flush_sessions(a, 0);
4163
4164     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
4165     lh_SSL_SESSION_free(a->sessions);
4166     X509_STORE_free(a->cert_store);
4167 #ifndef OPENSSL_NO_CT
4168     CTLOG_STORE_free(a->ctlog_store);
4169 #endif
4170     sk_SSL_CIPHER_free(a->cipher_list);
4171     sk_SSL_CIPHER_free(a->cipher_list_by_id);
4172     sk_SSL_CIPHER_free(a->tls13_ciphersuites);
4173     ssl_cert_free(a->cert);
4174     sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
4175     sk_X509_NAME_pop_free(a->client_ca_names, X509_NAME_free);
4176     OSSL_STACK_OF_X509_free(a->extra_certs);
4177     a->comp_methods = NULL;
4178 #ifndef OPENSSL_NO_SRTP
4179     sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
4180 #endif
4181 #ifndef OPENSSL_NO_SRP
4182     ssl_ctx_srp_ctx_free_intern(a);
4183 #endif
4184 #ifndef OPENSSL_NO_ENGINE
4185     tls_engine_finish(a->client_cert_engine);
4186 #endif
4187
4188     OPENSSL_free(a->ext.ecpointformats);
4189     OPENSSL_free(a->ext.supportedgroups);
4190     OPENSSL_free(a->ext.supported_groups_default);
4191     OPENSSL_free(a->ext.alpn);
4192     OPENSSL_secure_free(a->ext.secure);
4193
4194     ssl_evp_md_free(a->md5);
4195     ssl_evp_md_free(a->sha1);
4196
4197     for (j = 0; j < SSL_ENC_NUM_IDX; j++)
4198         ssl_evp_cipher_free(a->ssl_cipher_methods[j]);
4199     for (j = 0; j < SSL_MD_NUM_IDX; j++)
4200         ssl_evp_md_free(a->ssl_digest_methods[j]);
4201     for (j = 0; j < a->group_list_len; j++) {
4202         OPENSSL_free(a->group_list[j].tlsname);
4203         OPENSSL_free(a->group_list[j].realname);
4204         OPENSSL_free(a->group_list[j].algorithm);
4205     }
4206     OPENSSL_free(a->group_list);
4207     for (j = 0; j < a->sigalg_list_len; j++) {
4208         OPENSSL_free(a->sigalg_list[j].name);
4209         OPENSSL_free(a->sigalg_list[j].sigalg_name);
4210         OPENSSL_free(a->sigalg_list[j].sigalg_oid);
4211         OPENSSL_free(a->sigalg_list[j].sig_name);
4212         OPENSSL_free(a->sigalg_list[j].sig_oid);
4213         OPENSSL_free(a->sigalg_list[j].hash_name);
4214         OPENSSL_free(a->sigalg_list[j].hash_oid);
4215         OPENSSL_free(a->sigalg_list[j].keytype);
4216         OPENSSL_free(a->sigalg_list[j].keytype_oid);
4217     }
4218     OPENSSL_free(a->sigalg_list);
4219     OPENSSL_free(a->ssl_cert_info);
4220
4221     OPENSSL_free(a->sigalg_lookup_cache);
4222     OPENSSL_free(a->tls12_sigalgs);
4223
4224     OPENSSL_free(a->client_cert_type);
4225     OPENSSL_free(a->server_cert_type);
4226
4227     CRYPTO_THREAD_lock_free(a->lock);
4228     CRYPTO_FREE_REF(&a->references);
4229 #ifdef TSAN_REQUIRES_LOCKING
4230     CRYPTO_THREAD_lock_free(a->tsan_lock);
4231 #endif
4232
4233     OPENSSL_free(a->propq);
4234
4235     OPENSSL_free(a);
4236 }
4237
4238 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
4239 {
4240     ctx->default_passwd_callback = cb;
4241 }
4242
4243 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
4244 {
4245     ctx->default_passwd_callback_userdata = u;
4246 }
4247
4248 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
4249 {
4250     return ctx->default_passwd_callback;
4251 }
4252
4253 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
4254 {
4255     return ctx->default_passwd_callback_userdata;
4256 }
4257
4258 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
4259 {
4260     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4261
4262     if (sc == NULL)
4263         return;
4264
4265     sc->default_passwd_callback = cb;
4266 }
4267
4268 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
4269 {
4270     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4271
4272     if (sc == NULL)
4273         return;
4274
4275     sc->default_passwd_callback_userdata = u;
4276 }
4277
4278 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
4279 {
4280     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4281
4282     if (sc == NULL)
4283         return NULL;
4284
4285     return sc->default_passwd_callback;
4286 }
4287
4288 void *SSL_get_default_passwd_cb_userdata(SSL *s)
4289 {
4290     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4291
4292     if (sc == NULL)
4293         return NULL;
4294
4295     return sc->default_passwd_callback_userdata;
4296 }
4297
4298 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
4299                                       int (*cb) (X509_STORE_CTX *, void *),
4300                                       void *arg)
4301 {
4302     ctx->app_verify_callback = cb;
4303     ctx->app_verify_arg = arg;
4304 }
4305
4306 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
4307                         int (*cb) (int, X509_STORE_CTX *))
4308 {
4309     ctx->verify_mode = mode;
4310     ctx->default_verify_callback = cb;
4311 }
4312
4313 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
4314 {
4315     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
4316 }
4317
4318 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
4319 {
4320     ssl_cert_set_cert_cb(c->cert, cb, arg);
4321 }
4322
4323 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
4324 {
4325     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4326
4327     if (sc == NULL)
4328         return;
4329
4330     ssl_cert_set_cert_cb(sc->cert, cb, arg);
4331 }
4332
4333 void ssl_set_masks(SSL_CONNECTION *s)
4334 {
4335     CERT *c = s->cert;
4336     uint32_t *pvalid = s->s3.tmp.valid_flags;
4337     int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
4338     unsigned long mask_k, mask_a;
4339     int have_ecc_cert, ecdsa_ok;
4340
4341     if (c == NULL)
4342         return;
4343
4344     dh_tmp = (c->dh_tmp != NULL
4345               || c->dh_tmp_cb != NULL
4346               || c->dh_tmp_auto);
4347
4348     rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
4349     rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
4350     dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
4351     have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
4352     mask_k = 0;
4353     mask_a = 0;
4354
4355     OSSL_TRACE4(TLS_CIPHER, "dh_tmp=%d rsa_enc=%d rsa_sign=%d dsa_sign=%d\n",
4356                dh_tmp, rsa_enc, rsa_sign, dsa_sign);
4357
4358 #ifndef OPENSSL_NO_GOST
4359     if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
4360         mask_k |= SSL_kGOST | SSL_kGOST18;
4361         mask_a |= SSL_aGOST12;
4362     }
4363     if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
4364         mask_k |= SSL_kGOST | SSL_kGOST18;
4365         mask_a |= SSL_aGOST12;
4366     }
4367     if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
4368         mask_k |= SSL_kGOST;
4369         mask_a |= SSL_aGOST01;
4370     }
4371 #endif
4372
4373     if (rsa_enc)
4374         mask_k |= SSL_kRSA;
4375
4376     if (dh_tmp)
4377         mask_k |= SSL_kDHE;
4378
4379     /*
4380      * If we only have an RSA-PSS certificate allow RSA authentication
4381      * if TLS 1.2 and peer supports it.
4382      */
4383
4384     if (rsa_enc || rsa_sign || (ssl_has_cert(s, SSL_PKEY_RSA_PSS_SIGN)
4385                 && pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_EXPLICIT_SIGN
4386                 && TLS1_get_version(&s->ssl) == TLS1_2_VERSION))
4387         mask_a |= SSL_aRSA;
4388
4389     if (dsa_sign) {
4390         mask_a |= SSL_aDSS;
4391     }
4392
4393     mask_a |= SSL_aNULL;
4394
4395     /*
4396      * You can do anything with an RPK key, since there's no cert to restrict it
4397      * But we need to check for private keys
4398      */
4399     if (pvalid[SSL_PKEY_RSA] & CERT_PKEY_RPK) {
4400         mask_a |= SSL_aRSA;
4401         mask_k |= SSL_kRSA;
4402     }
4403     if (pvalid[SSL_PKEY_ECC] & CERT_PKEY_RPK)
4404         mask_a |= SSL_aECDSA;
4405     if (TLS1_get_version(&s->ssl) == TLS1_2_VERSION) {
4406         if (pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_RPK)
4407             mask_a |= SSL_aRSA;
4408         if (pvalid[SSL_PKEY_ED25519] & CERT_PKEY_RPK
4409                 || pvalid[SSL_PKEY_ED448] & CERT_PKEY_RPK)
4410             mask_a |= SSL_aECDSA;
4411     }
4412
4413     /*
4414      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
4415      * depending on the key usage extension.
4416      */
4417     if (have_ecc_cert) {
4418         uint32_t ex_kusage;
4419         ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
4420         ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
4421         if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
4422             ecdsa_ok = 0;
4423         if (ecdsa_ok)
4424             mask_a |= SSL_aECDSA;
4425     }
4426     /* Allow Ed25519 for TLS 1.2 if peer supports it */
4427     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
4428             && pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
4429             && TLS1_get_version(&s->ssl) == TLS1_2_VERSION)
4430             mask_a |= SSL_aECDSA;
4431
4432     /* Allow Ed448 for TLS 1.2 if peer supports it */
4433     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED448)
4434             && pvalid[SSL_PKEY_ED448] & CERT_PKEY_EXPLICIT_SIGN
4435             && TLS1_get_version(&s->ssl) == TLS1_2_VERSION)
4436             mask_a |= SSL_aECDSA;
4437
4438     mask_k |= SSL_kECDHE;
4439
4440 #ifndef OPENSSL_NO_PSK
4441     mask_k |= SSL_kPSK;
4442     mask_a |= SSL_aPSK;
4443     if (mask_k & SSL_kRSA)
4444         mask_k |= SSL_kRSAPSK;
4445     if (mask_k & SSL_kDHE)
4446         mask_k |= SSL_kDHEPSK;
4447     if (mask_k & SSL_kECDHE)
4448         mask_k |= SSL_kECDHEPSK;
4449 #endif
4450
4451     s->s3.tmp.mask_k = mask_k;
4452     s->s3.tmp.mask_a = mask_a;
4453 }
4454
4455 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL_CONNECTION *s)
4456 {
4457     if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
4458         /* key usage, if present, must allow signing */
4459         if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
4460             ERR_raise(ERR_LIB_SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
4461             return 0;
4462         }
4463     }
4464     return 1;                   /* all checks are ok */
4465 }
4466
4467 int ssl_get_server_cert_serverinfo(SSL_CONNECTION *s,
4468                                    const unsigned char **serverinfo,
4469                                    size_t *serverinfo_length)
4470 {
4471     CERT_PKEY *cpk = s->s3.tmp.cert;
4472     *serverinfo_length = 0;
4473
4474     if (cpk == NULL || cpk->serverinfo == NULL)
4475         return 0;
4476
4477     *serverinfo = cpk->serverinfo;
4478     *serverinfo_length = cpk->serverinfo_length;
4479     return 1;
4480 }
4481
4482 void ssl_update_cache(SSL_CONNECTION *s, int mode)
4483 {
4484     int i;
4485
4486     /*
4487      * If the session_id_length is 0, we are not supposed to cache it, and it
4488      * would be rather hard to do anyway :-)
4489      */
4490     if (s->session->session_id_length == 0)
4491         return;
4492
4493     /*
4494      * If sid_ctx_length is 0 there is no specific application context
4495      * associated with this session, so when we try to resume it and
4496      * SSL_VERIFY_PEER is requested to verify the client identity, we have no
4497      * indication that this is actually a session for the proper application
4498      * context, and the *handshake* will fail, not just the resumption attempt.
4499      * Do not cache (on the server) these sessions that are not resumable
4500      * (clients can set SSL_VERIFY_PEER without needing a sid_ctx set).
4501      */
4502     if (s->server && s->session->sid_ctx_length == 0
4503             && (s->verify_mode & SSL_VERIFY_PEER) != 0)
4504         return;
4505
4506     i = s->session_ctx->session_cache_mode;
4507     if ((i & mode) != 0
4508         && (!s->hit || SSL_CONNECTION_IS_TLS13(s))) {
4509         /*
4510          * Add the session to the internal cache. In server side TLSv1.3 we
4511          * normally don't do this because by default it's a full stateless ticket
4512          * with only a dummy session id so there is no reason to cache it,
4513          * unless:
4514          * - we are doing early_data, in which case we cache so that we can
4515          *   detect replays
4516          * - the application has set a remove_session_cb so needs to know about
4517          *   session timeout events
4518          * - SSL_OP_NO_TICKET is set in which case it is a stateful ticket
4519          */
4520         if ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0
4521                 && (!SSL_CONNECTION_IS_TLS13(s)
4522                     || !s->server
4523                     || (s->max_early_data > 0
4524                         && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0)
4525                     || s->session_ctx->remove_session_cb != NULL
4526                     || (s->options & SSL_OP_NO_TICKET) != 0))
4527             SSL_CTX_add_session(s->session_ctx, s->session);
4528
4529         /*
4530          * Add the session to the external cache. We do this even in server side
4531          * TLSv1.3 without early data because some applications just want to
4532          * know about the creation of a session and aren't doing a full cache.
4533          */
4534         if (s->session_ctx->new_session_cb != NULL) {
4535             SSL_SESSION_up_ref(s->session);
4536             if (!s->session_ctx->new_session_cb(SSL_CONNECTION_GET_SSL(s),
4537                                                 s->session))
4538                 SSL_SESSION_free(s->session);
4539         }
4540     }
4541
4542     /* auto flush every 255 connections */
4543     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
4544         TSAN_QUALIFIER int *stat;
4545
4546         if (mode & SSL_SESS_CACHE_CLIENT)
4547             stat = &s->session_ctx->stats.sess_connect_good;
4548         else
4549             stat = &s->session_ctx->stats.sess_accept_good;
4550         if ((ssl_tsan_load(s->session_ctx, stat) & 0xff) == 0xff)
4551             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
4552     }
4553 }
4554
4555 const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx)
4556 {
4557     return ctx->method;
4558 }
4559
4560 const SSL_METHOD *SSL_get_ssl_method(const SSL *s)
4561 {
4562     return s->method;
4563 }
4564
4565 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
4566 {
4567     int ret = 1;
4568     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4569
4570     /* Not allowed for QUIC */
4571     if (sc == NULL
4572         || (s->type != SSL_TYPE_SSL_CONNECTION && s->method != meth)
4573         || (s->type == SSL_TYPE_SSL_CONNECTION && IS_QUIC_METHOD(meth)))
4574         return 0;
4575
4576     if (s->method != meth) {
4577         const SSL_METHOD *sm = s->method;
4578         int (*hf) (SSL *) = sc->handshake_func;
4579
4580         if (sm->version == meth->version)
4581             s->method = meth;
4582         else {
4583             sm->ssl_deinit(s);
4584             s->method = meth;
4585             ret = s->method->ssl_init(s);
4586         }
4587
4588         if (hf == sm->ssl_connect)
4589             sc->handshake_func = meth->ssl_connect;
4590         else if (hf == sm->ssl_accept)
4591             sc->handshake_func = meth->ssl_accept;
4592     }
4593     return ret;
4594 }
4595
4596 int SSL_get_error(const SSL *s, int i)
4597 {
4598     return ossl_ssl_get_error(s, i, /*check_err=*/1);
4599 }
4600
4601 int ossl_ssl_get_error(const SSL *s, int i, int check_err)
4602 {
4603     int reason;
4604     unsigned long l;
4605     BIO *bio;
4606     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4607
4608     if (i > 0)
4609         return SSL_ERROR_NONE;
4610
4611 #ifndef OPENSSL_NO_QUIC
4612     if (IS_QUIC(s)) {
4613         reason = ossl_quic_get_error(s, i);
4614         if (reason != SSL_ERROR_NONE)
4615             return reason;
4616     }
4617 #endif
4618
4619     if (sc == NULL)
4620         return SSL_ERROR_SSL;
4621
4622     /*
4623      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
4624      * where we do encode the error
4625      */
4626     if (check_err && (l = ERR_peek_error()) != 0) {
4627         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
4628             return SSL_ERROR_SYSCALL;
4629         else
4630             return SSL_ERROR_SSL;
4631     }
4632
4633 #ifndef OPENSSL_NO_QUIC
4634     if (!IS_QUIC(s))
4635 #endif
4636     {
4637         if (SSL_want_read(s)) {
4638             bio = SSL_get_rbio(s);
4639             if (BIO_should_read(bio))
4640                 return SSL_ERROR_WANT_READ;
4641             else if (BIO_should_write(bio))
4642                 /*
4643                  * This one doesn't make too much sense ... We never try to
4644                  * write to the rbio, and an application program where rbio and
4645                  * wbio are separate couldn't even know what it should wait for.
4646                  * However if we ever set s->rwstate incorrectly (so that we
4647                  * have SSL_want_read(s) instead of SSL_want_write(s)) and rbio
4648                  * and wbio *are* the same, this test works around that bug; so
4649                  * it might be safer to keep it.
4650                  */
4651                 return SSL_ERROR_WANT_WRITE;
4652             else if (BIO_should_io_special(bio)) {
4653                 reason = BIO_get_retry_reason(bio);
4654                 if (reason == BIO_RR_CONNECT)
4655                     return SSL_ERROR_WANT_CONNECT;
4656                 else if (reason == BIO_RR_ACCEPT)
4657                     return SSL_ERROR_WANT_ACCEPT;
4658                 else
4659                     return SSL_ERROR_SYSCALL; /* unknown */
4660             }
4661         }
4662
4663         if (SSL_want_write(s)) {
4664             /*
4665              * Access wbio directly - in order to use the buffered bio if
4666              * present
4667              */
4668             bio = sc->wbio;
4669             if (BIO_should_write(bio))
4670                 return SSL_ERROR_WANT_WRITE;
4671             else if (BIO_should_read(bio))
4672                 /*
4673                  * See above (SSL_want_read(s) with BIO_should_write(bio))
4674                  */
4675                 return SSL_ERROR_WANT_READ;
4676             else if (BIO_should_io_special(bio)) {
4677                 reason = BIO_get_retry_reason(bio);
4678                 if (reason == BIO_RR_CONNECT)
4679                     return SSL_ERROR_WANT_CONNECT;
4680                 else if (reason == BIO_RR_ACCEPT)
4681                     return SSL_ERROR_WANT_ACCEPT;
4682                 else
4683                     return SSL_ERROR_SYSCALL;
4684             }
4685         }
4686     }
4687
4688     if (SSL_want_x509_lookup(s))
4689         return SSL_ERROR_WANT_X509_LOOKUP;
4690     if (SSL_want_retry_verify(s))
4691         return SSL_ERROR_WANT_RETRY_VERIFY;
4692     if (SSL_want_async(s))
4693         return SSL_ERROR_WANT_ASYNC;
4694     if (SSL_want_async_job(s))
4695         return SSL_ERROR_WANT_ASYNC_JOB;
4696     if (SSL_want_client_hello_cb(s))
4697         return SSL_ERROR_WANT_CLIENT_HELLO_CB;
4698
4699     if ((sc->shutdown & SSL_RECEIVED_SHUTDOWN) &&
4700         (sc->s3.warn_alert == SSL_AD_CLOSE_NOTIFY))
4701         return SSL_ERROR_ZERO_RETURN;
4702
4703     return SSL_ERROR_SYSCALL;
4704 }
4705
4706 static int ssl_do_handshake_intern(void *vargs)
4707 {
4708     struct ssl_async_args *args = (struct ssl_async_args *)vargs;
4709     SSL *s = args->s;
4710     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4711
4712     if (sc == NULL)
4713         return -1;
4714
4715     return sc->handshake_func(s);
4716 }
4717
4718 int SSL_do_handshake(SSL *s)
4719 {
4720     int ret = 1;
4721     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4722
4723 #ifndef OPENSSL_NO_QUIC
4724     if (IS_QUIC(s))
4725         return ossl_quic_do_handshake(s);
4726 #endif
4727
4728     if (sc->handshake_func == NULL) {
4729         ERR_raise(ERR_LIB_SSL, SSL_R_CONNECTION_TYPE_NOT_SET);
4730         return -1;
4731     }
4732
4733     ossl_statem_check_finish_init(sc, -1);
4734
4735     s->method->ssl_renegotiate_check(s, 0);
4736
4737     if (SSL_in_init(s) || SSL_in_before(s)) {
4738         if ((sc->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
4739             struct ssl_async_args args;
4740
4741             memset(&args, 0, sizeof(args));
4742             args.s = s;
4743
4744             ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
4745         } else {
4746             ret = sc->handshake_func(s);
4747         }
4748     }
4749     return ret;
4750 }
4751
4752 void SSL_set_accept_state(SSL *s)
4753 {
4754     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4755
4756 #ifndef OPENSSL_NO_QUIC
4757     if (IS_QUIC(s)) {
4758         ossl_quic_set_accept_state(s);
4759         return;
4760     }
4761 #endif
4762
4763     sc->server = 1;
4764     sc->shutdown = 0;
4765     ossl_statem_clear(sc);
4766     sc->handshake_func = s->method->ssl_accept;
4767     /* Ignore return value. Its a void public API function */
4768     clear_record_layer(sc);
4769 }
4770
4771 void SSL_set_connect_state(SSL *s)
4772 {
4773     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4774
4775 #ifndef OPENSSL_NO_QUIC
4776     if (IS_QUIC(s)) {
4777         ossl_quic_set_connect_state(s);
4778         return;
4779     }
4780 #endif
4781
4782     sc->server = 0;
4783     sc->shutdown = 0;
4784     ossl_statem_clear(sc);
4785     sc->handshake_func = s->method->ssl_connect;
4786     /* Ignore return value. Its a void public API function */
4787     clear_record_layer(sc);
4788 }
4789
4790 int ssl_undefined_function(SSL *s)
4791 {
4792     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4793     return 0;
4794 }
4795
4796 int ssl_undefined_void_function(void)
4797 {
4798     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4799     return 0;
4800 }
4801
4802 int ssl_undefined_const_function(const SSL *s)
4803 {
4804     return 0;
4805 }
4806
4807 const SSL_METHOD *ssl_bad_method(int ver)
4808 {
4809     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4810     return NULL;
4811 }
4812
4813 const char *ssl_protocol_to_string(int version)
4814 {
4815     switch (version)
4816     {
4817     case TLS1_3_VERSION:
4818         return "TLSv1.3";
4819
4820     case TLS1_2_VERSION:
4821         return "TLSv1.2";
4822
4823     case TLS1_1_VERSION:
4824         return "TLSv1.1";
4825
4826     case TLS1_VERSION:
4827         return "TLSv1";
4828
4829     case SSL3_VERSION:
4830         return "SSLv3";
4831
4832     case DTLS1_BAD_VER:
4833         return "DTLSv0.9";
4834
4835     case DTLS1_VERSION:
4836         return "DTLSv1";
4837
4838     case DTLS1_2_VERSION:
4839         return "DTLSv1.2";
4840
4841     default:
4842         return "unknown";
4843     }
4844 }
4845
4846 const char *SSL_get_version(const SSL *s)
4847 {
4848     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4849
4850 #ifndef OPENSSL_NO_QUIC
4851     /* We only support QUICv1 - so if its QUIC its QUICv1 */
4852     if (s->type == SSL_TYPE_QUIC_CONNECTION || s->type == SSL_TYPE_QUIC_XSO)
4853         return "QUICv1";
4854 #endif
4855
4856     if (sc == NULL)
4857         return NULL;
4858
4859     return ssl_protocol_to_string(sc->version);
4860 }
4861
4862 __owur int SSL_get_handshake_rtt(const SSL *s, uint64_t *rtt)
4863 {
4864     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4865
4866     if (sc == NULL)
4867         return -1;
4868     if (sc->ts_msg_write.t <= 0 || sc->ts_msg_read.t <= 0)
4869         return 0; /* data not (yet) available */
4870     if (sc->ts_msg_read.t < sc->ts_msg_write.t)
4871         return -1;
4872
4873     *rtt = ossl_time2us(ossl_time_subtract(sc->ts_msg_read, sc->ts_msg_write));
4874     return 1;
4875 }
4876
4877 static int dup_ca_names(STACK_OF(X509_NAME) **dst, STACK_OF(X509_NAME) *src)
4878 {
4879     STACK_OF(X509_NAME) *sk;
4880     X509_NAME *xn;
4881     int i;
4882
4883     if (src == NULL) {
4884         *dst = NULL;
4885         return 1;
4886     }
4887
4888     if ((sk = sk_X509_NAME_new_null()) == NULL)
4889         return 0;
4890     for (i = 0; i < sk_X509_NAME_num(src); i++) {
4891         xn = X509_NAME_dup(sk_X509_NAME_value(src, i));
4892         if (xn == NULL) {
4893             sk_X509_NAME_pop_free(sk, X509_NAME_free);
4894             return 0;
4895         }
4896         if (sk_X509_NAME_insert(sk, xn, i) == 0) {
4897             X509_NAME_free(xn);
4898             sk_X509_NAME_pop_free(sk, X509_NAME_free);
4899             return 0;
4900         }
4901     }
4902     *dst = sk;
4903
4904     return 1;
4905 }
4906
4907 SSL *SSL_dup(SSL *s)
4908 {
4909     SSL *ret;
4910     int i;
4911     /* TODO(QUIC FUTURE): Add a SSL_METHOD function for duplication */
4912     SSL_CONNECTION *retsc;
4913     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4914
4915     if (sc == NULL)
4916         return NULL;
4917
4918     /* If we're not quiescent, just up_ref! */
4919     if (!SSL_in_init(s) || !SSL_in_before(s)) {
4920         CRYPTO_UP_REF(&s->references, &i);
4921         return s;
4922     }
4923
4924     /*
4925      * Otherwise, copy configuration state, and session if set.
4926      */
4927     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
4928         return NULL;
4929     if ((retsc = SSL_CONNECTION_FROM_SSL_ONLY(ret)) == NULL)
4930         goto err;
4931
4932     if (sc->session != NULL) {
4933         /*
4934          * Arranges to share the same session via up_ref.  This "copies"
4935          * session-id, SSL_METHOD, sid_ctx, and 'cert'
4936          */
4937         if (!SSL_copy_session_id(ret, s))
4938             goto err;
4939     } else {
4940         /*
4941          * No session has been established yet, so we have to expect that
4942          * s->cert or ret->cert will be changed later -- they should not both
4943          * point to the same object, and thus we can't use
4944          * SSL_copy_session_id.
4945          */
4946         if (!SSL_set_ssl_method(ret, s->method))
4947             goto err;
4948
4949         if (sc->cert != NULL) {
4950             ssl_cert_free(retsc->cert);
4951             retsc->cert = ssl_cert_dup(sc->cert);
4952             if (retsc->cert == NULL)
4953                 goto err;
4954         }
4955
4956         if (!SSL_set_session_id_context(ret, sc->sid_ctx,
4957                                         (int)sc->sid_ctx_length))
4958             goto err;
4959     }
4960
4961     if (!ssl_dane_dup(retsc, sc))
4962         goto err;
4963     retsc->version = sc->version;
4964     retsc->options = sc->options;
4965     retsc->min_proto_version = sc->min_proto_version;
4966     retsc->max_proto_version = sc->max_proto_version;
4967     retsc->mode = sc->mode;
4968     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
4969     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
4970     retsc->msg_callback = sc->msg_callback;
4971     retsc->msg_callback_arg = sc->msg_callback_arg;
4972     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
4973     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
4974     retsc->generate_session_id = sc->generate_session_id;
4975
4976     SSL_set_info_callback(ret, SSL_get_info_callback(s));
4977
4978     /* copy app data, a little dangerous perhaps */
4979     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
4980         goto err;
4981
4982     retsc->server = sc->server;
4983     if (sc->handshake_func) {
4984         if (sc->server)
4985             SSL_set_accept_state(ret);
4986         else
4987             SSL_set_connect_state(ret);
4988     }
4989     retsc->shutdown = sc->shutdown;
4990     retsc->hit = sc->hit;
4991
4992     retsc->default_passwd_callback = sc->default_passwd_callback;
4993     retsc->default_passwd_callback_userdata = sc->default_passwd_callback_userdata;
4994
4995     X509_VERIFY_PARAM_inherit(retsc->param, sc->param);
4996
4997     /* dup the cipher_list and cipher_list_by_id stacks */
4998     if (sc->cipher_list != NULL) {
4999         if ((retsc->cipher_list = sk_SSL_CIPHER_dup(sc->cipher_list)) == NULL)
5000             goto err;
5001     }
5002     if (sc->cipher_list_by_id != NULL)
5003         if ((retsc->cipher_list_by_id = sk_SSL_CIPHER_dup(sc->cipher_list_by_id))
5004             == NULL)
5005             goto err;
5006
5007     /* Dup the client_CA list */
5008     if (!dup_ca_names(&retsc->ca_names, sc->ca_names)
5009             || !dup_ca_names(&retsc->client_ca_names, sc->client_ca_names))
5010         goto err;
5011
5012     return ret;
5013
5014  err:
5015     SSL_free(ret);
5016     return NULL;
5017 }
5018
5019 X509 *SSL_get_certificate(const SSL *s)
5020 {
5021     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5022
5023     if (sc == NULL)
5024         return NULL;
5025
5026     if (sc->cert != NULL)
5027         return sc->cert->key->x509;
5028     else
5029         return NULL;
5030 }
5031
5032 EVP_PKEY *SSL_get_privatekey(const SSL *s)
5033 {
5034     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5035
5036     if (sc == NULL)
5037         return NULL;
5038
5039     if (sc->cert != NULL)
5040         return sc->cert->key->privatekey;
5041     else
5042         return NULL;
5043 }
5044
5045 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
5046 {
5047     if (ctx->cert != NULL)
5048         return ctx->cert->key->x509;
5049     else
5050         return NULL;
5051 }
5052
5053 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
5054 {
5055     if (ctx->cert != NULL)
5056         return ctx->cert->key->privatekey;
5057     else
5058         return NULL;
5059 }
5060
5061 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
5062 {
5063     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5064
5065     if (sc == NULL)
5066         return NULL;
5067
5068     if ((sc->session != NULL) && (sc->session->cipher != NULL))
5069         return sc->session->cipher;
5070     return NULL;
5071 }
5072
5073 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s)
5074 {
5075     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5076
5077     if (sc == NULL)
5078         return NULL;
5079
5080     return sc->s3.tmp.new_cipher;
5081 }
5082
5083 const COMP_METHOD *SSL_get_current_compression(const SSL *s)
5084 {
5085 #ifndef OPENSSL_NO_COMP
5086     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
5087
5088     if (sc == NULL)
5089         return NULL;
5090
5091     return sc->rlayer.wrlmethod->get_compression(sc->rlayer.wrl);
5092 #else
5093     return NULL;
5094 #endif
5095 }
5096
5097 const COMP_METHOD *SSL_get_current_expansion(const SSL *s)
5098 {
5099 #ifndef OPENSSL_NO_COMP
5100     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
5101
5102     if (sc == NULL)
5103         return NULL;
5104
5105     return sc->rlayer.rrlmethod->get_compression(sc->rlayer.rrl);
5106 #else
5107     return NULL;
5108 #endif
5109 }
5110
5111 int ssl_init_wbio_buffer(SSL_CONNECTION *s)
5112 {
5113     BIO *bbio;
5114
5115     if (s->bbio != NULL) {
5116         /* Already buffered. */
5117         return 1;
5118     }
5119
5120     bbio = BIO_new(BIO_f_buffer());
5121     if (bbio == NULL || BIO_set_read_buffer_size(bbio, 1) <= 0) {
5122         BIO_free(bbio);
5123         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
5124         return 0;
5125     }
5126     s->bbio = bbio;
5127     s->wbio = BIO_push(bbio, s->wbio);
5128
5129     s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
5130
5131     return 1;
5132 }
5133
5134 int ssl_free_wbio_buffer(SSL_CONNECTION *s)
5135 {
5136     /* callers ensure s is never null */
5137     if (s->bbio == NULL)
5138         return 1;
5139
5140     s->wbio = BIO_pop(s->wbio);
5141     s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
5142
5143     BIO_free(s->bbio);
5144     s->bbio = NULL;
5145
5146     return 1;
5147 }
5148
5149 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
5150 {
5151     ctx->quiet_shutdown = mode;
5152 }
5153
5154 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
5155 {
5156     return ctx->quiet_shutdown;
5157 }
5158
5159 void SSL_set_quiet_shutdown(SSL *s, int mode)
5160 {
5161     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
5162
5163     /* Not supported with QUIC */
5164     if (sc == NULL)
5165         return;
5166
5167     sc->quiet_shutdown = mode;
5168 }
5169
5170 int SSL_get_quiet_shutdown(const SSL *s)
5171 {
5172     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
5173
5174     /* Not supported with QUIC */
5175     if (sc == NULL)
5176         return 0;
5177
5178     return sc->quiet_shutdown;
5179 }
5180
5181 void SSL_set_shutdown(SSL *s, int mode)
5182 {
5183     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
5184
5185     /* Not supported with QUIC */
5186     if (sc == NULL)
5187         return;
5188
5189     sc->shutdown = mode;
5190 }
5191
5192 int SSL_get_shutdown(const SSL *s)
5193 {
5194     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
5195
5196 #ifndef OPENSSL_NO_QUIC
5197     /* QUIC: Just indicate whether the connection was shutdown cleanly. */
5198     if (IS_QUIC(s))
5199         return ossl_quic_get_shutdown(s);
5200 #endif
5201
5202     if (sc == NULL)
5203         return 0;
5204
5205     return sc->shutdown;
5206 }
5207
5208 int SSL_version(const SSL *s)
5209 {
5210     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5211
5212 #ifndef OPENSSL_NO_QUIC
5213     /* We only support QUICv1 - so if its QUIC its QUICv1 */
5214     if (s->type == SSL_TYPE_QUIC_CONNECTION || s->type == SSL_TYPE_QUIC_XSO)
5215         return OSSL_QUIC1_VERSION;
5216 #endif
5217     if (sc == NULL)
5218         return 0;
5219
5220     return sc->version;
5221 }
5222
5223 int SSL_client_version(const SSL *s)
5224 {
5225     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5226
5227 #ifndef OPENSSL_NO_QUIC
5228     /* We only support QUICv1 - so if its QUIC its QUICv1 */
5229     if (s->type == SSL_TYPE_QUIC_CONNECTION || s->type == SSL_TYPE_QUIC_XSO)
5230         return OSSL_QUIC1_VERSION;
5231 #endif
5232     if (sc == NULL)
5233         return 0;
5234
5235     return sc->client_version;
5236 }
5237
5238 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
5239 {
5240     return ssl->ctx;
5241 }
5242
5243 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
5244 {
5245     CERT *new_cert;
5246     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
5247
5248     /* TODO(QUIC FUTURE): Add support for QUIC */
5249     if (sc == NULL)
5250         return NULL;
5251
5252     if (ssl->ctx == ctx)
5253         return ssl->ctx;
5254     if (ctx == NULL)
5255         ctx = sc->session_ctx;
5256     new_cert = ssl_cert_dup(ctx->cert);
5257     if (new_cert == NULL) {
5258         return NULL;
5259     }
5260
5261     if (!custom_exts_copy_flags(&new_cert->custext, &sc->cert->custext)) {
5262         ssl_cert_free(new_cert);
5263         return NULL;
5264     }
5265
5266     ssl_cert_free(sc->cert);
5267     sc->cert = new_cert;
5268
5269     /*
5270      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
5271      * so setter APIs must prevent invalid lengths from entering the system.
5272      */
5273     if (!ossl_assert(sc->sid_ctx_length <= sizeof(sc->sid_ctx)))
5274         return NULL;
5275
5276     /*
5277      * If the session ID context matches that of the parent SSL_CTX,
5278      * inherit it from the new SSL_CTX as well. If however the context does
5279      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
5280      * leave it unchanged.
5281      */
5282     if ((ssl->ctx != NULL) &&
5283         (sc->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
5284         (memcmp(sc->sid_ctx, ssl->ctx->sid_ctx, sc->sid_ctx_length) == 0)) {
5285         sc->sid_ctx_length = ctx->sid_ctx_length;
5286         memcpy(&sc->sid_ctx, &ctx->sid_ctx, sizeof(sc->sid_ctx));
5287     }
5288
5289     SSL_CTX_up_ref(ctx);
5290     SSL_CTX_free(ssl->ctx);     /* decrement reference count */
5291     ssl->ctx = ctx;
5292
5293     return ssl->ctx;
5294 }
5295
5296 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
5297 {
5298     return X509_STORE_set_default_paths_ex(ctx->cert_store, ctx->libctx,
5299                                            ctx->propq);
5300 }
5301
5302 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
5303 {
5304     X509_LOOKUP *lookup;
5305
5306     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
5307     if (lookup == NULL)
5308         return 0;
5309
5310     /* We ignore errors, in case the directory doesn't exist */
5311     ERR_set_mark();
5312
5313     X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
5314
5315     ERR_pop_to_mark();
5316
5317     return 1;
5318 }
5319
5320 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
5321 {
5322     X509_LOOKUP *lookup;
5323
5324     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
5325     if (lookup == NULL)
5326         return 0;
5327
5328     /* We ignore errors, in case the file doesn't exist */
5329     ERR_set_mark();
5330
5331     X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, ctx->libctx,
5332                              ctx->propq);
5333
5334     ERR_pop_to_mark();
5335
5336     return 1;
5337 }
5338
5339 int SSL_CTX_set_default_verify_store(SSL_CTX *ctx)
5340 {
5341     X509_LOOKUP *lookup;
5342
5343     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_store());
5344     if (lookup == NULL)
5345         return 0;
5346
5347     /* We ignore errors, in case the directory doesn't exist */
5348     ERR_set_mark();
5349
5350     X509_LOOKUP_add_store_ex(lookup, NULL, ctx->libctx, ctx->propq);
5351
5352     ERR_pop_to_mark();
5353
5354     return 1;
5355 }
5356
5357 int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile)
5358 {
5359     return X509_STORE_load_file_ex(ctx->cert_store, CAfile, ctx->libctx,
5360                                    ctx->propq);
5361 }
5362
5363 int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath)
5364 {
5365     return X509_STORE_load_path(ctx->cert_store, CApath);
5366 }
5367
5368 int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore)
5369 {
5370     return X509_STORE_load_store_ex(ctx->cert_store, CAstore, ctx->libctx,
5371                                     ctx->propq);
5372 }
5373
5374 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
5375                                   const char *CApath)
5376 {
5377     if (CAfile == NULL && CApath == NULL)
5378         return 0;
5379     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
5380         return 0;
5381     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
5382         return 0;
5383     return 1;
5384 }
5385
5386 void SSL_set_info_callback(SSL *ssl,
5387                            void (*cb) (const SSL *ssl, int type, int val))
5388 {
5389     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5390
5391     if (sc == NULL)
5392         return;
5393
5394     sc->info_callback = cb;
5395 }
5396
5397 /*
5398  * One compiler (Diab DCC) doesn't like argument names in returned function
5399  * pointer.
5400  */
5401 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
5402                                                int /* type */ ,
5403                                                int /* val */ ) {
5404     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5405
5406     if (sc == NULL)
5407         return NULL;
5408
5409     return sc->info_callback;
5410 }
5411
5412 void SSL_set_verify_result(SSL *ssl, long arg)
5413 {
5414     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5415
5416     if (sc == NULL)
5417         return;
5418
5419     sc->verify_result = arg;
5420 }
5421
5422 long SSL_get_verify_result(const SSL *ssl)
5423 {
5424     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5425
5426     if (sc == NULL)
5427         return 0;
5428
5429     return sc->verify_result;
5430 }
5431
5432 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
5433 {
5434     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5435
5436     if (sc == NULL)
5437         return 0;
5438
5439     if (outlen == 0)
5440         return sizeof(sc->s3.client_random);
5441     if (outlen > sizeof(sc->s3.client_random))
5442         outlen = sizeof(sc->s3.client_random);
5443     memcpy(out, sc->s3.client_random, outlen);
5444     return outlen;
5445 }
5446
5447 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
5448 {
5449     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5450
5451     if (sc == NULL)
5452         return 0;
5453
5454     if (outlen == 0)
5455         return sizeof(sc->s3.server_random);
5456     if (outlen > sizeof(sc->s3.server_random))
5457         outlen = sizeof(sc->s3.server_random);
5458     memcpy(out, sc->s3.server_random, outlen);
5459     return outlen;
5460 }
5461
5462 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
5463                                   unsigned char *out, size_t outlen)
5464 {
5465     if (outlen == 0)
5466         return session->master_key_length;
5467     if (outlen > session->master_key_length)
5468         outlen = session->master_key_length;
5469     memcpy(out, session->master_key, outlen);
5470     return outlen;
5471 }
5472
5473 int SSL_SESSION_set1_master_key(SSL_SESSION *sess, const unsigned char *in,
5474                                 size_t len)
5475 {
5476     if (len > sizeof(sess->master_key))
5477         return 0;
5478
5479     memcpy(sess->master_key, in, len);
5480     sess->master_key_length = len;
5481     return 1;
5482 }
5483
5484
5485 int SSL_set_ex_data(SSL *s, int idx, void *arg)
5486 {
5487     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
5488 }
5489
5490 void *SSL_get_ex_data(const SSL *s, int idx)
5491 {
5492     return CRYPTO_get_ex_data(&s->ex_data, idx);
5493 }
5494
5495 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
5496 {
5497     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
5498 }
5499
5500 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
5501 {
5502     return CRYPTO_get_ex_data(&s->ex_data, idx);
5503 }
5504
5505 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
5506 {
5507     return ctx->cert_store;
5508 }
5509
5510 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
5511 {
5512     X509_STORE_free(ctx->cert_store);
5513     ctx->cert_store = store;
5514 }
5515
5516 void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
5517 {
5518     if (store != NULL)
5519         X509_STORE_up_ref(store);
5520     SSL_CTX_set_cert_store(ctx, store);
5521 }
5522
5523 int SSL_want(const SSL *s)
5524 {
5525     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5526
5527 #ifndef OPENSSL_NO_QUIC
5528     if (IS_QUIC(s))
5529         return ossl_quic_want(s);
5530 #endif
5531
5532     if (sc == NULL)
5533         return SSL_NOTHING;
5534
5535     return sc->rwstate;
5536 }
5537
5538 #ifndef OPENSSL_NO_PSK
5539 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
5540 {
5541     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
5542         ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
5543         return 0;
5544     }
5545     OPENSSL_free(ctx->cert->psk_identity_hint);
5546     if (identity_hint != NULL) {
5547         ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
5548         if (ctx->cert->psk_identity_hint == NULL)
5549             return 0;
5550     } else
5551         ctx->cert->psk_identity_hint = NULL;
5552     return 1;
5553 }
5554
5555 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
5556 {
5557     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5558
5559     if (sc == NULL)
5560         return 0;
5561
5562     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
5563         ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
5564         return 0;
5565     }
5566     OPENSSL_free(sc->cert->psk_identity_hint);
5567     if (identity_hint != NULL) {
5568         sc->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
5569         if (sc->cert->psk_identity_hint == NULL)
5570             return 0;
5571     } else
5572         sc->cert->psk_identity_hint = NULL;
5573     return 1;
5574 }
5575
5576 const char *SSL_get_psk_identity_hint(const SSL *s)
5577 {
5578     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5579
5580     if (sc == NULL || sc->session == NULL)
5581         return NULL;
5582
5583     return sc->session->psk_identity_hint;
5584 }
5585
5586 const char *SSL_get_psk_identity(const SSL *s)
5587 {
5588     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5589
5590     if (sc == NULL || sc->session == NULL)
5591         return NULL;
5592
5593     return sc->session->psk_identity;
5594 }
5595
5596 void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
5597 {
5598     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5599
5600     if (sc == NULL)
5601         return;
5602
5603     sc->psk_client_callback = cb;
5604 }
5605
5606 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
5607 {
5608     ctx->psk_client_callback = cb;
5609 }
5610
5611 void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
5612 {
5613     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5614
5615     if (sc == NULL)
5616         return;
5617
5618     sc->psk_server_callback = cb;
5619 }
5620
5621 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
5622 {
5623     ctx->psk_server_callback = cb;
5624 }
5625 #endif
5626
5627 void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb)
5628 {
5629     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5630
5631     if (sc == NULL)
5632         return;
5633
5634     sc->psk_find_session_cb = cb;
5635 }
5636
5637 void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
5638                                            SSL_psk_find_session_cb_func cb)
5639 {
5640     ctx->psk_find_session_cb = cb;
5641 }
5642
5643 void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
5644 {
5645     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5646
5647     if (sc == NULL)
5648         return;
5649
5650     sc->psk_use_session_cb = cb;
5651 }
5652
5653 void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
5654                                            SSL_psk_use_session_cb_func cb)
5655 {
5656     ctx->psk_use_session_cb = cb;
5657 }
5658
5659 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
5660                               void (*cb) (int write_p, int version,
5661                                           int content_type, const void *buf,
5662                                           size_t len, SSL *ssl, void *arg))
5663 {
5664     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
5665 }
5666
5667 void SSL_set_msg_callback(SSL *ssl,
5668                           void (*cb) (int write_p, int version,
5669                                       int content_type, const void *buf,
5670                                       size_t len, SSL *ssl, void *arg))
5671 {
5672     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
5673 }
5674
5675 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
5676                                                 int (*cb) (SSL *ssl,
5677                                                            int
5678                                                            is_forward_secure))
5679 {
5680     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
5681                           (void (*)(void))cb);
5682 }
5683
5684 void SSL_set_not_resumable_session_callback(SSL *ssl,
5685                                             int (*cb) (SSL *ssl,
5686                                                        int is_forward_secure))
5687 {
5688     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
5689                       (void (*)(void))cb);
5690 }
5691
5692 void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
5693                                          size_t (*cb) (SSL *ssl, int type,
5694                                                        size_t len, void *arg))
5695 {
5696     ctx->record_padding_cb = cb;
5697 }
5698
5699 void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
5700 {
5701     ctx->record_padding_arg = arg;
5702 }
5703
5704 void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx)
5705 {
5706     return ctx->record_padding_arg;
5707 }
5708
5709 int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
5710 {
5711     if (IS_QUIC_CTX(ctx) && block_size > 1)
5712         return 0;
5713
5714     /* block size of 0 or 1 is basically no padding */
5715     if (block_size == 1)
5716         ctx->block_padding = 0;
5717     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
5718         ctx->block_padding = block_size;
5719     else
5720         return 0;
5721     return 1;
5722 }
5723
5724 int SSL_set_record_padding_callback(SSL *ssl,
5725                                      size_t (*cb) (SSL *ssl, int type,
5726                                                    size_t len, void *arg))
5727 {
5728     BIO *b;
5729     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
5730
5731     if (sc == NULL)
5732         return 0;
5733
5734     b = SSL_get_wbio(ssl);
5735     if (b == NULL || !BIO_get_ktls_send(b)) {
5736         sc->rlayer.record_padding_cb = cb;
5737         return 1;
5738     }
5739     return 0;
5740 }
5741
5742 void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
5743 {
5744     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5745
5746     if (sc == NULL)
5747         return;
5748
5749     sc->rlayer.record_padding_arg = arg;
5750 }
5751
5752 void *SSL_get_record_padding_callback_arg(const SSL *ssl)
5753 {
5754     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5755
5756     if (sc == NULL)
5757         return NULL;
5758
5759     return sc->rlayer.record_padding_arg;
5760 }
5761
5762 int SSL_set_block_padding(SSL *ssl, size_t block_size)
5763 {
5764     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5765
5766     if (sc == NULL || (IS_QUIC(ssl) && block_size > 1))
5767         return 0;
5768
5769     /* block size of 0 or 1 is basically no padding */
5770     if (block_size == 1)
5771         sc->rlayer.block_padding = 0;
5772     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
5773         sc->rlayer.block_padding = block_size;
5774     else
5775         return 0;
5776     return 1;
5777 }
5778
5779 int SSL_set_num_tickets(SSL *s, size_t num_tickets)
5780 {
5781     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5782
5783     if (sc == NULL)
5784         return 0;
5785
5786     sc->num_tickets = num_tickets;
5787
5788     return 1;
5789 }
5790
5791 size_t SSL_get_num_tickets(const SSL *s)
5792 {
5793     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5794
5795     if (sc == NULL)
5796         return 0;
5797
5798     return sc->num_tickets;
5799 }
5800
5801 int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets)
5802 {
5803     ctx->num_tickets = num_tickets;
5804
5805     return 1;
5806 }
5807
5808 size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx)
5809 {
5810     return ctx->num_tickets;
5811 }
5812
5813 /* Retrieve handshake hashes */
5814 int ssl_handshake_hash(SSL_CONNECTION *s,
5815                        unsigned char *out, size_t outlen,
5816                        size_t *hashlen)
5817 {
5818     EVP_MD_CTX *ctx = NULL;
5819     EVP_MD_CTX *hdgst = s->s3.handshake_dgst;
5820     int hashleni = EVP_MD_CTX_get_size(hdgst);
5821     int ret = 0;
5822
5823     if (hashleni < 0 || (size_t)hashleni > outlen) {
5824         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5825         goto err;
5826     }
5827
5828     ctx = EVP_MD_CTX_new();
5829     if (ctx == NULL) {
5830         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5831         goto err;
5832     }
5833
5834     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
5835         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0) {
5836         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5837         goto err;
5838     }
5839
5840     *hashlen = hashleni;
5841
5842     ret = 1;
5843  err:
5844     EVP_MD_CTX_free(ctx);
5845     return ret;
5846 }
5847
5848 int SSL_session_reused(const SSL *s)
5849 {
5850     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5851
5852     if (sc == NULL)
5853         return 0;
5854
5855     return sc->hit;
5856 }
5857
5858 int SSL_is_server(const SSL *s)
5859 {
5860     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5861
5862     if (sc == NULL)
5863         return 0;
5864
5865     return sc->server;
5866 }
5867
5868 #ifndef OPENSSL_NO_DEPRECATED_1_1_0
5869 void SSL_set_debug(SSL *s, int debug)
5870 {
5871     /* Old function was do-nothing anyway... */
5872     (void)s;
5873     (void)debug;
5874 }
5875 #endif
5876
5877 void SSL_set_security_level(SSL *s, int level)
5878 {
5879     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5880
5881     if (sc == NULL)
5882         return;
5883
5884     sc->cert->sec_level = level;
5885 }
5886
5887 int SSL_get_security_level(const SSL *s)
5888 {
5889     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5890
5891     if (sc == NULL)
5892         return 0;
5893
5894     return sc->cert->sec_level;
5895 }
5896
5897 void SSL_set_security_callback(SSL *s,
5898                                int (*cb) (const SSL *s, const SSL_CTX *ctx,
5899                                           int op, int bits, int nid,
5900                                           void *other, void *ex))
5901 {
5902     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5903
5904     if (sc == NULL)
5905         return;
5906
5907     sc->cert->sec_cb = cb;
5908 }
5909
5910 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
5911                                                 const SSL_CTX *ctx, int op,
5912                                                 int bits, int nid, void *other,
5913                                                 void *ex) {
5914     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5915
5916     if (sc == NULL)
5917         return NULL;
5918
5919     return sc->cert->sec_cb;
5920 }
5921
5922 void SSL_set0_security_ex_data(SSL *s, void *ex)
5923 {
5924     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5925
5926     if (sc == NULL)
5927         return;
5928
5929     sc->cert->sec_ex = ex;
5930 }
5931
5932 void *SSL_get0_security_ex_data(const SSL *s)
5933 {
5934     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5935
5936     if (sc == NULL)
5937         return NULL;
5938
5939     return sc->cert->sec_ex;
5940 }
5941
5942 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
5943 {
5944     ctx->cert->sec_level = level;
5945 }
5946
5947 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
5948 {
5949     return ctx->cert->sec_level;
5950 }
5951
5952 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
5953                                    int (*cb) (const SSL *s, const SSL_CTX *ctx,
5954                                               int op, int bits, int nid,
5955                                               void *other, void *ex))
5956 {
5957     ctx->cert->sec_cb = cb;
5958 }
5959
5960 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
5961                                                           const SSL_CTX *ctx,
5962                                                           int op, int bits,
5963                                                           int nid,
5964                                                           void *other,
5965                                                           void *ex) {
5966     return ctx->cert->sec_cb;
5967 }
5968
5969 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
5970 {
5971     ctx->cert->sec_ex = ex;
5972 }
5973
5974 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
5975 {
5976     return ctx->cert->sec_ex;
5977 }
5978
5979 uint64_t SSL_CTX_get_options(const SSL_CTX *ctx)
5980 {
5981     return ctx->options;
5982 }
5983
5984 uint64_t SSL_get_options(const SSL *s)
5985 {
5986     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5987
5988 #ifndef OPENSSL_NO_QUIC
5989     if (IS_QUIC(s))
5990         return ossl_quic_get_options(s);
5991 #endif
5992
5993     if (sc == NULL)
5994         return 0;
5995
5996     return sc->options;
5997 }
5998
5999 uint64_t SSL_CTX_set_options(SSL_CTX *ctx, uint64_t op)
6000 {
6001     return ctx->options |= op;
6002 }
6003
6004 uint64_t SSL_set_options(SSL *s, uint64_t op)
6005 {
6006     SSL_CONNECTION *sc;
6007     OSSL_PARAM options[2], *opts = options;
6008
6009 #ifndef OPENSSL_NO_QUIC
6010     if (IS_QUIC(s))
6011         return ossl_quic_set_options(s, op);
6012 #endif
6013
6014     sc = SSL_CONNECTION_FROM_SSL(s);
6015     if (sc == NULL)
6016         return 0;
6017
6018     sc->options |= op;
6019
6020     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
6021                                           &sc->options);
6022     *opts = OSSL_PARAM_construct_end();
6023
6024     /* Ignore return value */
6025     sc->rlayer.rrlmethod->set_options(sc->rlayer.rrl, options);
6026     sc->rlayer.wrlmethod->set_options(sc->rlayer.wrl, options);
6027
6028     return sc->options;
6029 }
6030
6031 uint64_t SSL_CTX_clear_options(SSL_CTX *ctx, uint64_t op)
6032 {
6033     return ctx->options &= ~op;
6034 }
6035
6036 uint64_t SSL_clear_options(SSL *s, uint64_t op)
6037 {
6038     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6039     OSSL_PARAM options[2], *opts = options;
6040
6041 #ifndef OPENSSL_NO_QUIC
6042     if (IS_QUIC(s))
6043         return ossl_quic_clear_options(s, op);
6044 #endif
6045
6046     if (sc == NULL)
6047         return 0;
6048
6049     sc->options &= ~op;
6050
6051     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
6052                                           &sc->options);
6053     *opts = OSSL_PARAM_construct_end();
6054
6055     /* Ignore return value */
6056     sc->rlayer.rrlmethod->set_options(sc->rlayer.rrl, options);
6057     sc->rlayer.wrlmethod->set_options(sc->rlayer.wrl, options);
6058
6059     return sc->options;
6060 }
6061
6062 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
6063 {
6064     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
6065
6066     if (sc == NULL)
6067         return NULL;
6068
6069     return sc->verified_chain;
6070 }
6071
6072 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
6073
6074 #ifndef OPENSSL_NO_CT
6075
6076 /*
6077  * Moves SCTs from the |src| stack to the |dst| stack.
6078  * The source of each SCT will be set to |origin|.
6079  * If |dst| points to a NULL pointer, a new stack will be created and owned by
6080  * the caller.
6081  * Returns the number of SCTs moved, or a negative integer if an error occurs.
6082  * The |dst| stack is created and possibly partially populated even in case
6083  * of error, likewise the |src| stack may be left in an intermediate state.
6084  */
6085 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
6086                         sct_source_t origin)
6087 {
6088     int scts_moved = 0;
6089     SCT *sct = NULL;
6090
6091     if (*dst == NULL) {
6092         *dst = sk_SCT_new_null();
6093         if (*dst == NULL) {
6094             ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
6095             goto err;
6096         }
6097     }
6098
6099     while ((sct = sk_SCT_pop(src)) != NULL) {
6100         if (SCT_set_source(sct, origin) != 1)
6101             goto err;
6102
6103         if (!sk_SCT_push(*dst, sct))
6104             goto err;
6105         scts_moved += 1;
6106     }
6107
6108     return scts_moved;
6109  err:
6110     SCT_free(sct);
6111     return -1;
6112 }
6113
6114 /*
6115  * Look for data collected during ServerHello and parse if found.
6116  * Returns the number of SCTs extracted.
6117  */
6118 static int ct_extract_tls_extension_scts(SSL_CONNECTION *s)
6119 {
6120     int scts_extracted = 0;
6121
6122     if (s->ext.scts != NULL) {
6123         const unsigned char *p = s->ext.scts;
6124         STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
6125
6126         scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
6127
6128         SCT_LIST_free(scts);
6129     }
6130
6131     return scts_extracted;
6132 }
6133
6134 /*
6135  * Checks for an OCSP response and then attempts to extract any SCTs found if it
6136  * contains an SCT X509 extension. They will be stored in |s->scts|.
6137  * Returns:
6138  * - The number of SCTs extracted, assuming an OCSP response exists.
6139  * - 0 if no OCSP response exists or it contains no SCTs.
6140  * - A negative integer if an error occurs.
6141  */
6142 static int ct_extract_ocsp_response_scts(SSL_CONNECTION *s)
6143 {
6144 # ifndef OPENSSL_NO_OCSP
6145     int scts_extracted = 0;
6146     const unsigned char *p;
6147     OCSP_BASICRESP *br = NULL;
6148     OCSP_RESPONSE *rsp = NULL;
6149     STACK_OF(SCT) *scts = NULL;
6150     int i;
6151
6152     if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
6153         goto err;
6154
6155     p = s->ext.ocsp.resp;
6156     rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
6157     if (rsp == NULL)
6158         goto err;
6159
6160     br = OCSP_response_get1_basic(rsp);
6161     if (br == NULL)
6162         goto err;
6163
6164     for (i = 0; i < OCSP_resp_count(br); ++i) {
6165         OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
6166
6167         if (single == NULL)
6168             continue;
6169
6170         scts =
6171             OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
6172         scts_extracted =
6173             ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
6174         if (scts_extracted < 0)
6175             goto err;
6176     }
6177  err:
6178     SCT_LIST_free(scts);
6179     OCSP_BASICRESP_free(br);
6180     OCSP_RESPONSE_free(rsp);
6181     return scts_extracted;
6182 # else
6183     /* Behave as if no OCSP response exists */
6184     return 0;
6185 # endif
6186 }
6187
6188 /*
6189  * Attempts to extract SCTs from the peer certificate.
6190  * Return the number of SCTs extracted, or a negative integer if an error
6191  * occurs.
6192  */
6193 static int ct_extract_x509v3_extension_scts(SSL_CONNECTION *s)
6194 {
6195     int scts_extracted = 0;
6196     X509 *cert = s->session != NULL ? s->session->peer : NULL;
6197
6198     if (cert != NULL) {
6199         STACK_OF(SCT) *scts =
6200             X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
6201
6202         scts_extracted =
6203             ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
6204
6205         SCT_LIST_free(scts);
6206     }
6207
6208     return scts_extracted;
6209 }
6210
6211 /*
6212  * Attempts to find all received SCTs by checking TLS extensions, the OCSP
6213  * response (if it exists) and X509v3 extensions in the certificate.
6214  * Returns NULL if an error occurs.
6215  */
6216 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
6217 {
6218     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6219
6220     if (sc == NULL)
6221         return NULL;
6222
6223     if (!sc->scts_parsed) {
6224         if (ct_extract_tls_extension_scts(sc) < 0 ||
6225             ct_extract_ocsp_response_scts(sc) < 0 ||
6226             ct_extract_x509v3_extension_scts(sc) < 0)
6227             goto err;
6228
6229         sc->scts_parsed = 1;
6230     }
6231     return sc->scts;
6232  err:
6233     return NULL;
6234 }
6235
6236 static int ct_permissive(const CT_POLICY_EVAL_CTX *ctx,
6237                          const STACK_OF(SCT) *scts, void *unused_arg)
6238 {
6239     return 1;
6240 }
6241
6242 static int ct_strict(const CT_POLICY_EVAL_CTX *ctx,
6243                      const STACK_OF(SCT) *scts, void *unused_arg)
6244 {
6245     int count = scts != NULL ? sk_SCT_num(scts) : 0;
6246     int i;
6247
6248     for (i = 0; i < count; ++i) {
6249         SCT *sct = sk_SCT_value(scts, i);
6250         int status = SCT_get_validation_status(sct);
6251
6252         if (status == SCT_VALIDATION_STATUS_VALID)
6253             return 1;
6254     }
6255     ERR_raise(ERR_LIB_SSL, SSL_R_NO_VALID_SCTS);
6256     return 0;
6257 }
6258
6259 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
6260                                    void *arg)
6261 {
6262     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6263
6264     if (sc == NULL)
6265         return 0;
6266
6267     /*
6268      * Since code exists that uses the custom extension handler for CT, look
6269      * for this and throw an error if they have already registered to use CT.
6270      */
6271     if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
6272                                                           TLSEXT_TYPE_signed_certificate_timestamp))
6273     {
6274         ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
6275         return 0;
6276     }
6277
6278     if (callback != NULL) {
6279         /*
6280          * If we are validating CT, then we MUST accept SCTs served via OCSP
6281          */
6282         if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
6283             return 0;
6284     }
6285
6286     sc->ct_validation_callback = callback;
6287     sc->ct_validation_callback_arg = arg;
6288
6289     return 1;
6290 }
6291
6292 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
6293                                        ssl_ct_validation_cb callback, void *arg)
6294 {
6295     /*
6296      * Since code exists that uses the custom extension handler for CT, look for
6297      * this and throw an error if they have already registered to use CT.
6298      */
6299     if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
6300                                                           TLSEXT_TYPE_signed_certificate_timestamp))
6301     {
6302         ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
6303         return 0;
6304     }
6305
6306     ctx->ct_validation_callback = callback;
6307     ctx->ct_validation_callback_arg = arg;
6308     return 1;
6309 }
6310
6311 int SSL_ct_is_enabled(const SSL *s)
6312 {
6313     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
6314
6315     if (sc == NULL)
6316         return 0;
6317
6318     return sc->ct_validation_callback != NULL;
6319 }
6320
6321 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
6322 {
6323     return ctx->ct_validation_callback != NULL;
6324 }
6325
6326 int ssl_validate_ct(SSL_CONNECTION *s)
6327 {
6328     int ret = 0;
6329     X509 *cert = s->session != NULL ? s->session->peer : NULL;
6330     X509 *issuer;
6331     SSL_DANE *dane = &s->dane;
6332     CT_POLICY_EVAL_CTX *ctx = NULL;
6333     const STACK_OF(SCT) *scts;
6334
6335     /*
6336      * If no callback is set, the peer is anonymous, or its chain is invalid,
6337      * skip SCT validation - just return success.  Applications that continue
6338      * handshakes without certificates, with unverified chains, or pinned leaf
6339      * certificates are outside the scope of the WebPKI and CT.
6340      *
6341      * The above exclusions notwithstanding the vast majority of peers will
6342      * have rather ordinary certificate chains validated by typical
6343      * applications that perform certificate verification and therefore will
6344      * process SCTs when enabled.
6345      */
6346     if (s->ct_validation_callback == NULL || cert == NULL ||
6347         s->verify_result != X509_V_OK ||
6348         s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
6349         return 1;
6350
6351     /*
6352      * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
6353      * trust-anchors.  See https://tools.ietf.org/html/rfc7671#section-4.2
6354      */
6355     if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
6356         switch (dane->mtlsa->usage) {
6357         case DANETLS_USAGE_DANE_TA:
6358         case DANETLS_USAGE_DANE_EE:
6359             return 1;
6360         }
6361     }
6362
6363     ctx = CT_POLICY_EVAL_CTX_new_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
6364                                     SSL_CONNECTION_GET_CTX(s)->propq);
6365     if (ctx == NULL) {
6366         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CT_LIB);
6367         goto end;
6368     }
6369
6370     issuer = sk_X509_value(s->verified_chain, 1);
6371     CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
6372     CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
6373     CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx,
6374             SSL_CONNECTION_GET_CTX(s)->ctlog_store);
6375     CT_POLICY_EVAL_CTX_set_time(
6376             ctx, (uint64_t)SSL_SESSION_get_time(s->session) * 1000);
6377
6378     scts = SSL_get0_peer_scts(SSL_CONNECTION_GET_SSL(s));
6379
6380     /*
6381      * This function returns success (> 0) only when all the SCTs are valid, 0
6382      * when some are invalid, and < 0 on various internal errors (out of
6383      * memory, etc.).  Having some, or even all, invalid SCTs is not sufficient
6384      * reason to abort the handshake, that decision is up to the callback.
6385      * Therefore, we error out only in the unexpected case that the return
6386      * value is negative.
6387      *
6388      * XXX: One might well argue that the return value of this function is an
6389      * unfortunate design choice.  Its job is only to determine the validation
6390      * status of each of the provided SCTs.  So long as it correctly separates
6391      * the wheat from the chaff it should return success.  Failure in this case
6392      * ought to correspond to an inability to carry out its duties.
6393      */
6394     if (SCT_LIST_validate(scts, ctx) < 0) {
6395         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_SCT_VERIFICATION_FAILED);
6396         goto end;
6397     }
6398
6399     ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
6400     if (ret < 0)
6401         ret = 0;                /* This function returns 0 on failure */
6402     if (!ret)
6403         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_CALLBACK_FAILED);
6404
6405  end:
6406     CT_POLICY_EVAL_CTX_free(ctx);
6407     /*
6408      * With SSL_VERIFY_NONE the session may be cached and re-used despite a
6409      * failure return code here.  Also the application may wish the complete
6410      * the handshake, and then disconnect cleanly at a higher layer, after
6411      * checking the verification status of the completed connection.
6412      *
6413      * We therefore force a certificate verification failure which will be
6414      * visible via SSL_get_verify_result() and cached as part of any resumed
6415      * session.
6416      *
6417      * Note: the permissive callback is for information gathering only, always
6418      * returns success, and does not affect verification status.  Only the
6419      * strict callback or a custom application-specified callback can trigger
6420      * connection failure or record a verification error.
6421      */
6422     if (ret <= 0)
6423         s->verify_result = X509_V_ERR_NO_VALID_SCTS;
6424     return ret;
6425 }
6426
6427 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
6428 {
6429     switch (validation_mode) {
6430     default:
6431         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
6432         return 0;
6433     case SSL_CT_VALIDATION_PERMISSIVE:
6434         return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
6435     case SSL_CT_VALIDATION_STRICT:
6436         return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
6437     }
6438 }
6439
6440 int SSL_enable_ct(SSL *s, int validation_mode)
6441 {
6442     switch (validation_mode) {
6443     default:
6444         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
6445         return 0;
6446     case SSL_CT_VALIDATION_PERMISSIVE:
6447         return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
6448     case SSL_CT_VALIDATION_STRICT:
6449         return SSL_set_ct_validation_callback(s, ct_strict, NULL);
6450     }
6451 }
6452
6453 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
6454 {
6455     return CTLOG_STORE_load_default_file(ctx->ctlog_store);
6456 }
6457
6458 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
6459 {
6460     return CTLOG_STORE_load_file(ctx->ctlog_store, path);
6461 }
6462
6463 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs)
6464 {
6465     CTLOG_STORE_free(ctx->ctlog_store);
6466     ctx->ctlog_store = logs;
6467 }
6468
6469 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
6470 {
6471     return ctx->ctlog_store;
6472 }
6473
6474 #endif  /* OPENSSL_NO_CT */
6475
6476 void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
6477                                  void *arg)
6478 {
6479     c->client_hello_cb = cb;
6480     c->client_hello_cb_arg = arg;
6481 }
6482
6483 int SSL_client_hello_isv2(SSL *s)
6484 {
6485     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6486
6487     if (sc == NULL)
6488         return 0;
6489
6490     if (sc->clienthello == NULL)
6491         return 0;
6492     return sc->clienthello->isv2;
6493 }
6494
6495 unsigned int SSL_client_hello_get0_legacy_version(SSL *s)
6496 {
6497     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6498
6499     if (sc == NULL)
6500         return 0;
6501
6502     if (sc->clienthello == NULL)
6503         return 0;
6504     return sc->clienthello->legacy_version;
6505 }
6506
6507 size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out)
6508 {
6509     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6510
6511     if (sc == NULL)
6512         return 0;
6513
6514     if (sc->clienthello == NULL)
6515         return 0;
6516     if (out != NULL)
6517         *out = sc->clienthello->random;
6518     return SSL3_RANDOM_SIZE;
6519 }
6520
6521 size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out)
6522 {
6523     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6524
6525     if (sc == NULL)
6526         return 0;
6527
6528     if (sc->clienthello == NULL)
6529         return 0;
6530     if (out != NULL)
6531         *out = sc->clienthello->session_id;
6532     return sc->clienthello->session_id_len;
6533 }
6534
6535 size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out)
6536 {
6537     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6538
6539     if (sc == NULL)
6540         return 0;
6541
6542     if (sc->clienthello == NULL)
6543         return 0;
6544     if (out != NULL)
6545         *out = PACKET_data(&sc->clienthello->ciphersuites);
6546     return PACKET_remaining(&sc->clienthello->ciphersuites);
6547 }
6548
6549 size_t SSL_client_hello_get0_compression_methods(SSL *s, const unsigned char **out)
6550 {
6551     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6552
6553     if (sc == NULL)
6554         return 0;
6555
6556     if (sc->clienthello == NULL)
6557         return 0;
6558     if (out != NULL)
6559         *out = sc->clienthello->compressions;
6560     return sc->clienthello->compressions_len;
6561 }
6562
6563 int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen)
6564 {
6565     RAW_EXTENSION *ext;
6566     int *present;
6567     size_t num = 0, i;
6568     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6569
6570     if (sc == NULL)
6571         return 0;
6572
6573     if (sc->clienthello == NULL || out == NULL || outlen == NULL)
6574         return 0;
6575     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6576         ext = sc->clienthello->pre_proc_exts + i;
6577         if (ext->present)
6578             num++;
6579     }
6580     if (num == 0) {
6581         *out = NULL;
6582         *outlen = 0;
6583         return 1;
6584     }
6585     if ((present = OPENSSL_malloc(sizeof(*present) * num)) == NULL)
6586         return 0;
6587     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6588         ext = sc->clienthello->pre_proc_exts + i;
6589         if (ext->present) {
6590             if (ext->received_order >= num)
6591                 goto err;
6592             present[ext->received_order] = ext->type;
6593         }
6594     }
6595     *out = present;
6596     *outlen = num;
6597     return 1;
6598  err:
6599     OPENSSL_free(present);
6600     return 0;
6601 }
6602
6603 int SSL_client_hello_get_extension_order(SSL *s, uint16_t *exts, size_t *num_exts)
6604 {
6605     RAW_EXTENSION *ext;
6606     size_t num = 0, i;
6607     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6608
6609     if (sc == NULL)
6610         return 0;
6611
6612     if (sc->clienthello == NULL || num_exts == NULL)
6613         return 0;
6614     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6615         ext = sc->clienthello->pre_proc_exts + i;
6616         if (ext->present)
6617             num++;
6618     }
6619     if (num == 0) {
6620         *num_exts = 0;
6621         return 1;
6622     }
6623     if (exts == NULL) {
6624         *num_exts = num;
6625         return 1;
6626     }
6627     if (*num_exts < num)
6628         return 0;
6629     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6630         ext = sc->clienthello->pre_proc_exts + i;
6631         if (ext->present) {
6632             if (ext->received_order >= num)
6633                 return 0;
6634             exts[ext->received_order] = ext->type;
6635         }
6636     }
6637     *num_exts = num;
6638     return 1;
6639 }
6640
6641 int SSL_client_hello_get0_ext(SSL *s, unsigned int type, const unsigned char **out,
6642                        size_t *outlen)
6643 {
6644     size_t i;
6645     RAW_EXTENSION *r;
6646     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6647
6648     if (sc == NULL)
6649         return 0;
6650
6651     if (sc->clienthello == NULL)
6652         return 0;
6653     for (i = 0; i < sc->clienthello->pre_proc_exts_len; ++i) {
6654         r = sc->clienthello->pre_proc_exts + i;
6655         if (r->present && r->type == type) {
6656             if (out != NULL)
6657                 *out = PACKET_data(&r->data);
6658             if (outlen != NULL)
6659                 *outlen = PACKET_remaining(&r->data);
6660             return 1;
6661         }
6662     }
6663     return 0;
6664 }
6665
6666 int SSL_free_buffers(SSL *ssl)
6667 {
6668     RECORD_LAYER *rl;
6669     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
6670
6671     if (sc == NULL)
6672         return 0;
6673
6674     rl = &sc->rlayer;
6675
6676     return rl->rrlmethod->free_buffers(rl->rrl)
6677            && rl->wrlmethod->free_buffers(rl->wrl);
6678 }
6679
6680 int SSL_alloc_buffers(SSL *ssl)
6681 {
6682     RECORD_LAYER *rl;
6683     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
6684
6685     if (sc == NULL)
6686         return 0;
6687
6688     /* QUIC always has buffers allocated. */
6689     if (IS_QUIC(ssl))
6690         return 1;
6691
6692     rl = &sc->rlayer;
6693
6694     return rl->rrlmethod->alloc_buffers(rl->rrl)
6695            && rl->wrlmethod->alloc_buffers(rl->wrl);
6696 }
6697
6698 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
6699 {
6700     ctx->keylog_callback = cb;
6701 }
6702
6703 SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
6704 {
6705     return ctx->keylog_callback;
6706 }
6707
6708 static int nss_keylog_int(const char *prefix,
6709                           SSL_CONNECTION *sc,
6710                           const uint8_t *parameter_1,
6711                           size_t parameter_1_len,
6712                           const uint8_t *parameter_2,
6713                           size_t parameter_2_len)
6714 {
6715     char *out = NULL;
6716     char *cursor = NULL;
6717     size_t out_len = 0;
6718     size_t i;
6719     size_t prefix_len;
6720     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
6721
6722     if (sctx->keylog_callback == NULL)
6723         return 1;
6724
6725     /*
6726      * Our output buffer will contain the following strings, rendered with
6727      * space characters in between, terminated by a NULL character: first the
6728      * prefix, then the first parameter, then the second parameter. The
6729      * meaning of each parameter depends on the specific key material being
6730      * logged. Note that the first and second parameters are encoded in
6731      * hexadecimal, so we need a buffer that is twice their lengths.
6732      */
6733     prefix_len = strlen(prefix);
6734     out_len = prefix_len + (2 * parameter_1_len) + (2 * parameter_2_len) + 3;
6735     if ((out = cursor = OPENSSL_malloc(out_len)) == NULL)
6736         return 0;
6737
6738     strcpy(cursor, prefix);
6739     cursor += prefix_len;
6740     *cursor++ = ' ';
6741
6742     for (i = 0; i < parameter_1_len; i++) {
6743         sprintf(cursor, "%02x", parameter_1[i]);
6744         cursor += 2;
6745     }
6746     *cursor++ = ' ';
6747
6748     for (i = 0; i < parameter_2_len; i++) {
6749         sprintf(cursor, "%02x", parameter_2[i]);
6750         cursor += 2;
6751     }
6752     *cursor = '\0';
6753
6754     sctx->keylog_callback(SSL_CONNECTION_GET_SSL(sc), (const char *)out);
6755     OPENSSL_clear_free(out, out_len);
6756     return 1;
6757
6758 }
6759
6760 int ssl_log_rsa_client_key_exchange(SSL_CONNECTION *sc,
6761                                     const uint8_t *encrypted_premaster,
6762                                     size_t encrypted_premaster_len,
6763                                     const uint8_t *premaster,
6764                                     size_t premaster_len)
6765 {
6766     if (encrypted_premaster_len < 8) {
6767         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
6768         return 0;
6769     }
6770
6771     /* We only want the first 8 bytes of the encrypted premaster as a tag. */
6772     return nss_keylog_int("RSA",
6773                           sc,
6774                           encrypted_premaster,
6775                           8,
6776                           premaster,
6777                           premaster_len);
6778 }
6779
6780 int ssl_log_secret(SSL_CONNECTION *sc,
6781                    const char *label,
6782                    const uint8_t *secret,
6783                    size_t secret_len)
6784 {
6785     return nss_keylog_int(label,
6786                           sc,
6787                           sc->s3.client_random,
6788                           SSL3_RANDOM_SIZE,
6789                           secret,
6790                           secret_len);
6791 }
6792
6793 #define SSLV2_CIPHER_LEN    3
6794
6795 int ssl_cache_cipherlist(SSL_CONNECTION *s, PACKET *cipher_suites, int sslv2format)
6796 {
6797     int n;
6798
6799     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
6800
6801     if (PACKET_remaining(cipher_suites) == 0) {
6802         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
6803         return 0;
6804     }
6805
6806     if (PACKET_remaining(cipher_suites) % n != 0) {
6807         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6808         return 0;
6809     }
6810
6811     OPENSSL_free(s->s3.tmp.ciphers_raw);
6812     s->s3.tmp.ciphers_raw = NULL;
6813     s->s3.tmp.ciphers_rawlen = 0;
6814
6815     if (sslv2format) {
6816         size_t numciphers = PACKET_remaining(cipher_suites) / n;
6817         PACKET sslv2ciphers = *cipher_suites;
6818         unsigned int leadbyte;
6819         unsigned char *raw;
6820
6821         /*
6822          * We store the raw ciphers list in SSLv3+ format so we need to do some
6823          * preprocessing to convert the list first. If there are any SSLv2 only
6824          * ciphersuites with a non-zero leading byte then we are going to
6825          * slightly over allocate because we won't store those. But that isn't a
6826          * problem.
6827          */
6828         raw = OPENSSL_malloc(numciphers * TLS_CIPHER_LEN);
6829         s->s3.tmp.ciphers_raw = raw;
6830         if (raw == NULL) {
6831             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6832             return 0;
6833         }
6834         for (s->s3.tmp.ciphers_rawlen = 0;
6835              PACKET_remaining(&sslv2ciphers) > 0;
6836              raw += TLS_CIPHER_LEN) {
6837             if (!PACKET_get_1(&sslv2ciphers, &leadbyte)
6838                     || (leadbyte == 0
6839                         && !PACKET_copy_bytes(&sslv2ciphers, raw,
6840                                               TLS_CIPHER_LEN))
6841                     || (leadbyte != 0
6842                         && !PACKET_forward(&sslv2ciphers, TLS_CIPHER_LEN))) {
6843                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
6844                 OPENSSL_free(s->s3.tmp.ciphers_raw);
6845                 s->s3.tmp.ciphers_raw = NULL;
6846                 s->s3.tmp.ciphers_rawlen = 0;
6847                 return 0;
6848             }
6849             if (leadbyte == 0)
6850                 s->s3.tmp.ciphers_rawlen += TLS_CIPHER_LEN;
6851         }
6852     } else if (!PACKET_memdup(cipher_suites, &s->s3.tmp.ciphers_raw,
6853                            &s->s3.tmp.ciphers_rawlen)) {
6854         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
6855         return 0;
6856     }
6857     return 1;
6858 }
6859
6860 int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
6861                              int isv2format, STACK_OF(SSL_CIPHER) **sk,
6862                              STACK_OF(SSL_CIPHER) **scsvs)
6863 {
6864     PACKET pkt;
6865     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6866
6867     if (sc == NULL)
6868         return 0;
6869
6870     if (!PACKET_buf_init(&pkt, bytes, len))
6871         return 0;
6872     return ossl_bytes_to_cipher_list(sc, &pkt, sk, scsvs, isv2format, 0);
6873 }
6874
6875 int ossl_bytes_to_cipher_list(SSL_CONNECTION *s, PACKET *cipher_suites,
6876                               STACK_OF(SSL_CIPHER) **skp,
6877                               STACK_OF(SSL_CIPHER) **scsvs_out,
6878                               int sslv2format, int fatal)
6879 {
6880     const SSL_CIPHER *c;
6881     STACK_OF(SSL_CIPHER) *sk = NULL;
6882     STACK_OF(SSL_CIPHER) *scsvs = NULL;
6883     int n;
6884     /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
6885     unsigned char cipher[SSLV2_CIPHER_LEN];
6886
6887     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
6888
6889     if (PACKET_remaining(cipher_suites) == 0) {
6890         if (fatal)
6891             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
6892         else
6893             ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHERS_SPECIFIED);
6894         return 0;
6895     }
6896
6897     if (PACKET_remaining(cipher_suites) % n != 0) {
6898         if (fatal)
6899             SSLfatal(s, SSL_AD_DECODE_ERROR,
6900                      SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6901         else
6902             ERR_raise(ERR_LIB_SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6903         return 0;
6904     }
6905
6906     sk = sk_SSL_CIPHER_new_null();
6907     scsvs = sk_SSL_CIPHER_new_null();
6908     if (sk == NULL || scsvs == NULL) {
6909         if (fatal)
6910             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6911         else
6912             ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
6913         goto err;
6914     }
6915
6916     while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
6917         /*
6918          * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
6919          * first byte set to zero, while true SSLv2 ciphers have a non-zero
6920          * first byte. We don't support any true SSLv2 ciphers, so skip them.
6921          */
6922         if (sslv2format && cipher[0] != '\0')
6923             continue;
6924
6925         /* For SSLv2-compat, ignore leading 0-byte. */
6926         c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher, 1);
6927         if (c != NULL) {
6928             if ((c->valid && !sk_SSL_CIPHER_push(sk, c)) ||
6929                 (!c->valid && !sk_SSL_CIPHER_push(scsvs, c))) {
6930                 if (fatal)
6931                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6932                 else
6933                     ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
6934                 goto err;
6935             }
6936         }
6937     }
6938     if (PACKET_remaining(cipher_suites) > 0) {
6939         if (fatal)
6940             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
6941         else
6942             ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
6943         goto err;
6944     }
6945
6946     if (skp != NULL)
6947         *skp = sk;
6948     else
6949         sk_SSL_CIPHER_free(sk);
6950     if (scsvs_out != NULL)
6951         *scsvs_out = scsvs;
6952     else
6953         sk_SSL_CIPHER_free(scsvs);
6954     return 1;
6955  err:
6956     sk_SSL_CIPHER_free(sk);
6957     sk_SSL_CIPHER_free(scsvs);
6958     return 0;
6959 }
6960
6961 int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
6962 {
6963     ctx->max_early_data = max_early_data;
6964
6965     return 1;
6966 }
6967
6968 uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
6969 {
6970     return ctx->max_early_data;
6971 }
6972
6973 int SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
6974 {
6975     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
6976
6977     if (sc == NULL)
6978         return 0;
6979
6980     sc->max_early_data = max_early_data;
6981
6982     return 1;
6983 }
6984
6985 uint32_t SSL_get_max_early_data(const SSL *s)
6986 {
6987     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
6988
6989     if (sc == NULL)
6990         return 0;
6991
6992     return sc->max_early_data;
6993 }
6994
6995 int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data)
6996 {
6997     ctx->recv_max_early_data = recv_max_early_data;
6998
6999     return 1;
7000 }
7001
7002 uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx)
7003 {
7004     return ctx->recv_max_early_data;
7005 }
7006
7007 int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data)
7008 {
7009     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
7010
7011     if (sc == NULL)
7012         return 0;
7013
7014     sc->recv_max_early_data = recv_max_early_data;
7015
7016     return 1;
7017 }
7018
7019 uint32_t SSL_get_recv_max_early_data(const SSL *s)
7020 {
7021     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
7022
7023     if (sc == NULL)
7024         return 0;
7025
7026     return sc->recv_max_early_data;
7027 }
7028
7029 __owur unsigned int ssl_get_max_send_fragment(const SSL_CONNECTION *sc)
7030 {
7031     /* Return any active Max Fragment Len extension */
7032     if (sc->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(sc->session))
7033         return GET_MAX_FRAGMENT_LENGTH(sc->session);
7034
7035     /* return current SSL connection setting */
7036     return sc->max_send_fragment;
7037 }
7038
7039 __owur unsigned int ssl_get_split_send_fragment(const SSL_CONNECTION *sc)
7040 {
7041     /* Return a value regarding an active Max Fragment Len extension */
7042     if (sc->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(sc->session)
7043         && sc->split_send_fragment > GET_MAX_FRAGMENT_LENGTH(sc->session))
7044         return GET_MAX_FRAGMENT_LENGTH(sc->session);
7045
7046     /* else limit |split_send_fragment| to current |max_send_fragment| */
7047     if (sc->split_send_fragment > sc->max_send_fragment)
7048         return sc->max_send_fragment;
7049
7050     /* return current SSL connection setting */
7051     return sc->split_send_fragment;
7052 }
7053
7054 int SSL_stateless(SSL *s)
7055 {
7056     int ret;
7057     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
7058
7059     if (sc == NULL)
7060         return 0;
7061
7062     /* Ensure there is no state left over from a previous invocation */
7063     if (!SSL_clear(s))
7064         return 0;
7065
7066     ERR_clear_error();
7067
7068     sc->s3.flags |= TLS1_FLAGS_STATELESS;
7069     ret = SSL_accept(s);
7070     sc->s3.flags &= ~TLS1_FLAGS_STATELESS;
7071
7072     if (ret > 0 && sc->ext.cookieok)
7073         return 1;
7074
7075     if (sc->hello_retry_request == SSL_HRR_PENDING && !ossl_statem_in_error(sc))
7076         return 0;
7077
7078     return -1;
7079 }
7080
7081 void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val)
7082 {
7083     ctx->pha_enabled = val;
7084 }
7085
7086 void SSL_set_post_handshake_auth(SSL *ssl, int val)
7087 {
7088     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
7089
7090     if (sc == NULL)
7091         return;
7092
7093     sc->pha_enabled = val;
7094 }
7095
7096 int SSL_verify_client_post_handshake(SSL *ssl)
7097 {
7098     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
7099
7100 #ifndef OPENSSL_NO_QUIC
7101     if (IS_QUIC(ssl)) {
7102         ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
7103         return 0;
7104     }
7105 #endif
7106
7107     if (sc == NULL)
7108         return 0;
7109
7110     if (!SSL_CONNECTION_IS_TLS13(sc)) {
7111         ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
7112         return 0;
7113     }
7114     if (!sc->server) {
7115         ERR_raise(ERR_LIB_SSL, SSL_R_NOT_SERVER);
7116         return 0;
7117     }
7118
7119     if (!SSL_is_init_finished(ssl)) {
7120         ERR_raise(ERR_LIB_SSL, SSL_R_STILL_IN_INIT);
7121         return 0;
7122     }
7123
7124     switch (sc->post_handshake_auth) {
7125     case SSL_PHA_NONE:
7126         ERR_raise(ERR_LIB_SSL, SSL_R_EXTENSION_NOT_RECEIVED);
7127         return 0;
7128     default:
7129     case SSL_PHA_EXT_SENT:
7130         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
7131         return 0;
7132     case SSL_PHA_EXT_RECEIVED:
7133         break;
7134     case SSL_PHA_REQUEST_PENDING:
7135         ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_PENDING);
7136         return 0;
7137     case SSL_PHA_REQUESTED:
7138         ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_SENT);
7139         return 0;
7140     }
7141
7142     sc->post_handshake_auth = SSL_PHA_REQUEST_PENDING;
7143
7144     /* checks verify_mode and algorithm_auth */
7145     if (!send_certificate_request(sc)) {
7146         sc->post_handshake_auth = SSL_PHA_EXT_RECEIVED; /* restore on error */
7147         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CONFIG);
7148         return 0;
7149     }
7150
7151     ossl_statem_set_in_init(sc, 1);
7152     return 1;
7153 }
7154
7155 int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
7156                                   SSL_CTX_generate_session_ticket_fn gen_cb,
7157                                   SSL_CTX_decrypt_session_ticket_fn dec_cb,
7158                                   void *arg)
7159 {
7160     ctx->generate_ticket_cb = gen_cb;
7161     ctx->decrypt_ticket_cb = dec_cb;
7162     ctx->ticket_cb_data = arg;
7163     return 1;
7164 }
7165
7166 void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
7167                                      SSL_allow_early_data_cb_fn cb,
7168                                      void *arg)
7169 {
7170     ctx->allow_early_data_cb = cb;
7171     ctx->allow_early_data_cb_data = arg;
7172 }
7173
7174 void SSL_set_allow_early_data_cb(SSL *s,
7175                                  SSL_allow_early_data_cb_fn cb,
7176                                  void *arg)
7177 {
7178     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
7179
7180     if (sc == NULL)
7181         return;
7182
7183     sc->allow_early_data_cb = cb;
7184     sc->allow_early_data_cb_data = arg;
7185 }
7186
7187 const EVP_CIPHER *ssl_evp_cipher_fetch(OSSL_LIB_CTX *libctx,
7188                                        int nid,
7189                                        const char *properties)
7190 {
7191     const EVP_CIPHER *ciph;
7192
7193     ciph = tls_get_cipher_from_engine(nid);
7194     if (ciph != NULL)
7195         return ciph;
7196
7197     /*
7198      * If there is no engine cipher then we do an explicit fetch. This may fail
7199      * and that could be ok
7200      */
7201     ERR_set_mark();
7202     ciph = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(nid), properties);
7203     ERR_pop_to_mark();
7204     return ciph;
7205 }
7206
7207
7208 int ssl_evp_cipher_up_ref(const EVP_CIPHER *cipher)
7209 {
7210     /* Don't up-ref an implicit EVP_CIPHER */
7211     if (EVP_CIPHER_get0_provider(cipher) == NULL)
7212         return 1;
7213
7214     /*
7215      * The cipher was explicitly fetched and therefore it is safe to cast
7216      * away the const
7217      */
7218     return EVP_CIPHER_up_ref((EVP_CIPHER *)cipher);
7219 }
7220
7221 void ssl_evp_cipher_free(const EVP_CIPHER *cipher)
7222 {
7223     if (cipher == NULL)
7224         return;
7225
7226     if (EVP_CIPHER_get0_provider(cipher) != NULL) {
7227         /*
7228          * The cipher was explicitly fetched and therefore it is safe to cast
7229          * away the const
7230          */
7231         EVP_CIPHER_free((EVP_CIPHER *)cipher);
7232     }
7233 }
7234
7235 const EVP_MD *ssl_evp_md_fetch(OSSL_LIB_CTX *libctx,
7236                                int nid,
7237                                const char *properties)
7238 {
7239     const EVP_MD *md;
7240
7241     md = tls_get_digest_from_engine(nid);
7242     if (md != NULL)
7243         return md;
7244
7245     /* Otherwise we do an explicit fetch */
7246     ERR_set_mark();
7247     md = EVP_MD_fetch(libctx, OBJ_nid2sn(nid), properties);
7248     ERR_pop_to_mark();
7249     return md;
7250 }
7251
7252 int ssl_evp_md_up_ref(const EVP_MD *md)
7253 {
7254     /* Don't up-ref an implicit EVP_MD */
7255     if (EVP_MD_get0_provider(md) == NULL)
7256         return 1;
7257
7258     /*
7259      * The digest was explicitly fetched and therefore it is safe to cast
7260      * away the const
7261      */
7262     return EVP_MD_up_ref((EVP_MD *)md);
7263 }
7264
7265 void ssl_evp_md_free(const EVP_MD *md)
7266 {
7267     if (md == NULL)
7268         return;
7269
7270     if (EVP_MD_get0_provider(md) != NULL) {
7271         /*
7272          * The digest was explicitly fetched and therefore it is safe to cast
7273          * away the const
7274          */
7275         EVP_MD_free((EVP_MD *)md);
7276     }
7277 }
7278
7279 int SSL_set0_tmp_dh_pkey(SSL *s, EVP_PKEY *dhpkey)
7280 {
7281     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7282
7283     if (sc == NULL)
7284         return 0;
7285
7286     if (!ssl_security(sc, SSL_SECOP_TMP_DH,
7287                       EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
7288         ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
7289         return 0;
7290     }
7291     EVP_PKEY_free(sc->cert->dh_tmp);
7292     sc->cert->dh_tmp = dhpkey;
7293     return 1;
7294 }
7295
7296 int SSL_CTX_set0_tmp_dh_pkey(SSL_CTX *ctx, EVP_PKEY *dhpkey)
7297 {
7298     if (!ssl_ctx_security(ctx, SSL_SECOP_TMP_DH,
7299                           EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
7300         ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
7301         return 0;
7302     }
7303     EVP_PKEY_free(ctx->cert->dh_tmp);
7304     ctx->cert->dh_tmp = dhpkey;
7305     return 1;
7306 }
7307
7308 /* QUIC-specific methods which are supported on QUIC connections only. */
7309 int SSL_handle_events(SSL *s)
7310 {
7311     SSL_CONNECTION *sc;
7312
7313 #ifndef OPENSSL_NO_QUIC
7314     if (IS_QUIC(s))
7315         return ossl_quic_handle_events(s);
7316 #endif
7317
7318     sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
7319     if (sc != NULL && SSL_CONNECTION_IS_DTLS(sc))
7320         /*
7321          * DTLSv1_handle_timeout returns 0 if the timer wasn't expired yet,
7322          * which we consider a success case. Theoretically DTLSv1_handle_timeout
7323          * can also return 0 if s is NULL or not a DTLS object, but we've
7324          * already ruled out those possibilities above, so this is not possible
7325          * here. Thus the only failure cases are where DTLSv1_handle_timeout
7326          * returns -1.
7327          */
7328         return DTLSv1_handle_timeout(s) >= 0;
7329
7330     return 1;
7331 }
7332
7333 int SSL_get_event_timeout(SSL *s, struct timeval *tv, int *is_infinite)
7334 {
7335     SSL_CONNECTION *sc;
7336
7337 #ifndef OPENSSL_NO_QUIC
7338     if (IS_QUIC(s))
7339         return ossl_quic_get_event_timeout(s, tv, is_infinite);
7340 #endif
7341
7342     sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
7343     if (sc != NULL && SSL_CONNECTION_IS_DTLS(sc)
7344         && DTLSv1_get_timeout(s, tv)) {
7345         *is_infinite = 0;
7346         return 1;
7347     }
7348
7349     tv->tv_sec  = 1000000;
7350     tv->tv_usec = 0;
7351     *is_infinite = 1;
7352     return 1;
7353 }
7354
7355 int SSL_get_rpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc)
7356 {
7357     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7358
7359 #ifndef OPENSSL_NO_QUIC
7360     if (IS_QUIC(s))
7361         return ossl_quic_get_rpoll_descriptor(s, desc);
7362 #endif
7363
7364     if (sc == NULL || sc->rbio == NULL)
7365         return 0;
7366
7367     return BIO_get_rpoll_descriptor(sc->rbio, desc);
7368 }
7369
7370 int SSL_get_wpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc)
7371 {
7372     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7373
7374 #ifndef OPENSSL_NO_QUIC
7375     if (IS_QUIC(s))
7376         return ossl_quic_get_wpoll_descriptor(s, desc);
7377 #endif
7378
7379     if (sc == NULL || sc->wbio == NULL)
7380         return 0;
7381
7382     return BIO_get_wpoll_descriptor(sc->wbio, desc);
7383 }
7384
7385 int SSL_net_read_desired(SSL *s)
7386 {
7387 #ifndef OPENSSL_NO_QUIC
7388     if (!IS_QUIC(s))
7389         return SSL_want_read(s);
7390
7391     return ossl_quic_get_net_read_desired(s);
7392 #else
7393     return SSL_want_read(s);
7394 #endif
7395 }
7396
7397 int SSL_net_write_desired(SSL *s)
7398 {
7399 #ifndef OPENSSL_NO_QUIC
7400     if (!IS_QUIC(s))
7401         return SSL_want_write(s);
7402
7403     return ossl_quic_get_net_write_desired(s);
7404 #else
7405     return SSL_want_write(s);
7406 #endif
7407 }
7408
7409 int SSL_set_blocking_mode(SSL *s, int blocking)
7410 {
7411 #ifndef OPENSSL_NO_QUIC
7412     if (!IS_QUIC(s))
7413         return 0;
7414
7415     return ossl_quic_conn_set_blocking_mode(s, blocking);
7416 #else
7417     return 0;
7418 #endif
7419 }
7420
7421 int SSL_get_blocking_mode(SSL *s)
7422 {
7423 #ifndef OPENSSL_NO_QUIC
7424     if (!IS_QUIC(s))
7425         return -1;
7426
7427     return ossl_quic_conn_get_blocking_mode(s);
7428 #else
7429     return -1;
7430 #endif
7431 }
7432
7433 int SSL_set1_initial_peer_addr(SSL *s, const BIO_ADDR *peer_addr)
7434 {
7435 #ifndef OPENSSL_NO_QUIC
7436     if (!IS_QUIC(s))
7437         return 0;
7438
7439     return ossl_quic_conn_set_initial_peer_addr(s, peer_addr);
7440 #else
7441     return 0;
7442 #endif
7443 }
7444
7445 int SSL_shutdown_ex(SSL *ssl, uint64_t flags,
7446                     const SSL_SHUTDOWN_EX_ARGS *args,
7447                     size_t args_len)
7448 {
7449 #ifndef OPENSSL_NO_QUIC
7450     if (!IS_QUIC(ssl))
7451         return SSL_shutdown(ssl);
7452
7453     return ossl_quic_conn_shutdown(ssl, flags, args, args_len);
7454 #else
7455     return SSL_shutdown(ssl);
7456 #endif
7457 }
7458
7459 int SSL_stream_conclude(SSL *ssl, uint64_t flags)
7460 {
7461 #ifndef OPENSSL_NO_QUIC
7462     if (!IS_QUIC(ssl))
7463         return 0;
7464
7465     return ossl_quic_conn_stream_conclude(ssl);
7466 #else
7467     return 0;
7468 #endif
7469 }
7470
7471 SSL *SSL_new_stream(SSL *s, uint64_t flags)
7472 {
7473 #ifndef OPENSSL_NO_QUIC
7474     if (!IS_QUIC(s))
7475         return NULL;
7476
7477     return ossl_quic_conn_stream_new(s, flags);
7478 #else
7479     return NULL;
7480 #endif
7481 }
7482
7483 SSL *SSL_get0_connection(SSL *s)
7484 {
7485 #ifndef OPENSSL_NO_QUIC
7486     if (!IS_QUIC(s))
7487         return s;
7488
7489     return ossl_quic_get0_connection(s);
7490 #else
7491     return s;
7492 #endif
7493 }
7494
7495 int SSL_is_connection(SSL *s)
7496 {
7497     return SSL_get0_connection(s) == s;
7498 }
7499
7500 int SSL_get_stream_type(SSL *s)
7501 {
7502 #ifndef OPENSSL_NO_QUIC
7503     if (!IS_QUIC(s))
7504         return SSL_STREAM_TYPE_BIDI;
7505
7506     return ossl_quic_get_stream_type(s);
7507 #else
7508     return SSL_STREAM_TYPE_BIDI;
7509 #endif
7510 }
7511
7512 uint64_t SSL_get_stream_id(SSL *s)
7513 {
7514 #ifndef OPENSSL_NO_QUIC
7515     if (!IS_QUIC(s))
7516         return UINT64_MAX;
7517
7518     return ossl_quic_get_stream_id(s);
7519 #else
7520     return UINT64_MAX;
7521 #endif
7522 }
7523
7524 int SSL_is_stream_local(SSL *s)
7525 {
7526 #ifndef OPENSSL_NO_QUIC
7527     if (!IS_QUIC(s))
7528         return -1;
7529
7530     return ossl_quic_is_stream_local(s);
7531 #else
7532     return -1;
7533 #endif
7534 }
7535
7536 int SSL_set_default_stream_mode(SSL *s, uint32_t mode)
7537 {
7538 #ifndef OPENSSL_NO_QUIC
7539     if (!IS_QUIC(s))
7540         return 0;
7541
7542     return ossl_quic_set_default_stream_mode(s, mode);
7543 #else
7544     return 0;
7545 #endif
7546 }
7547
7548 int SSL_set_incoming_stream_policy(SSL *s, int policy, uint64_t aec)
7549 {
7550 #ifndef OPENSSL_NO_QUIC
7551     if (!IS_QUIC(s))
7552         return 0;
7553
7554     return ossl_quic_set_incoming_stream_policy(s, policy, aec);
7555 #else
7556     return 0;
7557 #endif
7558 }
7559
7560 SSL *SSL_accept_stream(SSL *s, uint64_t flags)
7561 {
7562 #ifndef OPENSSL_NO_QUIC
7563     if (!IS_QUIC(s))
7564         return NULL;
7565
7566     return ossl_quic_accept_stream(s, flags);
7567 #else
7568     return NULL;
7569 #endif
7570 }
7571
7572 size_t SSL_get_accept_stream_queue_len(SSL *s)
7573 {
7574 #ifndef OPENSSL_NO_QUIC
7575     if (!IS_QUIC(s))
7576         return 0;
7577
7578     return ossl_quic_get_accept_stream_queue_len(s);
7579 #else
7580     return 0;
7581 #endif
7582 }
7583
7584 int SSL_stream_reset(SSL *s,
7585                      const SSL_STREAM_RESET_ARGS *args,
7586                      size_t args_len)
7587 {
7588 #ifndef OPENSSL_NO_QUIC
7589     if (!IS_QUIC(s))
7590         return 0;
7591
7592     return ossl_quic_stream_reset(s, args, args_len);
7593 #else
7594     return 0;
7595 #endif
7596 }
7597
7598 int SSL_get_stream_read_state(SSL *s)
7599 {
7600 #ifndef OPENSSL_NO_QUIC
7601     if (!IS_QUIC(s))
7602         return SSL_STREAM_STATE_NONE;
7603
7604     return ossl_quic_get_stream_read_state(s);
7605 #else
7606     return SSL_STREAM_STATE_NONE;
7607 #endif
7608 }
7609
7610 int SSL_get_stream_write_state(SSL *s)
7611 {
7612 #ifndef OPENSSL_NO_QUIC
7613     if (!IS_QUIC(s))
7614         return SSL_STREAM_STATE_NONE;
7615
7616     return ossl_quic_get_stream_write_state(s);
7617 #else
7618     return SSL_STREAM_STATE_NONE;
7619 #endif
7620 }
7621
7622 int SSL_get_stream_read_error_code(SSL *s, uint64_t *app_error_code)
7623 {
7624 #ifndef OPENSSL_NO_QUIC
7625     if (!IS_QUIC(s))
7626         return -1;
7627
7628     return ossl_quic_get_stream_read_error_code(s, app_error_code);
7629 #else
7630     return -1;
7631 #endif
7632 }
7633
7634 int SSL_get_stream_write_error_code(SSL *s, uint64_t *app_error_code)
7635 {
7636 #ifndef OPENSSL_NO_QUIC
7637     if (!IS_QUIC(s))
7638         return -1;
7639
7640     return ossl_quic_get_stream_write_error_code(s, app_error_code);
7641 #else
7642     return -1;
7643 #endif
7644 }
7645
7646 int SSL_get_conn_close_info(SSL *s, SSL_CONN_CLOSE_INFO *info,
7647                             size_t info_len)
7648 {
7649 #ifndef OPENSSL_NO_QUIC
7650     if (!IS_QUIC(s))
7651         return -1;
7652
7653     return ossl_quic_get_conn_close_info(s, info, info_len);
7654 #else
7655     return -1;
7656 #endif
7657 }
7658
7659 int SSL_add_expected_rpk(SSL *s, EVP_PKEY *rpk)
7660 {
7661     unsigned char *data = NULL;
7662     SSL_DANE *dane = SSL_get0_dane(s);
7663     int ret;
7664
7665     if (dane == NULL || dane->dctx == NULL)
7666         return 0;
7667     if ((ret = i2d_PUBKEY(rpk, &data)) <= 0)
7668         return 0;
7669
7670     ret = SSL_dane_tlsa_add(s, DANETLS_USAGE_DANE_EE,
7671                             DANETLS_SELECTOR_SPKI,
7672                             DANETLS_MATCHING_FULL,
7673                             data, (size_t)ret) > 0;
7674     OPENSSL_free(data);
7675     return ret;
7676 }
7677
7678 EVP_PKEY *SSL_get0_peer_rpk(const SSL *s)
7679 {
7680     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7681
7682     if (sc == NULL || sc->session == NULL)
7683         return NULL;
7684     return sc->session->peer_rpk;
7685 }
7686
7687 int SSL_get_negotiated_client_cert_type(const SSL *s)
7688 {
7689     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7690
7691     if (sc == NULL)
7692         return 0;
7693
7694     return sc->ext.client_cert_type;
7695 }
7696
7697 int SSL_get_negotiated_server_cert_type(const SSL *s)
7698 {
7699     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7700
7701     if (sc == NULL)
7702         return 0;
7703
7704     return sc->ext.server_cert_type;
7705 }
7706
7707 static int validate_cert_type(const unsigned char *val, size_t len)
7708 {
7709     size_t i;
7710     int saw_rpk = 0;
7711     int saw_x509 = 0;
7712
7713     if (val == NULL && len == 0)
7714         return 1;
7715
7716     if (val == NULL || len == 0)
7717         return 0;
7718
7719     for (i = 0; i < len; i++) {
7720         switch (val[i]) {
7721         case TLSEXT_cert_type_rpk:
7722             if (saw_rpk)
7723                 return 0;
7724             saw_rpk = 1;
7725             break;
7726         case TLSEXT_cert_type_x509:
7727             if (saw_x509)
7728                 return 0;
7729             saw_x509 = 1;
7730             break;
7731         case TLSEXT_cert_type_pgp:
7732         case TLSEXT_cert_type_1609dot2:
7733         default:
7734             return 0;
7735         }
7736     }
7737     return 1;
7738 }
7739
7740 static int set_cert_type(unsigned char **cert_type,
7741                          size_t *cert_type_len,
7742                          const unsigned char *val,
7743                          size_t len)
7744 {
7745     unsigned char *tmp = NULL;
7746
7747     if (!validate_cert_type(val, len))
7748         return 0;
7749
7750     if (val != NULL && (tmp = OPENSSL_memdup(val, len)) == NULL)
7751         return 0;
7752
7753     OPENSSL_free(*cert_type);
7754     *cert_type = tmp;
7755     *cert_type_len = len;
7756     return 1;
7757 }
7758
7759 int SSL_set1_client_cert_type(SSL *s, const unsigned char *val, size_t len)
7760 {
7761     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7762
7763     return set_cert_type(&sc->client_cert_type, &sc->client_cert_type_len,
7764                          val, len);
7765 }
7766
7767 int SSL_set1_server_cert_type(SSL *s, const unsigned char *val, size_t len)
7768 {
7769     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
7770
7771     return set_cert_type(&sc->server_cert_type, &sc->server_cert_type_len,
7772                          val, len);
7773 }
7774
7775 int SSL_CTX_set1_client_cert_type(SSL_CTX *ctx, const unsigned char *val, size_t len)
7776 {
7777     return set_cert_type(&ctx->client_cert_type, &ctx->client_cert_type_len,
7778                          val, len);
7779 }
7780
7781 int SSL_CTX_set1_server_cert_type(SSL_CTX *ctx, const unsigned char *val, size_t len)
7782 {
7783     return set_cert_type(&ctx->server_cert_type, &ctx->server_cert_type_len,
7784                          val, len);
7785 }
7786
7787 int SSL_get0_client_cert_type(const SSL *s, unsigned char **t, size_t *len)
7788 {
7789     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
7790
7791     if (t == NULL || len == NULL)
7792         return 0;
7793
7794     *t = sc->client_cert_type;
7795     *len = sc->client_cert_type_len;
7796     return 1;
7797 }
7798
7799 int SSL_get0_server_cert_type(const SSL *s, unsigned char **t, size_t *len)
7800 {
7801     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
7802
7803     if (t == NULL || len == NULL)
7804         return 0;
7805
7806     *t = sc->server_cert_type;
7807     *len = sc->server_cert_type_len;
7808     return 1;
7809 }
7810
7811 int SSL_CTX_get0_client_cert_type(const SSL_CTX *ctx, unsigned char **t, size_t *len)
7812 {
7813     if (t == NULL || len == NULL)
7814         return 0;
7815
7816     *t = ctx->client_cert_type;
7817     *len = ctx->client_cert_type_len;
7818     return 1;
7819 }
7820
7821 int SSL_CTX_get0_server_cert_type(const SSL_CTX *ctx, unsigned char **t, size_t *len)
7822 {
7823     if (t == NULL || len == NULL)
7824         return 0;
7825
7826     *t = ctx->server_cert_type;
7827     *len = ctx->server_cert_type_len;
7828     return 1;
7829 }