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