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