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