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