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