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