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