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