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