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