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