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