Use the configured max_send_fragment value in the write record layer
[openssl.git] / ssl / ssl_lib.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include <stdio.h>
13 #include "ssl_local.h"
14 #include "internal/e_os.h"
15 #include <openssl/objects.h>
16 #include <openssl/x509v3.h>
17 #include <openssl/rand.h>
18 #include <openssl/ocsp.h>
19 #include <openssl/dh.h>
20 #include <openssl/engine.h>
21 #include <openssl/async.h>
22 #include <openssl/ct.h>
23 #include <openssl/trace.h>
24 #include <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         sc->rlayer.wrlmethod->set_max_frag_len(sc->rlayer.wrl, larg);
2793         return 1;
2794     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2795         if ((size_t)larg > sc->max_send_fragment || larg == 0)
2796             return 0;
2797         sc->split_send_fragment = larg;
2798         return 1;
2799     case SSL_CTRL_SET_MAX_PIPELINES:
2800         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2801             return 0;
2802         sc->max_pipelines = larg;
2803         if (sc->rlayer.rrlmethod->set_max_pipelines != NULL)
2804             sc->rlayer.rrlmethod->set_max_pipelines(sc->rlayer.rrl, (size_t)larg);
2805         return 1;
2806     case SSL_CTRL_GET_RI_SUPPORT:
2807         return sc->s3.send_connection_binding;
2808     case SSL_CTRL_SET_RETRY_VERIFY:
2809         sc->rwstate = SSL_RETRY_VERIFY;
2810         return 1;
2811     case SSL_CTRL_CERT_FLAGS:
2812         return (sc->cert->cert_flags |= larg);
2813     case SSL_CTRL_CLEAR_CERT_FLAGS:
2814         return (sc->cert->cert_flags &= ~larg);
2815
2816     case SSL_CTRL_GET_RAW_CIPHERLIST:
2817         if (parg) {
2818             if (sc->s3.tmp.ciphers_raw == NULL)
2819                 return 0;
2820             *(unsigned char **)parg = sc->s3.tmp.ciphers_raw;
2821             return (int)sc->s3.tmp.ciphers_rawlen;
2822         } else {
2823             return TLS_CIPHER_LEN;
2824         }
2825     case SSL_CTRL_GET_EXTMS_SUPPORT:
2826         if (!sc->session || SSL_in_init(s) || ossl_statem_get_in_handshake(sc))
2827             return -1;
2828         if (sc->session->flags & SSL_SESS_FLAG_EXTMS)
2829             return 1;
2830         else
2831             return 0;
2832     case SSL_CTRL_SET_MIN_PROTO_VERSION:
2833         return ssl_check_allowed_versions(larg, sc->max_proto_version)
2834                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2835                                         &sc->min_proto_version);
2836     case SSL_CTRL_GET_MIN_PROTO_VERSION:
2837         return sc->min_proto_version;
2838     case SSL_CTRL_SET_MAX_PROTO_VERSION:
2839         return ssl_check_allowed_versions(sc->min_proto_version, larg)
2840                && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2841                                         &sc->max_proto_version);
2842     case SSL_CTRL_GET_MAX_PROTO_VERSION:
2843         return sc->max_proto_version;
2844     default:
2845         return s->method->ssl_ctrl(s, cmd, larg, parg);
2846     }
2847 }
2848
2849 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
2850 {
2851     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
2852
2853     if (sc == NULL)
2854         return 0;
2855
2856     switch (cmd) {
2857     case SSL_CTRL_SET_MSG_CALLBACK:
2858         sc->msg_callback = (void (*)
2859                             (int write_p, int version, int content_type,
2860                              const void *buf, size_t len, SSL *ssl,
2861                              void *arg))(fp);
2862         return 1;
2863
2864     default:
2865         return s->method->ssl_callback_ctrl(s, cmd, fp);
2866     }
2867 }
2868
2869 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
2870 {
2871     return ctx->sessions;
2872 }
2873
2874 static int ssl_tsan_load(SSL_CTX *ctx, TSAN_QUALIFIER int *stat)
2875 {
2876     int res = 0;
2877
2878     if (ssl_tsan_lock(ctx)) {
2879         res = tsan_load(stat);
2880         ssl_tsan_unlock(ctx);
2881     }
2882     return res;
2883 }
2884
2885 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
2886 {
2887     long l;
2888     /* For some cases with ctx == NULL perform syntax checks */
2889     if (ctx == NULL) {
2890         switch (cmd) {
2891         case SSL_CTRL_SET_GROUPS_LIST:
2892             return tls1_set_groups_list(ctx, NULL, NULL, parg);
2893         case SSL_CTRL_SET_SIGALGS_LIST:
2894         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
2895             return tls1_set_sigalgs_list(NULL, parg, 0);
2896         default:
2897             return 0;
2898         }
2899     }
2900
2901     switch (cmd) {
2902     case SSL_CTRL_GET_READ_AHEAD:
2903         return ctx->read_ahead;
2904     case SSL_CTRL_SET_READ_AHEAD:
2905         l = ctx->read_ahead;
2906         ctx->read_ahead = larg;
2907         return l;
2908
2909     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2910         ctx->msg_callback_arg = parg;
2911         return 1;
2912
2913     case SSL_CTRL_GET_MAX_CERT_LIST:
2914         return (long)ctx->max_cert_list;
2915     case SSL_CTRL_SET_MAX_CERT_LIST:
2916         if (larg < 0)
2917             return 0;
2918         l = (long)ctx->max_cert_list;
2919         ctx->max_cert_list = (size_t)larg;
2920         return l;
2921
2922     case SSL_CTRL_SET_SESS_CACHE_SIZE:
2923         if (larg < 0)
2924             return 0;
2925         l = (long)ctx->session_cache_size;
2926         ctx->session_cache_size = (size_t)larg;
2927         return l;
2928     case SSL_CTRL_GET_SESS_CACHE_SIZE:
2929         return (long)ctx->session_cache_size;
2930     case SSL_CTRL_SET_SESS_CACHE_MODE:
2931         l = ctx->session_cache_mode;
2932         ctx->session_cache_mode = larg;
2933         return l;
2934     case SSL_CTRL_GET_SESS_CACHE_MODE:
2935         return ctx->session_cache_mode;
2936
2937     case SSL_CTRL_SESS_NUMBER:
2938         return lh_SSL_SESSION_num_items(ctx->sessions);
2939     case SSL_CTRL_SESS_CONNECT:
2940         return ssl_tsan_load(ctx, &ctx->stats.sess_connect);
2941     case SSL_CTRL_SESS_CONNECT_GOOD:
2942         return ssl_tsan_load(ctx, &ctx->stats.sess_connect_good);
2943     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
2944         return ssl_tsan_load(ctx, &ctx->stats.sess_connect_renegotiate);
2945     case SSL_CTRL_SESS_ACCEPT:
2946         return ssl_tsan_load(ctx, &ctx->stats.sess_accept);
2947     case SSL_CTRL_SESS_ACCEPT_GOOD:
2948         return ssl_tsan_load(ctx, &ctx->stats.sess_accept_good);
2949     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
2950         return ssl_tsan_load(ctx, &ctx->stats.sess_accept_renegotiate);
2951     case SSL_CTRL_SESS_HIT:
2952         return ssl_tsan_load(ctx, &ctx->stats.sess_hit);
2953     case SSL_CTRL_SESS_CB_HIT:
2954         return ssl_tsan_load(ctx, &ctx->stats.sess_cb_hit);
2955     case SSL_CTRL_SESS_MISSES:
2956         return ssl_tsan_load(ctx, &ctx->stats.sess_miss);
2957     case SSL_CTRL_SESS_TIMEOUTS:
2958         return ssl_tsan_load(ctx, &ctx->stats.sess_timeout);
2959     case SSL_CTRL_SESS_CACHE_FULL:
2960         return ssl_tsan_load(ctx, &ctx->stats.sess_cache_full);
2961     case SSL_CTRL_MODE:
2962         return (ctx->mode |= larg);
2963     case SSL_CTRL_CLEAR_MODE:
2964         return (ctx->mode &= ~larg);
2965     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2966         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2967             return 0;
2968         ctx->max_send_fragment = larg;
2969         if (ctx->max_send_fragment < ctx->split_send_fragment)
2970             ctx->split_send_fragment = ctx->max_send_fragment;
2971         return 1;
2972     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2973         if ((size_t)larg > ctx->max_send_fragment || larg == 0)
2974             return 0;
2975         ctx->split_send_fragment = larg;
2976         return 1;
2977     case SSL_CTRL_SET_MAX_PIPELINES:
2978         if (larg < 1 || larg > SSL_MAX_PIPELINES)
2979             return 0;
2980         ctx->max_pipelines = larg;
2981         return 1;
2982     case SSL_CTRL_CERT_FLAGS:
2983         return (ctx->cert->cert_flags |= larg);
2984     case SSL_CTRL_CLEAR_CERT_FLAGS:
2985         return (ctx->cert->cert_flags &= ~larg);
2986     case SSL_CTRL_SET_MIN_PROTO_VERSION:
2987         return ssl_check_allowed_versions(larg, ctx->max_proto_version)
2988                && ssl_set_version_bound(ctx->method->version, (int)larg,
2989                                         &ctx->min_proto_version);
2990     case SSL_CTRL_GET_MIN_PROTO_VERSION:
2991         return ctx->min_proto_version;
2992     case SSL_CTRL_SET_MAX_PROTO_VERSION:
2993         return ssl_check_allowed_versions(ctx->min_proto_version, larg)
2994                && ssl_set_version_bound(ctx->method->version, (int)larg,
2995                                         &ctx->max_proto_version);
2996     case SSL_CTRL_GET_MAX_PROTO_VERSION:
2997         return ctx->max_proto_version;
2998     default:
2999         return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
3000     }
3001 }
3002
3003 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
3004 {
3005     switch (cmd) {
3006     case SSL_CTRL_SET_MSG_CALLBACK:
3007         ctx->msg_callback = (void (*)
3008                              (int write_p, int version, int content_type,
3009                               const void *buf, size_t len, SSL *ssl,
3010                               void *arg))(fp);
3011         return 1;
3012
3013     default:
3014         return ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp);
3015     }
3016 }
3017
3018 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
3019 {
3020     if (a->id > b->id)
3021         return 1;
3022     if (a->id < b->id)
3023         return -1;
3024     return 0;
3025 }
3026
3027 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
3028                           const SSL_CIPHER *const *bp)
3029 {
3030     if ((*ap)->id > (*bp)->id)
3031         return 1;
3032     if ((*ap)->id < (*bp)->id)
3033         return -1;
3034     return 0;
3035 }
3036
3037 /*
3038  * return a STACK of the ciphers available for the SSL and in order of
3039  * preference
3040  */
3041 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
3042 {
3043     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3044
3045     if (sc != NULL) {
3046         if (sc->cipher_list != NULL) {
3047             return sc->cipher_list;
3048         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
3049             return s->ctx->cipher_list;
3050         }
3051     }
3052     return NULL;
3053 }
3054
3055 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
3056 {
3057     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3058
3059     if (sc == NULL || !sc->server)
3060         return NULL;
3061     return sc->peer_ciphers;
3062 }
3063
3064 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
3065 {
3066     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
3067     int i;
3068     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3069
3070     if (sc == NULL)
3071         return NULL;
3072
3073     ciphers = SSL_get_ciphers(s);
3074     if (!ciphers)
3075         return NULL;
3076     if (!ssl_set_client_disabled(sc))
3077         return NULL;
3078     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
3079         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
3080         if (!ssl_cipher_disabled(sc, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
3081             if (!sk)
3082                 sk = sk_SSL_CIPHER_new_null();
3083             if (!sk)
3084                 return NULL;
3085             if (!sk_SSL_CIPHER_push(sk, c)) {
3086                 sk_SSL_CIPHER_free(sk);
3087                 return NULL;
3088             }
3089         }
3090     }
3091     return sk;
3092 }
3093
3094 /** return a STACK of the ciphers available for the SSL and in order of
3095  * algorithm id */
3096 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL_CONNECTION *s)
3097 {
3098     if (s != NULL) {
3099         if (s->cipher_list_by_id != NULL)
3100             return s->cipher_list_by_id;
3101         else if (s->ssl.ctx != NULL
3102                  && s->ssl.ctx->cipher_list_by_id != NULL)
3103             return s->ssl.ctx->cipher_list_by_id;
3104     }
3105     return NULL;
3106 }
3107
3108 /** The old interface to get the same thing as SSL_get_ciphers() */
3109 const char *SSL_get_cipher_list(const SSL *s, int n)
3110 {
3111     const SSL_CIPHER *c;
3112     STACK_OF(SSL_CIPHER) *sk;
3113
3114     if (s == NULL)
3115         return NULL;
3116     sk = SSL_get_ciphers(s);
3117     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
3118         return NULL;
3119     c = sk_SSL_CIPHER_value(sk, n);
3120     if (c == NULL)
3121         return NULL;
3122     return c->name;
3123 }
3124
3125 /** return a STACK of the ciphers available for the SSL_CTX and in order of
3126  * preference */
3127 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
3128 {
3129     if (ctx != NULL)
3130         return ctx->cipher_list;
3131     return NULL;
3132 }
3133
3134 /*
3135  * Distinguish between ciphers controlled by set_ciphersuite() and
3136  * set_cipher_list() when counting.
3137  */
3138 static int cipher_list_tls12_num(STACK_OF(SSL_CIPHER) *sk)
3139 {
3140     int i, num = 0;
3141     const SSL_CIPHER *c;
3142
3143     if (sk == NULL)
3144         return 0;
3145     for (i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
3146         c = sk_SSL_CIPHER_value(sk, i);
3147         if (c->min_tls >= TLS1_3_VERSION)
3148             continue;
3149         num++;
3150     }
3151     return num;
3152 }
3153
3154 /** specify the ciphers to be used by default by the SSL_CTX */
3155 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
3156 {
3157     STACK_OF(SSL_CIPHER) *sk;
3158
3159     sk = ssl_create_cipher_list(ctx, ctx->tls13_ciphersuites,
3160                                 &ctx->cipher_list, &ctx->cipher_list_by_id, str,
3161                                 ctx->cert);
3162     /*
3163      * ssl_create_cipher_list may return an empty stack if it was unable to
3164      * find a cipher matching the given rule string (for example if the rule
3165      * string specifies a cipher which has been disabled). This is not an
3166      * error as far as ssl_create_cipher_list is concerned, and hence
3167      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
3168      */
3169     if (sk == NULL)
3170         return 0;
3171     else if (cipher_list_tls12_num(sk) == 0) {
3172         ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
3173         return 0;
3174     }
3175     return 1;
3176 }
3177
3178 /** specify the ciphers to be used by the SSL */
3179 int SSL_set_cipher_list(SSL *s, const char *str)
3180 {
3181     STACK_OF(SSL_CIPHER) *sk;
3182     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3183
3184     if (sc == NULL)
3185         return 0;
3186
3187     sk = ssl_create_cipher_list(s->ctx, sc->tls13_ciphersuites,
3188                                 &sc->cipher_list, &sc->cipher_list_by_id, str,
3189                                 sc->cert);
3190     /* see comment in SSL_CTX_set_cipher_list */
3191     if (sk == NULL)
3192         return 0;
3193     else if (cipher_list_tls12_num(sk) == 0) {
3194         ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHER_MATCH);
3195         return 0;
3196     }
3197     return 1;
3198 }
3199
3200 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size)
3201 {
3202     char *p;
3203     STACK_OF(SSL_CIPHER) *clntsk, *srvrsk;
3204     const SSL_CIPHER *c;
3205     int i;
3206     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3207
3208     if (sc == NULL)
3209         return NULL;
3210
3211     if (!sc->server
3212             || sc->peer_ciphers == NULL
3213             || size < 2)
3214         return NULL;
3215
3216     p = buf;
3217     clntsk = sc->peer_ciphers;
3218     srvrsk = SSL_get_ciphers(s);
3219     if (clntsk == NULL || srvrsk == NULL)
3220         return NULL;
3221
3222     if (sk_SSL_CIPHER_num(clntsk) == 0 || sk_SSL_CIPHER_num(srvrsk) == 0)
3223         return NULL;
3224
3225     for (i = 0; i < sk_SSL_CIPHER_num(clntsk); i++) {
3226         int n;
3227
3228         c = sk_SSL_CIPHER_value(clntsk, i);
3229         if (sk_SSL_CIPHER_find(srvrsk, c) < 0)
3230             continue;
3231
3232         n = strlen(c->name);
3233         if (n + 1 > size) {
3234             if (p != buf)
3235                 --p;
3236             *p = '\0';
3237             return buf;
3238         }
3239         strcpy(p, c->name);
3240         p += n;
3241         *(p++) = ':';
3242         size -= n + 1;
3243     }
3244     p[-1] = '\0';
3245     return buf;
3246 }
3247
3248 /**
3249  * Return the requested servername (SNI) value. Note that the behaviour varies
3250  * depending on:
3251  * - whether this is called by the client or the server,
3252  * - if we are before or during/after the handshake,
3253  * - if a resumption or normal handshake is being attempted/has occurred
3254  * - whether we have negotiated TLSv1.2 (or below) or TLSv1.3
3255  *
3256  * Note that only the host_name type is defined (RFC 3546).
3257  */
3258 const char *SSL_get_servername(const SSL *s, const int type)
3259 {
3260     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3261     int server;
3262
3263     if (sc == NULL)
3264         return NULL;
3265
3266     /*
3267      * If we don't know if we are the client or the server yet then we assume
3268      * client.
3269      */
3270     server = sc->handshake_func == NULL ? 0 : sc->server;
3271
3272     if (type != TLSEXT_NAMETYPE_host_name)
3273         return NULL;
3274
3275     if (server) {
3276         /**
3277          * Server side
3278          * In TLSv1.3 on the server SNI is not associated with the session
3279          * but in TLSv1.2 or below it is.
3280          *
3281          * Before the handshake:
3282          *  - return NULL
3283          *
3284          * During/after the handshake (TLSv1.2 or below resumption occurred):
3285          * - If a servername was accepted by the server in the original
3286          *   handshake then it will return that servername, or NULL otherwise.
3287          *
3288          * During/after the handshake (TLSv1.2 or below resumption did not occur):
3289          * - The function will return the servername requested by the client in
3290          *   this handshake or NULL if none was requested.
3291          */
3292          if (sc->hit && !SSL_CONNECTION_IS_TLS13(sc))
3293             return sc->session->ext.hostname;
3294     } else {
3295         /**
3296          * Client side
3297          *
3298          * Before the handshake:
3299          *  - If a servername has been set via a call to
3300          *    SSL_set_tlsext_host_name() then it will return that servername
3301          *  - If one has not been set, but a TLSv1.2 resumption is being
3302          *    attempted and the session from the original handshake had a
3303          *    servername accepted by the server then it will return that
3304          *    servername
3305          *  - Otherwise it returns NULL
3306          *
3307          * During/after the handshake (TLSv1.2 or below resumption occurred):
3308          * - If the session from the original handshake had a servername accepted
3309          *   by the server then it will return that servername.
3310          * - Otherwise it returns the servername set via
3311          *   SSL_set_tlsext_host_name() (or NULL if it was not called).
3312          *
3313          * During/after the handshake (TLSv1.2 or below resumption did not occur):
3314          * - It will return the servername set via SSL_set_tlsext_host_name()
3315          *   (or NULL if it was not called).
3316          */
3317         if (SSL_in_before(s)) {
3318             if (sc->ext.hostname == NULL
3319                     && sc->session != NULL
3320                     && sc->session->ssl_version != TLS1_3_VERSION)
3321                 return sc->session->ext.hostname;
3322         } else {
3323             if (!SSL_CONNECTION_IS_TLS13(sc) && sc->hit
3324                 && sc->session->ext.hostname != NULL)
3325                 return sc->session->ext.hostname;
3326         }
3327     }
3328
3329     return sc->ext.hostname;
3330 }
3331
3332 int SSL_get_servername_type(const SSL *s)
3333 {
3334     if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)
3335         return TLSEXT_NAMETYPE_host_name;
3336     return -1;
3337 }
3338
3339 /*
3340  * SSL_select_next_proto implements the standard protocol selection. It is
3341  * expected that this function is called from the callback set by
3342  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
3343  * vector of 8-bit, length prefixed byte strings. The length byte itself is
3344  * not included in the length. A byte string of length 0 is invalid. No byte
3345  * string may be truncated. The current, but experimental algorithm for
3346  * selecting the protocol is: 1) If the server doesn't support NPN then this
3347  * is indicated to the callback. In this case, the client application has to
3348  * abort the connection or have a default application level protocol. 2) If
3349  * the server supports NPN, but advertises an empty list then the client
3350  * selects the first protocol in its list, but indicates via the API that this
3351  * fallback case was enacted. 3) Otherwise, the client finds the first
3352  * protocol in the server's list that it supports and selects this protocol.
3353  * This is because it's assumed that the server has better information about
3354  * which protocol a client should use. 4) If the client doesn't support any
3355  * of the server's advertised protocols, then this is treated the same as
3356  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
3357  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
3358  */
3359 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
3360                           const unsigned char *server,
3361                           unsigned int server_len,
3362                           const unsigned char *client, unsigned int client_len)
3363 {
3364     unsigned int i, j;
3365     const unsigned char *result;
3366     int status = OPENSSL_NPN_UNSUPPORTED;
3367
3368     /*
3369      * For each protocol in server preference order, see if we support it.
3370      */
3371     for (i = 0; i < server_len;) {
3372         for (j = 0; j < client_len;) {
3373             if (server[i] == client[j] &&
3374                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
3375                 /* We found a match */
3376                 result = &server[i];
3377                 status = OPENSSL_NPN_NEGOTIATED;
3378                 goto found;
3379             }
3380             j += client[j];
3381             j++;
3382         }
3383         i += server[i];
3384         i++;
3385     }
3386
3387     /* There's no overlap between our protocols and the server's list. */
3388     result = client;
3389     status = OPENSSL_NPN_NO_OVERLAP;
3390
3391  found:
3392     *out = (unsigned char *)result + 1;
3393     *outlen = result[0];
3394     return status;
3395 }
3396
3397 #ifndef OPENSSL_NO_NEXTPROTONEG
3398 /*
3399  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
3400  * client's requested protocol for this connection and returns 0. If the
3401  * client didn't request any protocol, then *data is set to NULL. Note that
3402  * the client can request any protocol it chooses. The value returned from
3403  * this function need not be a member of the list of supported protocols
3404  * provided by the callback.
3405  */
3406 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
3407                                     unsigned *len)
3408 {
3409     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
3410
3411     if (sc == NULL) {
3412         /* We have no other way to indicate error */
3413         *data = NULL;
3414         *len = 0;
3415         return;
3416     }
3417
3418     *data = sc->ext.npn;
3419     if (*data == NULL) {
3420         *len = 0;
3421     } else {
3422         *len = (unsigned int)sc->ext.npn_len;
3423     }
3424 }
3425
3426 /*
3427  * SSL_CTX_set_npn_advertised_cb sets a callback that is called when
3428  * a TLS server needs a list of supported protocols for Next Protocol
3429  * Negotiation. The returned list must be in wire format.  The list is
3430  * returned by setting |out| to point to it and |outlen| to its length. This
3431  * memory will not be modified, but one should assume that the SSL* keeps a
3432  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
3433  * wishes to advertise. Otherwise, no such extension will be included in the
3434  * ServerHello.
3435  */
3436 void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
3437                                    SSL_CTX_npn_advertised_cb_func cb,
3438                                    void *arg)
3439 {
3440     ctx->ext.npn_advertised_cb = cb;
3441     ctx->ext.npn_advertised_cb_arg = arg;
3442 }
3443
3444 /*
3445  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
3446  * client needs to select a protocol from the server's provided list. |out|
3447  * must be set to point to the selected protocol (which may be within |in|).
3448  * The length of the protocol name must be written into |outlen|. The
3449  * server's advertised protocols are provided in |in| and |inlen|. The
3450  * callback can assume that |in| is syntactically valid. The client must
3451  * select a protocol. It is fatal to the connection if this callback returns
3452  * a value other than SSL_TLSEXT_ERR_OK.
3453  */
3454 void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
3455                                SSL_CTX_npn_select_cb_func cb,
3456                                void *arg)
3457 {
3458     ctx->ext.npn_select_cb = cb;
3459     ctx->ext.npn_select_cb_arg = arg;
3460 }
3461 #endif
3462
3463 static int alpn_value_ok(const unsigned char *protos, unsigned int protos_len)
3464 {
3465     unsigned int idx;
3466
3467     if (protos_len < 2 || protos == NULL)
3468         return 0;
3469
3470     for (idx = 0; idx < protos_len; idx += protos[idx] + 1) {
3471         if (protos[idx] == 0)
3472             return 0;
3473     }
3474     return idx == protos_len;
3475 }
3476 /*
3477  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
3478  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
3479  * length-prefixed strings). Returns 0 on success.
3480  */
3481 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
3482                             unsigned int protos_len)
3483 {
3484     unsigned char *alpn;
3485
3486     if (protos_len == 0 || protos == NULL) {
3487         OPENSSL_free(ctx->ext.alpn);
3488         ctx->ext.alpn = NULL;
3489         ctx->ext.alpn_len = 0;
3490         return 0;
3491     }
3492     /* Not valid per RFC */
3493     if (!alpn_value_ok(protos, protos_len))
3494         return 1;
3495
3496     alpn = OPENSSL_memdup(protos, protos_len);
3497     if (alpn == NULL)
3498         return 1;
3499     OPENSSL_free(ctx->ext.alpn);
3500     ctx->ext.alpn = alpn;
3501     ctx->ext.alpn_len = protos_len;
3502
3503     return 0;
3504 }
3505
3506 /*
3507  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
3508  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
3509  * length-prefixed strings). Returns 0 on success.
3510  */
3511 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
3512                         unsigned int protos_len)
3513 {
3514     unsigned char *alpn;
3515     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
3516
3517     if (sc == NULL)
3518         return 1;
3519
3520     if (protos_len == 0 || protos == NULL) {
3521         OPENSSL_free(sc->ext.alpn);
3522         sc->ext.alpn = NULL;
3523         sc->ext.alpn_len = 0;
3524         return 0;
3525     }
3526     /* Not valid per RFC */
3527     if (!alpn_value_ok(protos, protos_len))
3528         return 1;
3529
3530     alpn = OPENSSL_memdup(protos, protos_len);
3531     if (alpn == NULL)
3532         return 1;
3533     OPENSSL_free(sc->ext.alpn);
3534     sc->ext.alpn = alpn;
3535     sc->ext.alpn_len = protos_len;
3536
3537     return 0;
3538 }
3539
3540 /*
3541  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
3542  * called during ClientHello processing in order to select an ALPN protocol
3543  * from the client's list of offered protocols.
3544  */
3545 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
3546                                 SSL_CTX_alpn_select_cb_func cb,
3547                                 void *arg)
3548 {
3549     ctx->ext.alpn_select_cb = cb;
3550     ctx->ext.alpn_select_cb_arg = arg;
3551 }
3552
3553 /*
3554  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
3555  * On return it sets |*data| to point to |*len| bytes of protocol name
3556  * (not including the leading length-prefix byte). If the server didn't
3557  * respond with a negotiated protocol then |*len| will be zero.
3558  */
3559 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
3560                             unsigned int *len)
3561 {
3562     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
3563
3564     if (sc == NULL) {
3565         /* We have no other way to indicate error */
3566         *data = NULL;
3567         *len = 0;
3568         return;
3569     }
3570
3571     *data = sc->s3.alpn_selected;
3572     if (*data == NULL)
3573         *len = 0;
3574     else
3575         *len = (unsigned int)sc->s3.alpn_selected_len;
3576 }
3577
3578 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
3579                                const char *label, size_t llen,
3580                                const unsigned char *context, size_t contextlen,
3581                                int use_context)
3582 {
3583     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3584
3585     if (sc == NULL)
3586         return -1;
3587
3588     if (sc->session == NULL
3589         || (sc->version < TLS1_VERSION && sc->version != DTLS1_BAD_VER))
3590         return -1;
3591
3592     return s->method->ssl3_enc->export_keying_material(sc, out, olen, label,
3593                                                        llen, context,
3594                                                        contextlen, use_context);
3595 }
3596
3597 int SSL_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
3598                                      const char *label, size_t llen,
3599                                      const unsigned char *context,
3600                                      size_t contextlen)
3601 {
3602     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
3603
3604     if (sc == NULL)
3605         return -1;
3606
3607     if (sc->version != TLS1_3_VERSION)
3608         return 0;
3609
3610     return tls13_export_keying_material_early(sc, out, olen, label, llen,
3611                                               context, contextlen);
3612 }
3613
3614 static unsigned long ssl_session_hash(const SSL_SESSION *a)
3615 {
3616     const unsigned char *session_id = a->session_id;
3617     unsigned long l;
3618     unsigned char tmp_storage[4];
3619
3620     if (a->session_id_length < sizeof(tmp_storage)) {
3621         memset(tmp_storage, 0, sizeof(tmp_storage));
3622         memcpy(tmp_storage, a->session_id, a->session_id_length);
3623         session_id = tmp_storage;
3624     }
3625
3626     l = (unsigned long)
3627         ((unsigned long)session_id[0]) |
3628         ((unsigned long)session_id[1] << 8L) |
3629         ((unsigned long)session_id[2] << 16L) |
3630         ((unsigned long)session_id[3] << 24L);
3631     return l;
3632 }
3633
3634 /*
3635  * NB: If this function (or indeed the hash function which uses a sort of
3636  * coarser function than this one) is changed, ensure
3637  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
3638  * being able to construct an SSL_SESSION that will collide with any existing
3639  * session with a matching session ID.
3640  */
3641 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
3642 {
3643     if (a->ssl_version != b->ssl_version)
3644         return 1;
3645     if (a->session_id_length != b->session_id_length)
3646         return 1;
3647     return memcmp(a->session_id, b->session_id, a->session_id_length);
3648 }
3649
3650 /*
3651  * These wrapper functions should remain rather than redeclaring
3652  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
3653  * variable. The reason is that the functions aren't static, they're exposed
3654  * via ssl.h.
3655  */
3656
3657 SSL_CTX *SSL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
3658                         const SSL_METHOD *meth)
3659 {
3660     SSL_CTX *ret = NULL;
3661
3662     if (meth == NULL) {
3663         ERR_raise(ERR_LIB_SSL, SSL_R_NULL_SSL_METHOD_PASSED);
3664         return NULL;
3665     }
3666
3667     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
3668         return NULL;
3669
3670     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
3671         ERR_raise(ERR_LIB_SSL, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
3672         goto err;
3673     }
3674     ret = OPENSSL_zalloc(sizeof(*ret));
3675     if (ret == NULL)
3676         goto err;
3677
3678     /* Init the reference counting before any call to SSL_CTX_free */
3679     ret->references = 1;
3680     ret->lock = CRYPTO_THREAD_lock_new();
3681     if (ret->lock == NULL) {
3682         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3683         goto err;
3684     }
3685
3686 #ifdef TSAN_REQUIRES_LOCKING
3687     ret->tsan_lock = CRYPTO_THREAD_lock_new();
3688     if (ret->tsan_lock == NULL) {
3689         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3690         goto err;
3691     }
3692 #endif
3693
3694     ret->libctx = libctx;
3695     if (propq != NULL) {
3696         ret->propq = OPENSSL_strdup(propq);
3697         if (ret->propq == NULL)
3698             goto err;
3699     }
3700
3701     ret->method = meth;
3702     ret->min_proto_version = 0;
3703     ret->max_proto_version = 0;
3704     ret->mode = SSL_MODE_AUTO_RETRY;
3705     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
3706     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
3707     /* We take the system default. */
3708     ret->session_timeout = meth->get_timeout();
3709     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
3710     ret->verify_mode = SSL_VERIFY_NONE;
3711     if ((ret->cert = ssl_cert_new()) == NULL) {
3712         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3713         goto err;
3714     }
3715
3716     ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
3717     if (ret->sessions == NULL) {
3718         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3719         goto err;
3720     }
3721     ret->cert_store = X509_STORE_new();
3722     if (ret->cert_store == NULL) {
3723         ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
3724         goto err;
3725     }
3726 #ifndef OPENSSL_NO_CT
3727     ret->ctlog_store = CTLOG_STORE_new_ex(libctx, propq);
3728     if (ret->ctlog_store == NULL) {
3729         ERR_raise(ERR_LIB_SSL, ERR_R_CT_LIB);
3730         goto err;
3731     }
3732 #endif
3733
3734     /* initialize cipher/digest methods table */
3735     if (!ssl_load_ciphers(ret))
3736         goto err;
3737     /* initialise sig algs */
3738     if (!ssl_setup_sig_algs(ret))
3739         goto err;
3740
3741     if (!ssl_load_groups(ret))
3742         goto err;
3743
3744     if (!SSL_CTX_set_ciphersuites(ret, OSSL_default_ciphersuites())) {
3745         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3746         goto err;
3747     }
3748
3749     if (!ssl_create_cipher_list(ret,
3750                                 ret->tls13_ciphersuites,
3751                                 &ret->cipher_list, &ret->cipher_list_by_id,
3752                                 OSSL_default_cipher_list(), ret->cert)
3753         || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
3754         ERR_raise(ERR_LIB_SSL, SSL_R_LIBRARY_HAS_NO_CIPHERS);
3755         goto err;
3756     }
3757
3758     ret->param = X509_VERIFY_PARAM_new();
3759     if (ret->param == NULL) {
3760         ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
3761         goto err;
3762     }
3763
3764     /*
3765      * If these aren't available from the provider we'll get NULL returns.
3766      * That's fine but will cause errors later if SSLv3 is negotiated
3767      */
3768     ret->md5 = ssl_evp_md_fetch(libctx, NID_md5, propq);
3769     ret->sha1 = ssl_evp_md_fetch(libctx, NID_sha1, propq);
3770
3771     if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL) {
3772         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3773         goto err;
3774     }
3775
3776     if ((ret->client_ca_names = sk_X509_NAME_new_null()) == NULL) {
3777         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3778         goto err;
3779     }
3780
3781     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data)) {
3782         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
3783         goto err;
3784     }
3785
3786     if ((ret->ext.secure = OPENSSL_secure_zalloc(sizeof(*ret->ext.secure))) == NULL)
3787         goto err;
3788
3789     /* No compression for DTLS */
3790     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
3791         ret->comp_methods = SSL_COMP_get_compression_methods();
3792
3793     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
3794     ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
3795
3796     /* Setup RFC5077 ticket keys */
3797     if ((RAND_bytes_ex(libctx, ret->ext.tick_key_name,
3798                        sizeof(ret->ext.tick_key_name), 0) <= 0)
3799         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_hmac_key,
3800                                sizeof(ret->ext.secure->tick_hmac_key), 0) <= 0)
3801         || (RAND_priv_bytes_ex(libctx, ret->ext.secure->tick_aes_key,
3802                                sizeof(ret->ext.secure->tick_aes_key), 0) <= 0))
3803         ret->options |= SSL_OP_NO_TICKET;
3804
3805     if (RAND_priv_bytes_ex(libctx, ret->ext.cookie_hmac_key,
3806                            sizeof(ret->ext.cookie_hmac_key), 0) <= 0) {
3807         ERR_raise(ERR_LIB_SSL, ERR_R_RAND_LIB);
3808         goto err;
3809     }
3810
3811 #ifndef OPENSSL_NO_SRP
3812     if (!ssl_ctx_srp_ctx_init_intern(ret)) {
3813         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
3814         goto err;
3815     }
3816 #endif
3817 #ifndef OPENSSL_NO_ENGINE
3818 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
3819 #  define eng_strx(x)     #x
3820 #  define eng_str(x)      eng_strx(x)
3821     /* Use specific client engine automatically... ignore errors */
3822     {
3823         ENGINE *eng;
3824         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
3825         if (!eng) {
3826             ERR_clear_error();
3827             ENGINE_load_builtin_engines();
3828             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
3829         }
3830         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
3831             ERR_clear_error();
3832     }
3833 # endif
3834 #endif
3835     /*
3836      * Disable compression by default to prevent CRIME. Applications can
3837      * re-enable compression by configuring
3838      * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
3839      * or by using the SSL_CONF library. Similarly we also enable TLSv1.3
3840      * middlebox compatibility by default. This may be disabled by default in
3841      * a later OpenSSL version.
3842      */
3843     ret->options |= SSL_OP_NO_COMPRESSION | SSL_OP_ENABLE_MIDDLEBOX_COMPAT;
3844
3845     ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
3846
3847     /*
3848      * We cannot usefully set a default max_early_data here (which gets
3849      * propagated in SSL_new(), for the following reason: setting the
3850      * SSL field causes tls_construct_stoc_early_data() to tell the
3851      * client that early data will be accepted when constructing a TLS 1.3
3852      * session ticket, and the client will accordingly send us early data
3853      * when using that ticket (if the client has early data to send).
3854      * However, in order for the early data to actually be consumed by
3855      * the application, the application must also have calls to
3856      * SSL_read_early_data(); otherwise we'll just skip past the early data
3857      * and ignore it.  So, since the application must add calls to
3858      * SSL_read_early_data(), we also require them to add
3859      * calls to SSL_CTX_set_max_early_data() in order to use early data,
3860      * eliminating the bandwidth-wasting early data in the case described
3861      * above.
3862      */
3863     ret->max_early_data = 0;
3864
3865     /*
3866      * Default recv_max_early_data is a fully loaded single record. Could be
3867      * split across multiple records in practice. We set this differently to
3868      * max_early_data so that, in the default case, we do not advertise any
3869      * support for early_data, but if a client were to send us some (e.g.
3870      * because of an old, stale ticket) then we will tolerate it and skip over
3871      * it.
3872      */
3873     ret->recv_max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
3874
3875     /* By default we send two session tickets automatically in TLSv1.3 */
3876     ret->num_tickets = 2;
3877
3878     ssl_ctx_system_config(ret);
3879
3880     return ret;
3881  err:
3882     SSL_CTX_free(ret);
3883     return NULL;
3884 }
3885
3886 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
3887 {
3888     return SSL_CTX_new_ex(NULL, NULL, meth);
3889 }
3890
3891 int SSL_CTX_up_ref(SSL_CTX *ctx)
3892 {
3893     int i;
3894
3895     if (CRYPTO_UP_REF(&ctx->references, &i, ctx->lock) <= 0)
3896         return 0;
3897
3898     REF_PRINT_COUNT("SSL_CTX", ctx);
3899     REF_ASSERT_ISNT(i < 2);
3900     return ((i > 1) ? 1 : 0);
3901 }
3902
3903 void SSL_CTX_free(SSL_CTX *a)
3904 {
3905     int i;
3906     size_t j;
3907
3908     if (a == NULL)
3909         return;
3910
3911     CRYPTO_DOWN_REF(&a->references, &i, a->lock);
3912     REF_PRINT_COUNT("SSL_CTX", a);
3913     if (i > 0)
3914         return;
3915     REF_ASSERT_ISNT(i < 0);
3916
3917     X509_VERIFY_PARAM_free(a->param);
3918     dane_ctx_final(&a->dane);
3919
3920     /*
3921      * Free internal session cache. However: the remove_cb() may reference
3922      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
3923      * after the sessions were flushed.
3924      * As the ex_data handling routines might also touch the session cache,
3925      * the most secure solution seems to be: empty (flush) the cache, then
3926      * free ex_data, then finally free the cache.
3927      * (See ticket [openssl.org #212].)
3928      */
3929     if (a->sessions != NULL)
3930         SSL_CTX_flush_sessions(a, 0);
3931
3932     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
3933     lh_SSL_SESSION_free(a->sessions);
3934     X509_STORE_free(a->cert_store);
3935 #ifndef OPENSSL_NO_CT
3936     CTLOG_STORE_free(a->ctlog_store);
3937 #endif
3938     sk_SSL_CIPHER_free(a->cipher_list);
3939     sk_SSL_CIPHER_free(a->cipher_list_by_id);
3940     sk_SSL_CIPHER_free(a->tls13_ciphersuites);
3941     ssl_cert_free(a->cert);
3942     sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
3943     sk_X509_NAME_pop_free(a->client_ca_names, X509_NAME_free);
3944     OSSL_STACK_OF_X509_free(a->extra_certs);
3945     a->comp_methods = NULL;
3946 #ifndef OPENSSL_NO_SRTP
3947     sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
3948 #endif
3949 #ifndef OPENSSL_NO_SRP
3950     ssl_ctx_srp_ctx_free_intern(a);
3951 #endif
3952 #ifndef OPENSSL_NO_ENGINE
3953     tls_engine_finish(a->client_cert_engine);
3954 #endif
3955
3956     OPENSSL_free(a->ext.ecpointformats);
3957     OPENSSL_free(a->ext.supportedgroups);
3958     OPENSSL_free(a->ext.supported_groups_default);
3959     OPENSSL_free(a->ext.alpn);
3960     OPENSSL_secure_free(a->ext.secure);
3961
3962     ssl_evp_md_free(a->md5);
3963     ssl_evp_md_free(a->sha1);
3964
3965     for (j = 0; j < SSL_ENC_NUM_IDX; j++)
3966         ssl_evp_cipher_free(a->ssl_cipher_methods[j]);
3967     for (j = 0; j < SSL_MD_NUM_IDX; j++)
3968         ssl_evp_md_free(a->ssl_digest_methods[j]);
3969     for (j = 0; j < a->group_list_len; j++) {
3970         OPENSSL_free(a->group_list[j].tlsname);
3971         OPENSSL_free(a->group_list[j].realname);
3972         OPENSSL_free(a->group_list[j].algorithm);
3973     }
3974     OPENSSL_free(a->group_list);
3975
3976     OPENSSL_free(a->sigalg_lookup_cache);
3977
3978     CRYPTO_THREAD_lock_free(a->lock);
3979 #ifdef TSAN_REQUIRES_LOCKING
3980     CRYPTO_THREAD_lock_free(a->tsan_lock);
3981 #endif
3982
3983     OPENSSL_free(a->propq);
3984
3985     OPENSSL_free(a);
3986 }
3987
3988 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
3989 {
3990     ctx->default_passwd_callback = cb;
3991 }
3992
3993 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
3994 {
3995     ctx->default_passwd_callback_userdata = u;
3996 }
3997
3998 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
3999 {
4000     return ctx->default_passwd_callback;
4001 }
4002
4003 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
4004 {
4005     return ctx->default_passwd_callback_userdata;
4006 }
4007
4008 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
4009 {
4010     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4011
4012     if (sc == NULL)
4013         return;
4014
4015     sc->default_passwd_callback = cb;
4016 }
4017
4018 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
4019 {
4020     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4021
4022     if (sc == NULL)
4023         return;
4024
4025     sc->default_passwd_callback_userdata = u;
4026 }
4027
4028 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
4029 {
4030     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4031
4032     if (sc == NULL)
4033         return NULL;
4034
4035     return sc->default_passwd_callback;
4036 }
4037
4038 void *SSL_get_default_passwd_cb_userdata(SSL *s)
4039 {
4040     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4041
4042     if (sc == NULL)
4043         return NULL;
4044
4045     return sc->default_passwd_callback_userdata;
4046 }
4047
4048 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
4049                                       int (*cb) (X509_STORE_CTX *, void *),
4050                                       void *arg)
4051 {
4052     ctx->app_verify_callback = cb;
4053     ctx->app_verify_arg = arg;
4054 }
4055
4056 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
4057                         int (*cb) (int, X509_STORE_CTX *))
4058 {
4059     ctx->verify_mode = mode;
4060     ctx->default_verify_callback = cb;
4061 }
4062
4063 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
4064 {
4065     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
4066 }
4067
4068 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
4069 {
4070     ssl_cert_set_cert_cb(c->cert, cb, arg);
4071 }
4072
4073 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
4074 {
4075     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4076
4077     if (sc == NULL)
4078         return;
4079
4080     ssl_cert_set_cert_cb(sc->cert, cb, arg);
4081 }
4082
4083 void ssl_set_masks(SSL_CONNECTION *s)
4084 {
4085     CERT *c = s->cert;
4086     uint32_t *pvalid = s->s3.tmp.valid_flags;
4087     int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
4088     unsigned long mask_k, mask_a;
4089     int have_ecc_cert, ecdsa_ok;
4090
4091     if (c == NULL)
4092         return;
4093
4094     dh_tmp = (c->dh_tmp != NULL
4095               || c->dh_tmp_cb != NULL
4096               || c->dh_tmp_auto);
4097
4098     rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
4099     rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
4100     dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
4101     have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
4102     mask_k = 0;
4103     mask_a = 0;
4104
4105     OSSL_TRACE4(TLS_CIPHER, "dh_tmp=%d rsa_enc=%d rsa_sign=%d dsa_sign=%d\n",
4106                dh_tmp, rsa_enc, rsa_sign, dsa_sign);
4107
4108 #ifndef OPENSSL_NO_GOST
4109     if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
4110         mask_k |= SSL_kGOST | SSL_kGOST18;
4111         mask_a |= SSL_aGOST12;
4112     }
4113     if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
4114         mask_k |= SSL_kGOST | SSL_kGOST18;
4115         mask_a |= SSL_aGOST12;
4116     }
4117     if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
4118         mask_k |= SSL_kGOST;
4119         mask_a |= SSL_aGOST01;
4120     }
4121 #endif
4122
4123     if (rsa_enc)
4124         mask_k |= SSL_kRSA;
4125
4126     if (dh_tmp)
4127         mask_k |= SSL_kDHE;
4128
4129     /*
4130      * If we only have an RSA-PSS certificate allow RSA authentication
4131      * if TLS 1.2 and peer supports it.
4132      */
4133
4134     if (rsa_enc || rsa_sign || (ssl_has_cert(s, SSL_PKEY_RSA_PSS_SIGN)
4135                 && pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_EXPLICIT_SIGN
4136                 && TLS1_get_version(&s->ssl) == TLS1_2_VERSION))
4137         mask_a |= SSL_aRSA;
4138
4139     if (dsa_sign) {
4140         mask_a |= SSL_aDSS;
4141     }
4142
4143     mask_a |= SSL_aNULL;
4144
4145     /*
4146      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
4147      * depending on the key usage extension.
4148      */
4149     if (have_ecc_cert) {
4150         uint32_t ex_kusage;
4151         ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
4152         ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
4153         if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
4154             ecdsa_ok = 0;
4155         if (ecdsa_ok)
4156             mask_a |= SSL_aECDSA;
4157     }
4158     /* Allow Ed25519 for TLS 1.2 if peer supports it */
4159     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
4160             && pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
4161             && TLS1_get_version(&s->ssl) == TLS1_2_VERSION)
4162             mask_a |= SSL_aECDSA;
4163
4164     /* Allow Ed448 for TLS 1.2 if peer supports it */
4165     if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED448)
4166             && pvalid[SSL_PKEY_ED448] & CERT_PKEY_EXPLICIT_SIGN
4167             && TLS1_get_version(&s->ssl) == TLS1_2_VERSION)
4168             mask_a |= SSL_aECDSA;
4169
4170     mask_k |= SSL_kECDHE;
4171
4172 #ifndef OPENSSL_NO_PSK
4173     mask_k |= SSL_kPSK;
4174     mask_a |= SSL_aPSK;
4175     if (mask_k & SSL_kRSA)
4176         mask_k |= SSL_kRSAPSK;
4177     if (mask_k & SSL_kDHE)
4178         mask_k |= SSL_kDHEPSK;
4179     if (mask_k & SSL_kECDHE)
4180         mask_k |= SSL_kECDHEPSK;
4181 #endif
4182
4183     s->s3.tmp.mask_k = mask_k;
4184     s->s3.tmp.mask_a = mask_a;
4185 }
4186
4187 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL_CONNECTION *s)
4188 {
4189     if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
4190         /* key usage, if present, must allow signing */
4191         if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
4192             ERR_raise(ERR_LIB_SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
4193             return 0;
4194         }
4195     }
4196     return 1;                   /* all checks are ok */
4197 }
4198
4199 int ssl_get_server_cert_serverinfo(SSL_CONNECTION *s,
4200                                    const unsigned char **serverinfo,
4201                                    size_t *serverinfo_length)
4202 {
4203     CERT_PKEY *cpk = s->s3.tmp.cert;
4204     *serverinfo_length = 0;
4205
4206     if (cpk == NULL || cpk->serverinfo == NULL)
4207         return 0;
4208
4209     *serverinfo = cpk->serverinfo;
4210     *serverinfo_length = cpk->serverinfo_length;
4211     return 1;
4212 }
4213
4214 void ssl_update_cache(SSL_CONNECTION *s, int mode)
4215 {
4216     int i;
4217
4218     /*
4219      * If the session_id_length is 0, we are not supposed to cache it, and it
4220      * would be rather hard to do anyway :-)
4221      */
4222     if (s->session->session_id_length == 0)
4223         return;
4224
4225     /*
4226      * If sid_ctx_length is 0 there is no specific application context
4227      * associated with this session, so when we try to resume it and
4228      * SSL_VERIFY_PEER is requested to verify the client identity, we have no
4229      * indication that this is actually a session for the proper application
4230      * context, and the *handshake* will fail, not just the resumption attempt.
4231      * Do not cache (on the server) these sessions that are not resumable
4232      * (clients can set SSL_VERIFY_PEER without needing a sid_ctx set).
4233      */
4234     if (s->server && s->session->sid_ctx_length == 0
4235             && (s->verify_mode & SSL_VERIFY_PEER) != 0)
4236         return;
4237
4238     i = s->session_ctx->session_cache_mode;
4239     if ((i & mode) != 0
4240         && (!s->hit || SSL_CONNECTION_IS_TLS13(s))) {
4241         /*
4242          * Add the session to the internal cache. In server side TLSv1.3 we
4243          * normally don't do this because by default it's a full stateless ticket
4244          * with only a dummy session id so there is no reason to cache it,
4245          * unless:
4246          * - we are doing early_data, in which case we cache so that we can
4247          *   detect replays
4248          * - the application has set a remove_session_cb so needs to know about
4249          *   session timeout events
4250          * - SSL_OP_NO_TICKET is set in which case it is a stateful ticket
4251          */
4252         if ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0
4253                 && (!SSL_CONNECTION_IS_TLS13(s)
4254                     || !s->server
4255                     || (s->max_early_data > 0
4256                         && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0)
4257                     || s->session_ctx->remove_session_cb != NULL
4258                     || (s->options & SSL_OP_NO_TICKET) != 0))
4259             SSL_CTX_add_session(s->session_ctx, s->session);
4260
4261         /*
4262          * Add the session to the external cache. We do this even in server side
4263          * TLSv1.3 without early data because some applications just want to
4264          * know about the creation of a session and aren't doing a full cache.
4265          */
4266         if (s->session_ctx->new_session_cb != NULL) {
4267             SSL_SESSION_up_ref(s->session);
4268             if (!s->session_ctx->new_session_cb(SSL_CONNECTION_GET_SSL(s),
4269                                                 s->session))
4270                 SSL_SESSION_free(s->session);
4271         }
4272     }
4273
4274     /* auto flush every 255 connections */
4275     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
4276         TSAN_QUALIFIER int *stat;
4277
4278         if (mode & SSL_SESS_CACHE_CLIENT)
4279             stat = &s->session_ctx->stats.sess_connect_good;
4280         else
4281             stat = &s->session_ctx->stats.sess_accept_good;
4282         if ((ssl_tsan_load(s->session_ctx, stat) & 0xff) == 0xff)
4283             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
4284     }
4285 }
4286
4287 const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx)
4288 {
4289     return ctx->method;
4290 }
4291
4292 const SSL_METHOD *SSL_get_ssl_method(const SSL *s)
4293 {
4294     return s->method;
4295 }
4296
4297 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
4298 {
4299     int ret = 1;
4300     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4301
4302     /* TODO(QUIC): Do we want this for QUIC? */
4303     if (sc == NULL
4304         || (s->type != SSL_TYPE_SSL_CONNECTION && s->method != meth))
4305         return 0;
4306
4307     if (s->method != meth) {
4308         const SSL_METHOD *sm = s->method;
4309         int (*hf) (SSL *) = sc->handshake_func;
4310
4311         if (sm->version == meth->version)
4312             s->method = meth;
4313         else {
4314             sm->ssl_deinit(s);
4315             s->method = meth;
4316             ret = s->method->ssl_init(s);
4317         }
4318
4319         if (hf == sm->ssl_connect)
4320             sc->handshake_func = meth->ssl_connect;
4321         else if (hf == sm->ssl_accept)
4322             sc->handshake_func = meth->ssl_accept;
4323     }
4324     return ret;
4325 }
4326
4327 int SSL_get_error(const SSL *s, int i)
4328 {
4329     int reason;
4330     unsigned long l;
4331     BIO *bio;
4332     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4333
4334     if (i > 0)
4335         return SSL_ERROR_NONE;
4336
4337     /* TODO(QUIC): This will need more handling for QUIC_CONNECTIONs */
4338     if (sc == NULL)
4339         return SSL_ERROR_SSL;
4340
4341     /*
4342      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
4343      * where we do encode the error
4344      */
4345     if ((l = ERR_peek_error()) != 0) {
4346         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
4347             return SSL_ERROR_SYSCALL;
4348         else
4349             return SSL_ERROR_SSL;
4350     }
4351
4352     if (SSL_want_read(s)) {
4353         bio = SSL_get_rbio(s);
4354         if (BIO_should_read(bio))
4355             return SSL_ERROR_WANT_READ;
4356         else if (BIO_should_write(bio))
4357             /*
4358              * This one doesn't make too much sense ... We never try to write
4359              * to the rbio, and an application program where rbio and wbio
4360              * are separate couldn't even know what it should wait for.
4361              * However if we ever set s->rwstate incorrectly (so that we have
4362              * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
4363              * wbio *are* the same, this test works around that bug; so it
4364              * might be safer to keep it.
4365              */
4366             return SSL_ERROR_WANT_WRITE;
4367         else if (BIO_should_io_special(bio)) {
4368             reason = BIO_get_retry_reason(bio);
4369             if (reason == BIO_RR_CONNECT)
4370                 return SSL_ERROR_WANT_CONNECT;
4371             else if (reason == BIO_RR_ACCEPT)
4372                 return SSL_ERROR_WANT_ACCEPT;
4373             else
4374                 return SSL_ERROR_SYSCALL; /* unknown */
4375         }
4376     }
4377
4378     if (SSL_want_write(s)) {
4379         /* Access wbio directly - in order to use the buffered bio if present */
4380         bio = sc->wbio;
4381         if (BIO_should_write(bio))
4382             return SSL_ERROR_WANT_WRITE;
4383         else if (BIO_should_read(bio))
4384             /*
4385              * See above (SSL_want_read(s) with BIO_should_write(bio))
4386              */
4387             return SSL_ERROR_WANT_READ;
4388         else if (BIO_should_io_special(bio)) {
4389             reason = BIO_get_retry_reason(bio);
4390             if (reason == BIO_RR_CONNECT)
4391                 return SSL_ERROR_WANT_CONNECT;
4392             else if (reason == BIO_RR_ACCEPT)
4393                 return SSL_ERROR_WANT_ACCEPT;
4394             else
4395                 return SSL_ERROR_SYSCALL;
4396         }
4397     }
4398     if (SSL_want_x509_lookup(s))
4399         return SSL_ERROR_WANT_X509_LOOKUP;
4400     if (SSL_want_retry_verify(s))
4401         return SSL_ERROR_WANT_RETRY_VERIFY;
4402     if (SSL_want_async(s))
4403         return SSL_ERROR_WANT_ASYNC;
4404     if (SSL_want_async_job(s))
4405         return SSL_ERROR_WANT_ASYNC_JOB;
4406     if (SSL_want_client_hello_cb(s))
4407         return SSL_ERROR_WANT_CLIENT_HELLO_CB;
4408
4409     if ((sc->shutdown & SSL_RECEIVED_SHUTDOWN) &&
4410         (sc->s3.warn_alert == SSL_AD_CLOSE_NOTIFY))
4411         return SSL_ERROR_ZERO_RETURN;
4412
4413     return SSL_ERROR_SYSCALL;
4414 }
4415
4416 static int ssl_do_handshake_intern(void *vargs)
4417 {
4418     struct ssl_async_args *args = (struct ssl_async_args *)vargs;
4419     SSL *s = args->s;
4420     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4421
4422     if (sc == NULL)
4423         return -1;
4424
4425     return sc->handshake_func(s);
4426 }
4427
4428 int SSL_do_handshake(SSL *s)
4429 {
4430     int ret = 1;
4431     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4432
4433     /* TODO(QUIC): Special handling for QUIC will be needed */
4434     if (sc == NULL)
4435         return -1;
4436
4437     if (sc->handshake_func == NULL) {
4438         ERR_raise(ERR_LIB_SSL, SSL_R_CONNECTION_TYPE_NOT_SET);
4439         return -1;
4440     }
4441
4442     ossl_statem_check_finish_init(sc, -1);
4443
4444     s->method->ssl_renegotiate_check(s, 0);
4445
4446     if (SSL_in_init(s) || SSL_in_before(s)) {
4447         if ((sc->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
4448             struct ssl_async_args args;
4449
4450             memset(&args, 0, sizeof(args));
4451             args.s = s;
4452
4453             ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
4454         } else {
4455             ret = sc->handshake_func(s);
4456         }
4457     }
4458     return ret;
4459 }
4460
4461 void SSL_set_accept_state(SSL *s)
4462 {
4463     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4464
4465     /* TODO(QUIC): Special handling for QUIC will be needed */
4466     if (sc == NULL)
4467         return;
4468
4469     sc->server = 1;
4470     sc->shutdown = 0;
4471     ossl_statem_clear(sc);
4472     sc->handshake_func = s->method->ssl_accept;
4473     clear_ciphers(sc);
4474 }
4475
4476 void SSL_set_connect_state(SSL *s)
4477 {
4478     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4479
4480     /* TODO(QUIC): Special handling for QUIC will be needed */
4481     if (sc == NULL)
4482         return;
4483
4484     sc->server = 0;
4485     sc->shutdown = 0;
4486     ossl_statem_clear(sc);
4487     sc->handshake_func = s->method->ssl_connect;
4488     clear_ciphers(sc);
4489 }
4490
4491 int ssl_undefined_function(SSL *s)
4492 {
4493     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4494     return 0;
4495 }
4496
4497 int ssl_undefined_void_function(void)
4498 {
4499     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4500     return 0;
4501 }
4502
4503 int ssl_undefined_const_function(const SSL *s)
4504 {
4505     return 0;
4506 }
4507
4508 const SSL_METHOD *ssl_bad_method(int ver)
4509 {
4510     ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4511     return NULL;
4512 }
4513
4514 const char *ssl_protocol_to_string(int version)
4515 {
4516     switch (version)
4517     {
4518     case TLS1_3_VERSION:
4519         return "TLSv1.3";
4520
4521     case TLS1_2_VERSION:
4522         return "TLSv1.2";
4523
4524     case TLS1_1_VERSION:
4525         return "TLSv1.1";
4526
4527     case TLS1_VERSION:
4528         return "TLSv1";
4529
4530     case SSL3_VERSION:
4531         return "SSLv3";
4532
4533     case DTLS1_BAD_VER:
4534         return "DTLSv0.9";
4535
4536     case DTLS1_VERSION:
4537         return "DTLSv1";
4538
4539     case DTLS1_2_VERSION:
4540         return "DTLSv1.2";
4541
4542     default:
4543         return "unknown";
4544     }
4545 }
4546
4547 const char *SSL_get_version(const SSL *s)
4548 {
4549     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4550
4551     /* TODO(QUIC): Should QUIC return QUIC or TLSv1.3? */
4552     if (sc == NULL)
4553         return NULL;
4554
4555     return ssl_protocol_to_string(sc->version);
4556 }
4557
4558 static int dup_ca_names(STACK_OF(X509_NAME) **dst, STACK_OF(X509_NAME) *src)
4559 {
4560     STACK_OF(X509_NAME) *sk;
4561     X509_NAME *xn;
4562     int i;
4563
4564     if (src == NULL) {
4565         *dst = NULL;
4566         return 1;
4567     }
4568
4569     if ((sk = sk_X509_NAME_new_null()) == NULL)
4570         return 0;
4571     for (i = 0; i < sk_X509_NAME_num(src); i++) {
4572         xn = X509_NAME_dup(sk_X509_NAME_value(src, i));
4573         if (xn == NULL) {
4574             sk_X509_NAME_pop_free(sk, X509_NAME_free);
4575             return 0;
4576         }
4577         if (sk_X509_NAME_insert(sk, xn, i) == 0) {
4578             X509_NAME_free(xn);
4579             sk_X509_NAME_pop_free(sk, X509_NAME_free);
4580             return 0;
4581         }
4582     }
4583     *dst = sk;
4584
4585     return 1;
4586 }
4587
4588 SSL *SSL_dup(SSL *s)
4589 {
4590     SSL *ret;
4591     int i;
4592     /* TODO(QUIC): Add a SSL_METHOD function for duplication */
4593     SSL_CONNECTION *retsc;
4594     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4595
4596     if (sc == NULL)
4597         return NULL;
4598
4599     /* If we're not quiescent, just up_ref! */
4600     if (!SSL_in_init(s) || !SSL_in_before(s)) {
4601         CRYPTO_UP_REF(&s->references, &i, s->lock);
4602         return s;
4603     }
4604
4605     /*
4606      * Otherwise, copy configuration state, and session if set.
4607      */
4608     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
4609         return NULL;
4610     if ((retsc = SSL_CONNECTION_FROM_SSL_ONLY(ret)) == NULL)
4611         goto err;
4612
4613     if (sc->session != NULL) {
4614         /*
4615          * Arranges to share the same session via up_ref.  This "copies"
4616          * session-id, SSL_METHOD, sid_ctx, and 'cert'
4617          */
4618         if (!SSL_copy_session_id(ret, s))
4619             goto err;
4620     } else {
4621         /*
4622          * No session has been established yet, so we have to expect that
4623          * s->cert or ret->cert will be changed later -- they should not both
4624          * point to the same object, and thus we can't use
4625          * SSL_copy_session_id.
4626          */
4627         if (!SSL_set_ssl_method(ret, s->method))
4628             goto err;
4629
4630         if (sc->cert != NULL) {
4631             ssl_cert_free(retsc->cert);
4632             retsc->cert = ssl_cert_dup(sc->cert);
4633             if (retsc->cert == NULL)
4634                 goto err;
4635         }
4636
4637         if (!SSL_set_session_id_context(ret, sc->sid_ctx,
4638                                         (int)sc->sid_ctx_length))
4639             goto err;
4640     }
4641
4642     if (!ssl_dane_dup(retsc, sc))
4643         goto err;
4644     retsc->version = sc->version;
4645     retsc->options = sc->options;
4646     retsc->min_proto_version = sc->min_proto_version;
4647     retsc->max_proto_version = sc->max_proto_version;
4648     retsc->mode = sc->mode;
4649     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
4650     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
4651     retsc->msg_callback = sc->msg_callback;
4652     retsc->msg_callback_arg = sc->msg_callback_arg;
4653     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
4654     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
4655     retsc->generate_session_id = sc->generate_session_id;
4656
4657     SSL_set_info_callback(ret, SSL_get_info_callback(s));
4658
4659     /* copy app data, a little dangerous perhaps */
4660     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
4661         goto err;
4662
4663     retsc->server = sc->server;
4664     if (sc->handshake_func) {
4665         if (sc->server)
4666             SSL_set_accept_state(ret);
4667         else
4668             SSL_set_connect_state(ret);
4669     }
4670     retsc->shutdown = sc->shutdown;
4671     retsc->hit = sc->hit;
4672
4673     retsc->default_passwd_callback = sc->default_passwd_callback;
4674     retsc->default_passwd_callback_userdata = sc->default_passwd_callback_userdata;
4675
4676     X509_VERIFY_PARAM_inherit(retsc->param, sc->param);
4677
4678     /* dup the cipher_list and cipher_list_by_id stacks */
4679     if (sc->cipher_list != NULL) {
4680         if ((retsc->cipher_list = sk_SSL_CIPHER_dup(sc->cipher_list)) == NULL)
4681             goto err;
4682     }
4683     if (sc->cipher_list_by_id != NULL)
4684         if ((retsc->cipher_list_by_id = sk_SSL_CIPHER_dup(sc->cipher_list_by_id))
4685             == NULL)
4686             goto err;
4687
4688     /* Dup the client_CA list */
4689     if (!dup_ca_names(&retsc->ca_names, sc->ca_names)
4690             || !dup_ca_names(&retsc->client_ca_names, sc->client_ca_names))
4691         goto err;
4692
4693     return ret;
4694
4695  err:
4696     SSL_free(ret);
4697     return NULL;
4698 }
4699
4700 void ssl_clear_cipher_ctx(SSL_CONNECTION *s)
4701 {
4702     if (s->enc_read_ctx != NULL) {
4703         EVP_CIPHER_CTX_free(s->enc_read_ctx);
4704         s->enc_read_ctx = NULL;
4705     }
4706     if (s->enc_write_ctx != NULL) {
4707         EVP_CIPHER_CTX_free(s->enc_write_ctx);
4708         s->enc_write_ctx = NULL;
4709     }
4710 #ifndef OPENSSL_NO_COMP
4711     COMP_CTX_free(s->expand);
4712     s->expand = NULL;
4713     COMP_CTX_free(s->compress);
4714     s->compress = NULL;
4715 #endif
4716 }
4717
4718 X509 *SSL_get_certificate(const SSL *s)
4719 {
4720     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
4721
4722     if (sc == NULL)
4723         return NULL;
4724
4725     if (sc->cert != NULL)
4726         return sc->cert->key->x509;
4727     else
4728         return NULL;
4729 }
4730
4731 EVP_PKEY *SSL_get_privatekey(const SSL *s)
4732 {
4733     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4734
4735     if (sc == NULL)
4736         return NULL;
4737
4738     if (sc->cert != NULL)
4739         return sc->cert->key->privatekey;
4740     else
4741         return NULL;
4742 }
4743
4744 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
4745 {
4746     if (ctx->cert != NULL)
4747         return ctx->cert->key->x509;
4748     else
4749         return NULL;
4750 }
4751
4752 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
4753 {
4754     if (ctx->cert != NULL)
4755         return ctx->cert->key->privatekey;
4756     else
4757         return NULL;
4758 }
4759
4760 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
4761 {
4762     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4763
4764     if (sc == NULL)
4765         return NULL;
4766
4767     if ((sc->session != NULL) && (sc->session->cipher != NULL))
4768         return sc->session->cipher;
4769     return NULL;
4770 }
4771
4772 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s)
4773 {
4774     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4775
4776     if (sc == NULL)
4777         return NULL;
4778
4779     return sc->s3.tmp.new_cipher;
4780 }
4781
4782 const COMP_METHOD *SSL_get_current_compression(const SSL *s)
4783 {
4784 #ifndef OPENSSL_NO_COMP
4785     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
4786
4787     if (sc == NULL)
4788         return NULL;
4789
4790     /* TODO(RECLAYER): Remove me once SSLv3/DTLS moved to write record layer */
4791     if (SSL_CONNECTION_IS_DTLS(sc) || sc->version == SSL3_VERSION)
4792         return sc->compress ? COMP_CTX_get_method(sc->compress) : NULL;
4793
4794     return sc->rlayer.wrlmethod->get_compression(sc->rlayer.wrl);
4795 #else
4796     return NULL;
4797 #endif
4798 }
4799
4800 const COMP_METHOD *SSL_get_current_expansion(const SSL *s)
4801 {
4802 #ifndef OPENSSL_NO_COMP
4803     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
4804
4805     if (sc == NULL)
4806         return NULL;
4807
4808     return sc->rlayer.rrlmethod->get_compression(sc->rlayer.rrl);
4809 #else
4810     return NULL;
4811 #endif
4812 }
4813
4814 int ssl_init_wbio_buffer(SSL_CONNECTION *s)
4815 {
4816     BIO *bbio;
4817
4818     if (s->bbio != NULL) {
4819         /* Already buffered. */
4820         return 1;
4821     }
4822
4823     bbio = BIO_new(BIO_f_buffer());
4824     if (bbio == NULL || !BIO_set_read_buffer_size(bbio, 1)) {
4825         BIO_free(bbio);
4826         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
4827         return 0;
4828     }
4829     s->bbio = bbio;
4830     s->wbio = BIO_push(bbio, s->wbio);
4831
4832     s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
4833
4834     return 1;
4835 }
4836
4837 int ssl_free_wbio_buffer(SSL_CONNECTION *s)
4838 {
4839     /* callers ensure s is never null */
4840     if (s->bbio == NULL)
4841         return 1;
4842
4843     s->wbio = BIO_pop(s->wbio);
4844     s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
4845
4846     BIO_free(s->bbio);
4847     s->bbio = NULL;
4848
4849     return 1;
4850 }
4851
4852 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
4853 {
4854     ctx->quiet_shutdown = mode;
4855 }
4856
4857 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
4858 {
4859     return ctx->quiet_shutdown;
4860 }
4861
4862 void SSL_set_quiet_shutdown(SSL *s, int mode)
4863 {
4864     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4865
4866     /* TODO(QUIC): Do we want this for QUIC? */
4867     if (sc == NULL)
4868         return;
4869
4870     sc->quiet_shutdown = mode;
4871 }
4872
4873 int SSL_get_quiet_shutdown(const SSL *s)
4874 {
4875     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
4876
4877     /* TODO(QUIC): Do we want this for QUIC? */
4878     if (sc == NULL)
4879         return 0;
4880
4881     return sc->quiet_shutdown;
4882 }
4883
4884 void SSL_set_shutdown(SSL *s, int mode)
4885 {
4886     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
4887
4888     /* TODO(QUIC): Do we want this for QUIC? */
4889     if (sc == NULL)
4890         return;
4891
4892     sc->shutdown = mode;
4893 }
4894
4895 int SSL_get_shutdown(const SSL *s)
4896 {
4897     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
4898
4899     /* TODO(QUIC): Do we want this for QUIC? */
4900     if (sc == NULL)
4901         return 0;
4902
4903     return sc->shutdown;
4904 }
4905
4906 int SSL_version(const SSL *s)
4907 {
4908     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4909
4910     /* TODO(QUIC): Do we want to report QUIC version this way instead? */
4911     if (sc == NULL)
4912         return 0;
4913
4914     return sc->version;
4915 }
4916
4917 int SSL_client_version(const SSL *s)
4918 {
4919     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
4920
4921     /* TODO(QUIC): Do we want to report QUIC version this way instead? */
4922     if (sc == NULL)
4923         return 0;
4924
4925     return sc->client_version;
4926 }
4927
4928 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
4929 {
4930     return ssl->ctx;
4931 }
4932
4933 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
4934 {
4935     CERT *new_cert;
4936     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
4937
4938     /* TODO(QUIC): Do we need this for QUIC support? */
4939     if (sc == NULL)
4940         return NULL;
4941
4942     if (ssl->ctx == ctx)
4943         return ssl->ctx;
4944     if (ctx == NULL)
4945         ctx = sc->session_ctx;
4946     new_cert = ssl_cert_dup(ctx->cert);
4947     if (new_cert == NULL) {
4948         return NULL;
4949     }
4950
4951     if (!custom_exts_copy_flags(&new_cert->custext, &sc->cert->custext)) {
4952         ssl_cert_free(new_cert);
4953         return NULL;
4954     }
4955
4956     ssl_cert_free(sc->cert);
4957     sc->cert = new_cert;
4958
4959     /*
4960      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
4961      * so setter APIs must prevent invalid lengths from entering the system.
4962      */
4963     if (!ossl_assert(sc->sid_ctx_length <= sizeof(sc->sid_ctx)))
4964         return NULL;
4965
4966     /*
4967      * If the session ID context matches that of the parent SSL_CTX,
4968      * inherit it from the new SSL_CTX as well. If however the context does
4969      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
4970      * leave it unchanged.
4971      */
4972     if ((ssl->ctx != NULL) &&
4973         (sc->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
4974         (memcmp(sc->sid_ctx, ssl->ctx->sid_ctx, sc->sid_ctx_length) == 0)) {
4975         sc->sid_ctx_length = ctx->sid_ctx_length;
4976         memcpy(&sc->sid_ctx, &ctx->sid_ctx, sizeof(sc->sid_ctx));
4977     }
4978
4979     SSL_CTX_up_ref(ctx);
4980     SSL_CTX_free(ssl->ctx);     /* decrement reference count */
4981     ssl->ctx = ctx;
4982
4983     return ssl->ctx;
4984 }
4985
4986 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
4987 {
4988     return X509_STORE_set_default_paths_ex(ctx->cert_store, ctx->libctx,
4989                                            ctx->propq);
4990 }
4991
4992 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
4993 {
4994     X509_LOOKUP *lookup;
4995
4996     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
4997     if (lookup == NULL)
4998         return 0;
4999
5000     /* We ignore errors, in case the directory doesn't exist */
5001     ERR_set_mark();
5002
5003     X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
5004
5005     ERR_pop_to_mark();
5006
5007     return 1;
5008 }
5009
5010 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
5011 {
5012     X509_LOOKUP *lookup;
5013
5014     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
5015     if (lookup == NULL)
5016         return 0;
5017
5018     /* We ignore errors, in case the file doesn't exist */
5019     ERR_set_mark();
5020
5021     X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, ctx->libctx,
5022                              ctx->propq);
5023
5024     ERR_pop_to_mark();
5025
5026     return 1;
5027 }
5028
5029 int SSL_CTX_set_default_verify_store(SSL_CTX *ctx)
5030 {
5031     X509_LOOKUP *lookup;
5032
5033     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_store());
5034     if (lookup == NULL)
5035         return 0;
5036
5037     /* We ignore errors, in case the directory doesn't exist */
5038     ERR_set_mark();
5039
5040     X509_LOOKUP_add_store_ex(lookup, NULL, ctx->libctx, ctx->propq);
5041
5042     ERR_pop_to_mark();
5043
5044     return 1;
5045 }
5046
5047 int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile)
5048 {
5049     return X509_STORE_load_file_ex(ctx->cert_store, CAfile, ctx->libctx,
5050                                    ctx->propq);
5051 }
5052
5053 int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath)
5054 {
5055     return X509_STORE_load_path(ctx->cert_store, CApath);
5056 }
5057
5058 int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore)
5059 {
5060     return X509_STORE_load_store_ex(ctx->cert_store, CAstore, ctx->libctx,
5061                                     ctx->propq);
5062 }
5063
5064 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
5065                                   const char *CApath)
5066 {
5067     if (CAfile == NULL && CApath == NULL)
5068         return 0;
5069     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
5070         return 0;
5071     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
5072         return 0;
5073     return 1;
5074 }
5075
5076 void SSL_set_info_callback(SSL *ssl,
5077                            void (*cb) (const SSL *ssl, int type, int val))
5078 {
5079     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5080
5081     if (sc == NULL)
5082         return;
5083
5084     sc->info_callback = cb;
5085 }
5086
5087 /*
5088  * One compiler (Diab DCC) doesn't like argument names in returned function
5089  * pointer.
5090  */
5091 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
5092                                                int /* type */ ,
5093                                                int /* val */ ) {
5094     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5095
5096     if (sc == NULL)
5097         return NULL;
5098
5099     return sc->info_callback;
5100 }
5101
5102 void SSL_set_verify_result(SSL *ssl, long arg)
5103 {
5104     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5105
5106     if (sc == NULL)
5107         return;
5108
5109     sc->verify_result = arg;
5110 }
5111
5112 long SSL_get_verify_result(const SSL *ssl)
5113 {
5114     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5115
5116     if (sc == NULL)
5117         return 0;
5118
5119     return sc->verify_result;
5120 }
5121
5122 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
5123 {
5124     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5125
5126     if (sc == NULL)
5127         return 0;
5128
5129     if (outlen == 0)
5130         return sizeof(sc->s3.client_random);
5131     if (outlen > sizeof(sc->s3.client_random))
5132         outlen = sizeof(sc->s3.client_random);
5133     memcpy(out, sc->s3.client_random, outlen);
5134     return outlen;
5135 }
5136
5137 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
5138 {
5139     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5140
5141     if (sc == NULL)
5142         return 0;
5143
5144     if (outlen == 0)
5145         return sizeof(sc->s3.server_random);
5146     if (outlen > sizeof(sc->s3.server_random))
5147         outlen = sizeof(sc->s3.server_random);
5148     memcpy(out, sc->s3.server_random, outlen);
5149     return outlen;
5150 }
5151
5152 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
5153                                   unsigned char *out, size_t outlen)
5154 {
5155     if (outlen == 0)
5156         return session->master_key_length;
5157     if (outlen > session->master_key_length)
5158         outlen = session->master_key_length;
5159     memcpy(out, session->master_key, outlen);
5160     return outlen;
5161 }
5162
5163 int SSL_SESSION_set1_master_key(SSL_SESSION *sess, const unsigned char *in,
5164                                 size_t len)
5165 {
5166     if (len > sizeof(sess->master_key))
5167         return 0;
5168
5169     memcpy(sess->master_key, in, len);
5170     sess->master_key_length = len;
5171     return 1;
5172 }
5173
5174
5175 int SSL_set_ex_data(SSL *s, int idx, void *arg)
5176 {
5177     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
5178 }
5179
5180 void *SSL_get_ex_data(const SSL *s, int idx)
5181 {
5182     return CRYPTO_get_ex_data(&s->ex_data, idx);
5183 }
5184
5185 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
5186 {
5187     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
5188 }
5189
5190 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
5191 {
5192     return CRYPTO_get_ex_data(&s->ex_data, idx);
5193 }
5194
5195 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
5196 {
5197     return ctx->cert_store;
5198 }
5199
5200 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
5201 {
5202     X509_STORE_free(ctx->cert_store);
5203     ctx->cert_store = store;
5204 }
5205
5206 void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
5207 {
5208     if (store != NULL)
5209         X509_STORE_up_ref(store);
5210     SSL_CTX_set_cert_store(ctx, store);
5211 }
5212
5213 int SSL_want(const SSL *s)
5214 {
5215     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5216
5217     if (sc == NULL)
5218         return SSL_NOTHING;
5219
5220     return sc->rwstate;
5221 }
5222
5223 #ifndef OPENSSL_NO_PSK
5224 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
5225 {
5226     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
5227         ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
5228         return 0;
5229     }
5230     OPENSSL_free(ctx->cert->psk_identity_hint);
5231     if (identity_hint != NULL) {
5232         ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
5233         if (ctx->cert->psk_identity_hint == NULL)
5234             return 0;
5235     } else
5236         ctx->cert->psk_identity_hint = NULL;
5237     return 1;
5238 }
5239
5240 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
5241 {
5242     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5243
5244     if (sc == NULL)
5245         return 0;
5246
5247     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
5248         ERR_raise(ERR_LIB_SSL, SSL_R_DATA_LENGTH_TOO_LONG);
5249         return 0;
5250     }
5251     OPENSSL_free(sc->cert->psk_identity_hint);
5252     if (identity_hint != NULL) {
5253         sc->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
5254         if (sc->cert->psk_identity_hint == NULL)
5255             return 0;
5256     } else
5257         sc->cert->psk_identity_hint = NULL;
5258     return 1;
5259 }
5260
5261 const char *SSL_get_psk_identity_hint(const SSL *s)
5262 {
5263     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5264
5265     if (sc == NULL || sc->session == NULL)
5266         return NULL;
5267
5268     return sc->session->psk_identity_hint;
5269 }
5270
5271 const char *SSL_get_psk_identity(const SSL *s)
5272 {
5273     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5274
5275     if (sc == NULL || sc->session == NULL)
5276         return NULL;
5277
5278     return sc->session->psk_identity;
5279 }
5280
5281 void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
5282 {
5283     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5284
5285     if (sc == NULL)
5286         return;
5287
5288     sc->psk_client_callback = cb;
5289 }
5290
5291 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
5292 {
5293     ctx->psk_client_callback = cb;
5294 }
5295
5296 void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
5297 {
5298     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5299
5300     if (sc == NULL)
5301         return;
5302
5303     sc->psk_server_callback = cb;
5304 }
5305
5306 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
5307 {
5308     ctx->psk_server_callback = cb;
5309 }
5310 #endif
5311
5312 void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb)
5313 {
5314     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5315
5316     if (sc == NULL)
5317         return;
5318
5319     sc->psk_find_session_cb = cb;
5320 }
5321
5322 void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
5323                                            SSL_psk_find_session_cb_func cb)
5324 {
5325     ctx->psk_find_session_cb = cb;
5326 }
5327
5328 void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
5329 {
5330     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5331
5332     if (sc == NULL)
5333         return;
5334
5335     sc->psk_use_session_cb = cb;
5336 }
5337
5338 void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
5339                                            SSL_psk_use_session_cb_func cb)
5340 {
5341     ctx->psk_use_session_cb = cb;
5342 }
5343
5344 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
5345                               void (*cb) (int write_p, int version,
5346                                           int content_type, const void *buf,
5347                                           size_t len, SSL *ssl, void *arg))
5348 {
5349     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
5350 }
5351
5352 void SSL_set_msg_callback(SSL *ssl,
5353                           void (*cb) (int write_p, int version,
5354                                       int content_type, const void *buf,
5355                                       size_t len, SSL *ssl, void *arg))
5356 {
5357     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
5358 }
5359
5360 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
5361                                                 int (*cb) (SSL *ssl,
5362                                                            int
5363                                                            is_forward_secure))
5364 {
5365     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
5366                           (void (*)(void))cb);
5367 }
5368
5369 void SSL_set_not_resumable_session_callback(SSL *ssl,
5370                                             int (*cb) (SSL *ssl,
5371                                                        int is_forward_secure))
5372 {
5373     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
5374                       (void (*)(void))cb);
5375 }
5376
5377 void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
5378                                          size_t (*cb) (SSL *ssl, int type,
5379                                                        size_t len, void *arg))
5380 {
5381     ctx->record_padding_cb = cb;
5382 }
5383
5384 void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
5385 {
5386     ctx->record_padding_arg = arg;
5387 }
5388
5389 void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx)
5390 {
5391     return ctx->record_padding_arg;
5392 }
5393
5394 int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
5395 {
5396     /* block size of 0 or 1 is basically no padding */
5397     if (block_size == 1)
5398         ctx->block_padding = 0;
5399     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
5400         ctx->block_padding = block_size;
5401     else
5402         return 0;
5403     return 1;
5404 }
5405
5406 int SSL_set_record_padding_callback(SSL *ssl,
5407                                      size_t (*cb) (SSL *ssl, int type,
5408                                                    size_t len, void *arg))
5409 {
5410     BIO *b;
5411     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5412
5413     if (sc == NULL)
5414         return 0;
5415
5416     b = SSL_get_wbio(ssl);
5417     if (b == NULL || !BIO_get_ktls_send(b)) {
5418         sc->rlayer.record_padding_cb = cb;
5419         return 1;
5420     }
5421     return 0;
5422 }
5423
5424 void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
5425 {
5426     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5427
5428     if (sc == NULL)
5429         return;
5430
5431     sc->rlayer.record_padding_arg = arg;
5432 }
5433
5434 void *SSL_get_record_padding_callback_arg(const SSL *ssl)
5435 {
5436     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(ssl);
5437
5438     if (sc == NULL)
5439         return NULL;
5440
5441     return sc->rlayer.record_padding_arg;
5442 }
5443
5444 int SSL_set_block_padding(SSL *ssl, size_t block_size)
5445 {
5446     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
5447
5448     if (sc == NULL)
5449         return 0;
5450
5451     /* block size of 0 or 1 is basically no padding */
5452     if (block_size == 1)
5453         sc->rlayer.block_padding = 0;
5454     else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
5455         sc->rlayer.block_padding = block_size;
5456     else
5457         return 0;
5458     return 1;
5459 }
5460
5461 int SSL_set_num_tickets(SSL *s, size_t num_tickets)
5462 {
5463     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5464
5465     if (sc == NULL)
5466         return 0;
5467
5468     sc->num_tickets = num_tickets;
5469
5470     return 1;
5471 }
5472
5473 size_t SSL_get_num_tickets(const SSL *s)
5474 {
5475     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5476
5477     if (sc == NULL)
5478         return 0;
5479
5480     return sc->num_tickets;
5481 }
5482
5483 int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets)
5484 {
5485     ctx->num_tickets = num_tickets;
5486
5487     return 1;
5488 }
5489
5490 size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx)
5491 {
5492     return ctx->num_tickets;
5493 }
5494
5495 /*
5496  * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
5497  * variable, freeing EVP_MD_CTX previously stored in that variable, if any.
5498  * If EVP_MD pointer is passed, initializes ctx with this |md|.
5499  * Returns the newly allocated ctx;
5500  */
5501
5502 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
5503 {
5504     ssl_clear_hash_ctx(hash);
5505     *hash = EVP_MD_CTX_new();
5506     if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
5507         EVP_MD_CTX_free(*hash);
5508         *hash = NULL;
5509         return NULL;
5510     }
5511     return *hash;
5512 }
5513
5514 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
5515 {
5516
5517     EVP_MD_CTX_free(*hash);
5518     *hash = NULL;
5519 }
5520
5521 /* Retrieve handshake hashes */
5522 int ssl_handshake_hash(SSL_CONNECTION *s,
5523                        unsigned char *out, size_t outlen,
5524                        size_t *hashlen)
5525 {
5526     EVP_MD_CTX *ctx = NULL;
5527     EVP_MD_CTX *hdgst = s->s3.handshake_dgst;
5528     int hashleni = EVP_MD_CTX_get_size(hdgst);
5529     int ret = 0;
5530
5531     if (hashleni < 0 || (size_t)hashleni > outlen) {
5532         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5533         goto err;
5534     }
5535
5536     ctx = EVP_MD_CTX_new();
5537     if (ctx == NULL) {
5538         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5539         goto err;
5540     }
5541
5542     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
5543         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0) {
5544         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
5545         goto err;
5546     }
5547
5548     *hashlen = hashleni;
5549
5550     ret = 1;
5551  err:
5552     EVP_MD_CTX_free(ctx);
5553     return ret;
5554 }
5555
5556 int SSL_session_reused(const SSL *s)
5557 {
5558     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5559
5560     if (sc == NULL)
5561         return 0;
5562
5563     return sc->hit;
5564 }
5565
5566 int SSL_is_server(const SSL *s)
5567 {
5568     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5569
5570     if (sc == NULL)
5571         return 0;
5572
5573     return sc->server;
5574 }
5575
5576 #ifndef OPENSSL_NO_DEPRECATED_1_1_0
5577 void SSL_set_debug(SSL *s, int debug)
5578 {
5579     /* Old function was do-nothing anyway... */
5580     (void)s;
5581     (void)debug;
5582 }
5583 #endif
5584
5585 void SSL_set_security_level(SSL *s, int level)
5586 {
5587     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5588
5589     if (sc == NULL)
5590         return;
5591
5592     sc->cert->sec_level = level;
5593 }
5594
5595 int SSL_get_security_level(const SSL *s)
5596 {
5597     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5598
5599     if (sc == NULL)
5600         return 0;
5601
5602     return sc->cert->sec_level;
5603 }
5604
5605 void SSL_set_security_callback(SSL *s,
5606                                int (*cb) (const SSL *s, const SSL_CTX *ctx,
5607                                           int op, int bits, int nid,
5608                                           void *other, void *ex))
5609 {
5610     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5611
5612     if (sc == NULL)
5613         return;
5614
5615     sc->cert->sec_cb = cb;
5616 }
5617
5618 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
5619                                                 const SSL_CTX *ctx, int op,
5620                                                 int bits, int nid, void *other,
5621                                                 void *ex) {
5622     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5623
5624     if (sc == NULL)
5625         return NULL;
5626
5627     return sc->cert->sec_cb;
5628 }
5629
5630 void SSL_set0_security_ex_data(SSL *s, void *ex)
5631 {
5632     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5633
5634     if (sc == NULL)
5635         return;
5636
5637     sc->cert->sec_ex = ex;
5638 }
5639
5640 void *SSL_get0_security_ex_data(const SSL *s)
5641 {
5642     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5643
5644     if (sc == NULL)
5645         return NULL;
5646
5647     return sc->cert->sec_ex;
5648 }
5649
5650 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
5651 {
5652     ctx->cert->sec_level = level;
5653 }
5654
5655 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
5656 {
5657     return ctx->cert->sec_level;
5658 }
5659
5660 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
5661                                    int (*cb) (const SSL *s, const SSL_CTX *ctx,
5662                                               int op, int bits, int nid,
5663                                               void *other, void *ex))
5664 {
5665     ctx->cert->sec_cb = cb;
5666 }
5667
5668 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
5669                                                           const SSL_CTX *ctx,
5670                                                           int op, int bits,
5671                                                           int nid,
5672                                                           void *other,
5673                                                           void *ex) {
5674     return ctx->cert->sec_cb;
5675 }
5676
5677 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
5678 {
5679     ctx->cert->sec_ex = ex;
5680 }
5681
5682 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
5683 {
5684     return ctx->cert->sec_ex;
5685 }
5686
5687 uint64_t SSL_CTX_get_options(const SSL_CTX *ctx)
5688 {
5689     return ctx->options;
5690 }
5691
5692 uint64_t SSL_get_options(const SSL *s)
5693 {
5694     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5695
5696     if (sc == NULL)
5697         return 0;
5698
5699     return sc->options;
5700 }
5701
5702 uint64_t SSL_CTX_set_options(SSL_CTX *ctx, uint64_t op)
5703 {
5704     return ctx->options |= op;
5705 }
5706
5707 uint64_t SSL_set_options(SSL *s, uint64_t op)
5708 {
5709     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5710     OSSL_PARAM options[2], *opts = options;
5711
5712     if (sc == NULL)
5713         return 0;
5714
5715     sc->options |= op;
5716
5717     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
5718                                           &sc->options);
5719     *opts = OSSL_PARAM_construct_end();
5720
5721     /* Ignore return value */
5722     sc->rlayer.rrlmethod->set_options(sc->rlayer.rrl, options);
5723
5724     return sc->options;
5725 }
5726
5727 uint64_t SSL_CTX_clear_options(SSL_CTX *ctx, uint64_t op)
5728 {
5729     return ctx->options &= ~op;
5730 }
5731
5732 uint64_t SSL_clear_options(SSL *s, uint64_t op)
5733 {
5734     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5735
5736     if (sc == NULL)
5737         return 0;
5738
5739     return sc->options &= ~op;
5740 }
5741
5742 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
5743 {
5744     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5745
5746     if (sc == NULL)
5747         return NULL;
5748
5749     return sc->verified_chain;
5750 }
5751
5752 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
5753
5754 #ifndef OPENSSL_NO_CT
5755
5756 /*
5757  * Moves SCTs from the |src| stack to the |dst| stack.
5758  * The source of each SCT will be set to |origin|.
5759  * If |dst| points to a NULL pointer, a new stack will be created and owned by
5760  * the caller.
5761  * Returns the number of SCTs moved, or a negative integer if an error occurs.
5762  */
5763 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
5764                         sct_source_t origin)
5765 {
5766     int scts_moved = 0;
5767     SCT *sct = NULL;
5768
5769     if (*dst == NULL) {
5770         *dst = sk_SCT_new_null();
5771         if (*dst == NULL) {
5772             ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
5773             goto err;
5774         }
5775     }
5776
5777     while (sk_SCT_num(src) > 0) {
5778         sct = sk_SCT_pop(src);
5779         if (SCT_set_source(sct, origin) != 1)
5780             goto err;
5781
5782         if (sk_SCT_push(*dst, sct) <= 0)
5783             goto err;
5784         scts_moved += 1;
5785     }
5786
5787     return scts_moved;
5788  err:
5789     if (sct != NULL)
5790         sk_SCT_push(src, sct);  /* Put the SCT back */
5791     return -1;
5792 }
5793
5794 /*
5795  * Look for data collected during ServerHello and parse if found.
5796  * Returns the number of SCTs extracted.
5797  */
5798 static int ct_extract_tls_extension_scts(SSL_CONNECTION *s)
5799 {
5800     int scts_extracted = 0;
5801
5802     if (s->ext.scts != NULL) {
5803         const unsigned char *p = s->ext.scts;
5804         STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
5805
5806         scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
5807
5808         SCT_LIST_free(scts);
5809     }
5810
5811     return scts_extracted;
5812 }
5813
5814 /*
5815  * Checks for an OCSP response and then attempts to extract any SCTs found if it
5816  * contains an SCT X509 extension. They will be stored in |s->scts|.
5817  * Returns:
5818  * - The number of SCTs extracted, assuming an OCSP response exists.
5819  * - 0 if no OCSP response exists or it contains no SCTs.
5820  * - A negative integer if an error occurs.
5821  */
5822 static int ct_extract_ocsp_response_scts(SSL_CONNECTION *s)
5823 {
5824 # ifndef OPENSSL_NO_OCSP
5825     int scts_extracted = 0;
5826     const unsigned char *p;
5827     OCSP_BASICRESP *br = NULL;
5828     OCSP_RESPONSE *rsp = NULL;
5829     STACK_OF(SCT) *scts = NULL;
5830     int i;
5831
5832     if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
5833         goto err;
5834
5835     p = s->ext.ocsp.resp;
5836     rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
5837     if (rsp == NULL)
5838         goto err;
5839
5840     br = OCSP_response_get1_basic(rsp);
5841     if (br == NULL)
5842         goto err;
5843
5844     for (i = 0; i < OCSP_resp_count(br); ++i) {
5845         OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
5846
5847         if (single == NULL)
5848             continue;
5849
5850         scts =
5851             OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
5852         scts_extracted =
5853             ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
5854         if (scts_extracted < 0)
5855             goto err;
5856     }
5857  err:
5858     SCT_LIST_free(scts);
5859     OCSP_BASICRESP_free(br);
5860     OCSP_RESPONSE_free(rsp);
5861     return scts_extracted;
5862 # else
5863     /* Behave as if no OCSP response exists */
5864     return 0;
5865 # endif
5866 }
5867
5868 /*
5869  * Attempts to extract SCTs from the peer certificate.
5870  * Return the number of SCTs extracted, or a negative integer if an error
5871  * occurs.
5872  */
5873 static int ct_extract_x509v3_extension_scts(SSL_CONNECTION *s)
5874 {
5875     int scts_extracted = 0;
5876     X509 *cert = s->session != NULL ? s->session->peer : NULL;
5877
5878     if (cert != NULL) {
5879         STACK_OF(SCT) *scts =
5880             X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
5881
5882         scts_extracted =
5883             ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
5884
5885         SCT_LIST_free(scts);
5886     }
5887
5888     return scts_extracted;
5889 }
5890
5891 /*
5892  * Attempts to find all received SCTs by checking TLS extensions, the OCSP
5893  * response (if it exists) and X509v3 extensions in the certificate.
5894  * Returns NULL if an error occurs.
5895  */
5896 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
5897 {
5898     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5899
5900     if (sc == NULL)
5901         return NULL;
5902
5903     if (!sc->scts_parsed) {
5904         if (ct_extract_tls_extension_scts(sc) < 0 ||
5905             ct_extract_ocsp_response_scts(sc) < 0 ||
5906             ct_extract_x509v3_extension_scts(sc) < 0)
5907             goto err;
5908
5909         sc->scts_parsed = 1;
5910     }
5911     return sc->scts;
5912  err:
5913     return NULL;
5914 }
5915
5916 static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
5917                          const STACK_OF(SCT) *scts, void *unused_arg)
5918 {
5919     return 1;
5920 }
5921
5922 static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
5923                      const STACK_OF(SCT) *scts, void *unused_arg)
5924 {
5925     int count = scts != NULL ? sk_SCT_num(scts) : 0;
5926     int i;
5927
5928     for (i = 0; i < count; ++i) {
5929         SCT *sct = sk_SCT_value(scts, i);
5930         int status = SCT_get_validation_status(sct);
5931
5932         if (status == SCT_VALIDATION_STATUS_VALID)
5933             return 1;
5934     }
5935     ERR_raise(ERR_LIB_SSL, SSL_R_NO_VALID_SCTS);
5936     return 0;
5937 }
5938
5939 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
5940                                    void *arg)
5941 {
5942     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
5943
5944     if (sc == NULL)
5945         return 0;
5946
5947     /*
5948      * Since code exists that uses the custom extension handler for CT, look
5949      * for this and throw an error if they have already registered to use CT.
5950      */
5951     if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
5952                                                           TLSEXT_TYPE_signed_certificate_timestamp))
5953     {
5954         ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
5955         return 0;
5956     }
5957
5958     if (callback != NULL) {
5959         /*
5960          * If we are validating CT, then we MUST accept SCTs served via OCSP
5961          */
5962         if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
5963             return 0;
5964     }
5965
5966     sc->ct_validation_callback = callback;
5967     sc->ct_validation_callback_arg = arg;
5968
5969     return 1;
5970 }
5971
5972 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
5973                                        ssl_ct_validation_cb callback, void *arg)
5974 {
5975     /*
5976      * Since code exists that uses the custom extension handler for CT, look for
5977      * this and throw an error if they have already registered to use CT.
5978      */
5979     if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
5980                                                           TLSEXT_TYPE_signed_certificate_timestamp))
5981     {
5982         ERR_raise(ERR_LIB_SSL, SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
5983         return 0;
5984     }
5985
5986     ctx->ct_validation_callback = callback;
5987     ctx->ct_validation_callback_arg = arg;
5988     return 1;
5989 }
5990
5991 int SSL_ct_is_enabled(const SSL *s)
5992 {
5993     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
5994
5995     if (sc == NULL)
5996         return 0;
5997
5998     return sc->ct_validation_callback != NULL;
5999 }
6000
6001 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
6002 {
6003     return ctx->ct_validation_callback != NULL;
6004 }
6005
6006 int ssl_validate_ct(SSL_CONNECTION *s)
6007 {
6008     int ret = 0;
6009     X509 *cert = s->session != NULL ? s->session->peer : NULL;
6010     X509 *issuer;
6011     SSL_DANE *dane = &s->dane;
6012     CT_POLICY_EVAL_CTX *ctx = NULL;
6013     const STACK_OF(SCT) *scts;
6014
6015     /*
6016      * If no callback is set, the peer is anonymous, or its chain is invalid,
6017      * skip SCT validation - just return success.  Applications that continue
6018      * handshakes without certificates, with unverified chains, or pinned leaf
6019      * certificates are outside the scope of the WebPKI and CT.
6020      *
6021      * The above exclusions notwithstanding the vast majority of peers will
6022      * have rather ordinary certificate chains validated by typical
6023      * applications that perform certificate verification and therefore will
6024      * process SCTs when enabled.
6025      */
6026     if (s->ct_validation_callback == NULL || cert == NULL ||
6027         s->verify_result != X509_V_OK ||
6028         s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
6029         return 1;
6030
6031     /*
6032      * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
6033      * trust-anchors.  See https://tools.ietf.org/html/rfc7671#section-4.2
6034      */
6035     if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
6036         switch (dane->mtlsa->usage) {
6037         case DANETLS_USAGE_DANE_TA:
6038         case DANETLS_USAGE_DANE_EE:
6039             return 1;
6040         }
6041     }
6042
6043     ctx = CT_POLICY_EVAL_CTX_new_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
6044                                     SSL_CONNECTION_GET_CTX(s)->propq);
6045     if (ctx == NULL) {
6046         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CT_LIB);
6047         goto end;
6048     }
6049
6050     issuer = sk_X509_value(s->verified_chain, 1);
6051     CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
6052     CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
6053     CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx,
6054             SSL_CONNECTION_GET_CTX(s)->ctlog_store);
6055     CT_POLICY_EVAL_CTX_set_time(
6056             ctx, (uint64_t)SSL_SESSION_get_time(s->session) * 1000);
6057
6058     scts = SSL_get0_peer_scts(SSL_CONNECTION_GET_SSL(s));
6059
6060     /*
6061      * This function returns success (> 0) only when all the SCTs are valid, 0
6062      * when some are invalid, and < 0 on various internal errors (out of
6063      * memory, etc.).  Having some, or even all, invalid SCTs is not sufficient
6064      * reason to abort the handshake, that decision is up to the callback.
6065      * Therefore, we error out only in the unexpected case that the return
6066      * value is negative.
6067      *
6068      * XXX: One might well argue that the return value of this function is an
6069      * unfortunate design choice.  Its job is only to determine the validation
6070      * status of each of the provided SCTs.  So long as it correctly separates
6071      * the wheat from the chaff it should return success.  Failure in this case
6072      * ought to correspond to an inability to carry out its duties.
6073      */
6074     if (SCT_LIST_validate(scts, ctx) < 0) {
6075         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_SCT_VERIFICATION_FAILED);
6076         goto end;
6077     }
6078
6079     ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
6080     if (ret < 0)
6081         ret = 0;                /* This function returns 0 on failure */
6082     if (!ret)
6083         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_CALLBACK_FAILED);
6084
6085  end:
6086     CT_POLICY_EVAL_CTX_free(ctx);
6087     /*
6088      * With SSL_VERIFY_NONE the session may be cached and re-used despite a
6089      * failure return code here.  Also the application may wish the complete
6090      * the handshake, and then disconnect cleanly at a higher layer, after
6091      * checking the verification status of the completed connection.
6092      *
6093      * We therefore force a certificate verification failure which will be
6094      * visible via SSL_get_verify_result() and cached as part of any resumed
6095      * session.
6096      *
6097      * Note: the permissive callback is for information gathering only, always
6098      * returns success, and does not affect verification status.  Only the
6099      * strict callback or a custom application-specified callback can trigger
6100      * connection failure or record a verification error.
6101      */
6102     if (ret <= 0)
6103         s->verify_result = X509_V_ERR_NO_VALID_SCTS;
6104     return ret;
6105 }
6106
6107 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
6108 {
6109     switch (validation_mode) {
6110     default:
6111         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
6112         return 0;
6113     case SSL_CT_VALIDATION_PERMISSIVE:
6114         return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
6115     case SSL_CT_VALIDATION_STRICT:
6116         return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
6117     }
6118 }
6119
6120 int SSL_enable_ct(SSL *s, int validation_mode)
6121 {
6122     switch (validation_mode) {
6123     default:
6124         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CT_VALIDATION_TYPE);
6125         return 0;
6126     case SSL_CT_VALIDATION_PERMISSIVE:
6127         return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
6128     case SSL_CT_VALIDATION_STRICT:
6129         return SSL_set_ct_validation_callback(s, ct_strict, NULL);
6130     }
6131 }
6132
6133 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
6134 {
6135     return CTLOG_STORE_load_default_file(ctx->ctlog_store);
6136 }
6137
6138 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
6139 {
6140     return CTLOG_STORE_load_file(ctx->ctlog_store, path);
6141 }
6142
6143 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE * logs)
6144 {
6145     CTLOG_STORE_free(ctx->ctlog_store);
6146     ctx->ctlog_store = logs;
6147 }
6148
6149 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
6150 {
6151     return ctx->ctlog_store;
6152 }
6153
6154 #endif  /* OPENSSL_NO_CT */
6155
6156 void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
6157                                  void *arg)
6158 {
6159     c->client_hello_cb = cb;
6160     c->client_hello_cb_arg = arg;
6161 }
6162
6163 int SSL_client_hello_isv2(SSL *s)
6164 {
6165     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6166
6167     if (sc == NULL)
6168         return 0;
6169
6170     if (sc->clienthello == NULL)
6171         return 0;
6172     return sc->clienthello->isv2;
6173 }
6174
6175 unsigned int SSL_client_hello_get0_legacy_version(SSL *s)
6176 {
6177     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6178
6179     if (sc == NULL)
6180         return 0;
6181
6182     if (sc->clienthello == NULL)
6183         return 0;
6184     return sc->clienthello->legacy_version;
6185 }
6186
6187 size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out)
6188 {
6189     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6190
6191     if (sc == NULL)
6192         return 0;
6193
6194     if (sc->clienthello == NULL)
6195         return 0;
6196     if (out != NULL)
6197         *out = sc->clienthello->random;
6198     return SSL3_RANDOM_SIZE;
6199 }
6200
6201 size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out)
6202 {
6203     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6204
6205     if (sc == NULL)
6206         return 0;
6207
6208     if (sc->clienthello == NULL)
6209         return 0;
6210     if (out != NULL)
6211         *out = sc->clienthello->session_id;
6212     return sc->clienthello->session_id_len;
6213 }
6214
6215 size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out)
6216 {
6217     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6218
6219     if (sc == NULL)
6220         return 0;
6221
6222     if (sc->clienthello == NULL)
6223         return 0;
6224     if (out != NULL)
6225         *out = PACKET_data(&sc->clienthello->ciphersuites);
6226     return PACKET_remaining(&sc->clienthello->ciphersuites);
6227 }
6228
6229 size_t SSL_client_hello_get0_compression_methods(SSL *s, const unsigned char **out)
6230 {
6231     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6232
6233     if (sc == NULL)
6234         return 0;
6235
6236     if (sc->clienthello == NULL)
6237         return 0;
6238     if (out != NULL)
6239         *out = sc->clienthello->compressions;
6240     return sc->clienthello->compressions_len;
6241 }
6242
6243 int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen)
6244 {
6245     RAW_EXTENSION *ext;
6246     int *present;
6247     size_t num = 0, i;
6248     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6249
6250     if (sc == NULL)
6251         return 0;
6252
6253     if (sc->clienthello == NULL || out == NULL || outlen == NULL)
6254         return 0;
6255     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6256         ext = sc->clienthello->pre_proc_exts + i;
6257         if (ext->present)
6258             num++;
6259     }
6260     if (num == 0) {
6261         *out = NULL;
6262         *outlen = 0;
6263         return 1;
6264     }
6265     if ((present = OPENSSL_malloc(sizeof(*present) * num)) == NULL)
6266         return 0;
6267     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6268         ext = sc->clienthello->pre_proc_exts + i;
6269         if (ext->present) {
6270             if (ext->received_order >= num)
6271                 goto err;
6272             present[ext->received_order] = ext->type;
6273         }
6274     }
6275     *out = present;
6276     *outlen = num;
6277     return 1;
6278  err:
6279     OPENSSL_free(present);
6280     return 0;
6281 }
6282
6283 int SSL_client_hello_get_extension_order(SSL *s, uint16_t *exts, size_t *num_exts)
6284 {
6285     RAW_EXTENSION *ext;
6286     size_t num = 0, i;
6287     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6288
6289     if (sc == NULL)
6290         return 0;
6291
6292     if (sc->clienthello == NULL || num_exts == NULL)
6293         return 0;
6294     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6295         ext = sc->clienthello->pre_proc_exts + i;
6296         if (ext->present)
6297             num++;
6298     }
6299     if (num == 0) {
6300         *num_exts = 0;
6301         return 1;
6302     }
6303     if (exts == NULL) {
6304         *num_exts = num;
6305         return 1;
6306     }
6307     if (*num_exts < num)
6308         return 0;
6309     for (i = 0; i < sc->clienthello->pre_proc_exts_len; i++) {
6310         ext = sc->clienthello->pre_proc_exts + i;
6311         if (ext->present) {
6312             if (ext->received_order >= num)
6313                 return 0;
6314             exts[ext->received_order] = ext->type;
6315         }
6316     }
6317     *num_exts = num;
6318     return 1;
6319 }
6320
6321 int SSL_client_hello_get0_ext(SSL *s, unsigned int type, const unsigned char **out,
6322                        size_t *outlen)
6323 {
6324     size_t i;
6325     RAW_EXTENSION *r;
6326     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6327
6328     if (sc == NULL)
6329         return 0;
6330
6331     if (sc->clienthello == NULL)
6332         return 0;
6333     for (i = 0; i < sc->clienthello->pre_proc_exts_len; ++i) {
6334         r = sc->clienthello->pre_proc_exts + i;
6335         if (r->present && r->type == type) {
6336             if (out != NULL)
6337                 *out = PACKET_data(&r->data);
6338             if (outlen != NULL)
6339                 *outlen = PACKET_remaining(&r->data);
6340             return 1;
6341         }
6342     }
6343     return 0;
6344 }
6345
6346 int SSL_free_buffers(SSL *ssl)
6347 {
6348     RECORD_LAYER *rl;
6349     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
6350
6351     if (sc == NULL)
6352         return 0;
6353
6354     rl = &sc->rlayer;
6355
6356     if (RECORD_LAYER_read_pending(rl) || RECORD_LAYER_write_pending(rl))
6357         return 0;
6358
6359     RECORD_LAYER_release(rl);
6360     return 1;
6361 }
6362
6363 int SSL_alloc_buffers(SSL *ssl)
6364 {
6365     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
6366
6367     if (sc == NULL)
6368         return 0;
6369
6370     return ssl3_setup_buffers(sc);
6371 }
6372
6373 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
6374 {
6375     ctx->keylog_callback = cb;
6376 }
6377
6378 SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
6379 {
6380     return ctx->keylog_callback;
6381 }
6382
6383 static int nss_keylog_int(const char *prefix,
6384                           SSL_CONNECTION *sc,
6385                           const uint8_t *parameter_1,
6386                           size_t parameter_1_len,
6387                           const uint8_t *parameter_2,
6388                           size_t parameter_2_len)
6389 {
6390     char *out = NULL;
6391     char *cursor = NULL;
6392     size_t out_len = 0;
6393     size_t i;
6394     size_t prefix_len;
6395     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
6396
6397     if (sctx->keylog_callback == NULL)
6398         return 1;
6399
6400     /*
6401      * Our output buffer will contain the following strings, rendered with
6402      * space characters in between, terminated by a NULL character: first the
6403      * prefix, then the first parameter, then the second parameter. The
6404      * meaning of each parameter depends on the specific key material being
6405      * logged. Note that the first and second parameters are encoded in
6406      * hexadecimal, so we need a buffer that is twice their lengths.
6407      */
6408     prefix_len = strlen(prefix);
6409     out_len = prefix_len + (2 * parameter_1_len) + (2 * parameter_2_len) + 3;
6410     if ((out = cursor = OPENSSL_malloc(out_len)) == NULL)
6411         return 0;
6412
6413     strcpy(cursor, prefix);
6414     cursor += prefix_len;
6415     *cursor++ = ' ';
6416
6417     for (i = 0; i < parameter_1_len; i++) {
6418         sprintf(cursor, "%02x", parameter_1[i]);
6419         cursor += 2;
6420     }
6421     *cursor++ = ' ';
6422
6423     for (i = 0; i < parameter_2_len; i++) {
6424         sprintf(cursor, "%02x", parameter_2[i]);
6425         cursor += 2;
6426     }
6427     *cursor = '\0';
6428
6429     sctx->keylog_callback(SSL_CONNECTION_GET_SSL(sc), (const char *)out);
6430     OPENSSL_clear_free(out, out_len);
6431     return 1;
6432
6433 }
6434
6435 int ssl_log_rsa_client_key_exchange(SSL_CONNECTION *sc,
6436                                     const uint8_t *encrypted_premaster,
6437                                     size_t encrypted_premaster_len,
6438                                     const uint8_t *premaster,
6439                                     size_t premaster_len)
6440 {
6441     if (encrypted_premaster_len < 8) {
6442         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
6443         return 0;
6444     }
6445
6446     /* We only want the first 8 bytes of the encrypted premaster as a tag. */
6447     return nss_keylog_int("RSA",
6448                           sc,
6449                           encrypted_premaster,
6450                           8,
6451                           premaster,
6452                           premaster_len);
6453 }
6454
6455 int ssl_log_secret(SSL_CONNECTION *sc,
6456                    const char *label,
6457                    const uint8_t *secret,
6458                    size_t secret_len)
6459 {
6460     return nss_keylog_int(label,
6461                           sc,
6462                           sc->s3.client_random,
6463                           SSL3_RANDOM_SIZE,
6464                           secret,
6465                           secret_len);
6466 }
6467
6468 #define SSLV2_CIPHER_LEN    3
6469
6470 int ssl_cache_cipherlist(SSL_CONNECTION *s, PACKET *cipher_suites, int sslv2format)
6471 {
6472     int n;
6473
6474     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
6475
6476     if (PACKET_remaining(cipher_suites) == 0) {
6477         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
6478         return 0;
6479     }
6480
6481     if (PACKET_remaining(cipher_suites) % n != 0) {
6482         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6483         return 0;
6484     }
6485
6486     OPENSSL_free(s->s3.tmp.ciphers_raw);
6487     s->s3.tmp.ciphers_raw = NULL;
6488     s->s3.tmp.ciphers_rawlen = 0;
6489
6490     if (sslv2format) {
6491         size_t numciphers = PACKET_remaining(cipher_suites) / n;
6492         PACKET sslv2ciphers = *cipher_suites;
6493         unsigned int leadbyte;
6494         unsigned char *raw;
6495
6496         /*
6497          * We store the raw ciphers list in SSLv3+ format so we need to do some
6498          * preprocessing to convert the list first. If there are any SSLv2 only
6499          * ciphersuites with a non-zero leading byte then we are going to
6500          * slightly over allocate because we won't store those. But that isn't a
6501          * problem.
6502          */
6503         raw = OPENSSL_malloc(numciphers * TLS_CIPHER_LEN);
6504         s->s3.tmp.ciphers_raw = raw;
6505         if (raw == NULL) {
6506             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6507             return 0;
6508         }
6509         for (s->s3.tmp.ciphers_rawlen = 0;
6510              PACKET_remaining(&sslv2ciphers) > 0;
6511              raw += TLS_CIPHER_LEN) {
6512             if (!PACKET_get_1(&sslv2ciphers, &leadbyte)
6513                     || (leadbyte == 0
6514                         && !PACKET_copy_bytes(&sslv2ciphers, raw,
6515                                               TLS_CIPHER_LEN))
6516                     || (leadbyte != 0
6517                         && !PACKET_forward(&sslv2ciphers, TLS_CIPHER_LEN))) {
6518                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
6519                 OPENSSL_free(s->s3.tmp.ciphers_raw);
6520                 s->s3.tmp.ciphers_raw = NULL;
6521                 s->s3.tmp.ciphers_rawlen = 0;
6522                 return 0;
6523             }
6524             if (leadbyte == 0)
6525                 s->s3.tmp.ciphers_rawlen += TLS_CIPHER_LEN;
6526         }
6527     } else if (!PACKET_memdup(cipher_suites, &s->s3.tmp.ciphers_raw,
6528                            &s->s3.tmp.ciphers_rawlen)) {
6529         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
6530         return 0;
6531     }
6532     return 1;
6533 }
6534
6535 int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
6536                              int isv2format, STACK_OF(SSL_CIPHER) **sk,
6537                              STACK_OF(SSL_CIPHER) **scsvs)
6538 {
6539     PACKET pkt;
6540     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6541
6542     if (sc == NULL)
6543         return 0;
6544
6545     if (!PACKET_buf_init(&pkt, bytes, len))
6546         return 0;
6547     return ossl_bytes_to_cipher_list(sc, &pkt, sk, scsvs, isv2format, 0);
6548 }
6549
6550 int ossl_bytes_to_cipher_list(SSL_CONNECTION *s, PACKET *cipher_suites,
6551                               STACK_OF(SSL_CIPHER) **skp,
6552                               STACK_OF(SSL_CIPHER) **scsvs_out,
6553                               int sslv2format, int fatal)
6554 {
6555     const SSL_CIPHER *c;
6556     STACK_OF(SSL_CIPHER) *sk = NULL;
6557     STACK_OF(SSL_CIPHER) *scsvs = NULL;
6558     int n;
6559     /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
6560     unsigned char cipher[SSLV2_CIPHER_LEN];
6561
6562     n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
6563
6564     if (PACKET_remaining(cipher_suites) == 0) {
6565         if (fatal)
6566             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CIPHERS_SPECIFIED);
6567         else
6568             ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHERS_SPECIFIED);
6569         return 0;
6570     }
6571
6572     if (PACKET_remaining(cipher_suites) % n != 0) {
6573         if (fatal)
6574             SSLfatal(s, SSL_AD_DECODE_ERROR,
6575                      SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6576         else
6577             ERR_raise(ERR_LIB_SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
6578         return 0;
6579     }
6580
6581     sk = sk_SSL_CIPHER_new_null();
6582     scsvs = sk_SSL_CIPHER_new_null();
6583     if (sk == NULL || scsvs == NULL) {
6584         if (fatal)
6585             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6586         else
6587             ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
6588         goto err;
6589     }
6590
6591     while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
6592         /*
6593          * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
6594          * first byte set to zero, while true SSLv2 ciphers have a non-zero
6595          * first byte. We don't support any true SSLv2 ciphers, so skip them.
6596          */
6597         if (sslv2format && cipher[0] != '\0')
6598             continue;
6599
6600         /* For SSLv2-compat, ignore leading 0-byte. */
6601         c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher, 1);
6602         if (c != NULL) {
6603             if ((c->valid && !sk_SSL_CIPHER_push(sk, c)) ||
6604                 (!c->valid && !sk_SSL_CIPHER_push(scsvs, c))) {
6605                 if (fatal)
6606                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
6607                 else
6608                     ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
6609                 goto err;
6610             }
6611         }
6612     }
6613     if (PACKET_remaining(cipher_suites) > 0) {
6614         if (fatal)
6615             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
6616         else
6617             ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
6618         goto err;
6619     }
6620
6621     if (skp != NULL)
6622         *skp = sk;
6623     else
6624         sk_SSL_CIPHER_free(sk);
6625     if (scsvs_out != NULL)
6626         *scsvs_out = scsvs;
6627     else
6628         sk_SSL_CIPHER_free(scsvs);
6629     return 1;
6630  err:
6631     sk_SSL_CIPHER_free(sk);
6632     sk_SSL_CIPHER_free(scsvs);
6633     return 0;
6634 }
6635
6636 int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
6637 {
6638     ctx->max_early_data = max_early_data;
6639
6640     return 1;
6641 }
6642
6643 uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
6644 {
6645     return ctx->max_early_data;
6646 }
6647
6648 int SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
6649 {
6650     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6651
6652     if (sc == NULL)
6653         return 0;
6654
6655     sc->max_early_data = max_early_data;
6656
6657     return 1;
6658 }
6659
6660 uint32_t SSL_get_max_early_data(const SSL *s)
6661 {
6662     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
6663
6664     if (sc == NULL)
6665         return 0;
6666
6667     return sc->max_early_data;
6668 }
6669
6670 int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data)
6671 {
6672     ctx->recv_max_early_data = recv_max_early_data;
6673
6674     return 1;
6675 }
6676
6677 uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx)
6678 {
6679     return ctx->recv_max_early_data;
6680 }
6681
6682 int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data)
6683 {
6684     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6685
6686     if (sc == NULL)
6687         return 0;
6688
6689     sc->recv_max_early_data = recv_max_early_data;
6690
6691     return 1;
6692 }
6693
6694 uint32_t SSL_get_recv_max_early_data(const SSL *s)
6695 {
6696     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
6697
6698     if (sc == NULL)
6699         return 0;
6700
6701     return sc->recv_max_early_data;
6702 }
6703
6704 __owur unsigned int ssl_get_max_send_fragment(const SSL_CONNECTION *sc)
6705 {
6706     /* Return any active Max Fragment Len extension */
6707     if (sc->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(sc->session))
6708         return GET_MAX_FRAGMENT_LENGTH(sc->session);
6709
6710     /* return current SSL connection setting */
6711     return sc->max_send_fragment;
6712 }
6713
6714 __owur unsigned int ssl_get_split_send_fragment(const SSL_CONNECTION *sc)
6715 {
6716     /* Return a value regarding an active Max Fragment Len extension */
6717     if (sc->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(sc->session)
6718         && sc->split_send_fragment > GET_MAX_FRAGMENT_LENGTH(sc->session))
6719         return GET_MAX_FRAGMENT_LENGTH(sc->session);
6720
6721     /* else limit |split_send_fragment| to current |max_send_fragment| */
6722     if (sc->split_send_fragment > sc->max_send_fragment)
6723         return sc->max_send_fragment;
6724
6725     /* return current SSL connection setting */
6726     return sc->split_send_fragment;
6727 }
6728
6729 int SSL_stateless(SSL *s)
6730 {
6731     int ret;
6732     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6733
6734     /* TODO(QUIC): This will need further work. */
6735     if (sc == NULL)
6736         return 0;
6737
6738     /* Ensure there is no state left over from a previous invocation */
6739     if (!SSL_clear(s))
6740         return 0;
6741
6742     ERR_clear_error();
6743
6744     sc->s3.flags |= TLS1_FLAGS_STATELESS;
6745     ret = SSL_accept(s);
6746     sc->s3.flags &= ~TLS1_FLAGS_STATELESS;
6747
6748     if (ret > 0 && sc->ext.cookieok)
6749         return 1;
6750
6751     if (sc->hello_retry_request == SSL_HRR_PENDING && !ossl_statem_in_error(sc))
6752         return 0;
6753
6754     return -1;
6755 }
6756
6757 void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val)
6758 {
6759     ctx->pha_enabled = val;
6760 }
6761
6762 void SSL_set_post_handshake_auth(SSL *ssl, int val)
6763 {
6764     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
6765
6766     if (sc == NULL)
6767         return;
6768
6769     sc->pha_enabled = val;
6770 }
6771
6772 int SSL_verify_client_post_handshake(SSL *ssl)
6773 {
6774     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
6775
6776     if (sc == NULL)
6777         return 0;
6778
6779     if (!SSL_CONNECTION_IS_TLS13(sc)) {
6780         ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
6781         return 0;
6782     }
6783     if (!sc->server) {
6784         ERR_raise(ERR_LIB_SSL, SSL_R_NOT_SERVER);
6785         return 0;
6786     }
6787
6788     if (!SSL_is_init_finished(ssl)) {
6789         ERR_raise(ERR_LIB_SSL, SSL_R_STILL_IN_INIT);
6790         return 0;
6791     }
6792
6793     switch (sc->post_handshake_auth) {
6794     case SSL_PHA_NONE:
6795         ERR_raise(ERR_LIB_SSL, SSL_R_EXTENSION_NOT_RECEIVED);
6796         return 0;
6797     default:
6798     case SSL_PHA_EXT_SENT:
6799         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
6800         return 0;
6801     case SSL_PHA_EXT_RECEIVED:
6802         break;
6803     case SSL_PHA_REQUEST_PENDING:
6804         ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_PENDING);
6805         return 0;
6806     case SSL_PHA_REQUESTED:
6807         ERR_raise(ERR_LIB_SSL, SSL_R_REQUEST_SENT);
6808         return 0;
6809     }
6810
6811     sc->post_handshake_auth = SSL_PHA_REQUEST_PENDING;
6812
6813     /* checks verify_mode and algorithm_auth */
6814     if (!send_certificate_request(sc)) {
6815         sc->post_handshake_auth = SSL_PHA_EXT_RECEIVED; /* restore on error */
6816         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_CONFIG);
6817         return 0;
6818     }
6819
6820     ossl_statem_set_in_init(sc, 1);
6821     return 1;
6822 }
6823
6824 int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
6825                                   SSL_CTX_generate_session_ticket_fn gen_cb,
6826                                   SSL_CTX_decrypt_session_ticket_fn dec_cb,
6827                                   void *arg)
6828 {
6829     ctx->generate_ticket_cb = gen_cb;
6830     ctx->decrypt_ticket_cb = dec_cb;
6831     ctx->ticket_cb_data = arg;
6832     return 1;
6833 }
6834
6835 void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
6836                                      SSL_allow_early_data_cb_fn cb,
6837                                      void *arg)
6838 {
6839     ctx->allow_early_data_cb = cb;
6840     ctx->allow_early_data_cb_data = arg;
6841 }
6842
6843 void SSL_set_allow_early_data_cb(SSL *s,
6844                                  SSL_allow_early_data_cb_fn cb,
6845                                  void *arg)
6846 {
6847     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6848
6849     if (sc == NULL)
6850         return;
6851
6852     sc->allow_early_data_cb = cb;
6853     sc->allow_early_data_cb_data = arg;
6854 }
6855
6856 const EVP_CIPHER *ssl_evp_cipher_fetch(OSSL_LIB_CTX *libctx,
6857                                        int nid,
6858                                        const char *properties)
6859 {
6860     const EVP_CIPHER *ciph;
6861
6862     ciph = tls_get_cipher_from_engine(nid);
6863     if (ciph != NULL)
6864         return ciph;
6865
6866     /*
6867      * If there is no engine cipher then we do an explicit fetch. This may fail
6868      * and that could be ok
6869      */
6870     ERR_set_mark();
6871     ciph = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(nid), properties);
6872     ERR_pop_to_mark();
6873     return ciph;
6874 }
6875
6876
6877 int ssl_evp_cipher_up_ref(const EVP_CIPHER *cipher)
6878 {
6879     /* Don't up-ref an implicit EVP_CIPHER */
6880     if (EVP_CIPHER_get0_provider(cipher) == NULL)
6881         return 1;
6882
6883     /*
6884      * The cipher was explicitly fetched and therefore it is safe to cast
6885      * away the const
6886      */
6887     return EVP_CIPHER_up_ref((EVP_CIPHER *)cipher);
6888 }
6889
6890 void ssl_evp_cipher_free(const EVP_CIPHER *cipher)
6891 {
6892     if (cipher == NULL)
6893         return;
6894
6895     if (EVP_CIPHER_get0_provider(cipher) != NULL) {
6896         /*
6897          * The cipher was explicitly fetched and therefore it is safe to cast
6898          * away the const
6899          */
6900         EVP_CIPHER_free((EVP_CIPHER *)cipher);
6901     }
6902 }
6903
6904 const EVP_MD *ssl_evp_md_fetch(OSSL_LIB_CTX *libctx,
6905                                int nid,
6906                                const char *properties)
6907 {
6908     const EVP_MD *md;
6909
6910     md = tls_get_digest_from_engine(nid);
6911     if (md != NULL)
6912         return md;
6913
6914     /* Otherwise we do an explicit fetch */
6915     ERR_set_mark();
6916     md = EVP_MD_fetch(libctx, OBJ_nid2sn(nid), properties);
6917     ERR_pop_to_mark();
6918     return md;
6919 }
6920
6921 int ssl_evp_md_up_ref(const EVP_MD *md)
6922 {
6923     /* Don't up-ref an implicit EVP_MD */
6924     if (EVP_MD_get0_provider(md) == NULL)
6925         return 1;
6926
6927     /*
6928      * The digest was explicitly fetched and therefore it is safe to cast
6929      * away the const
6930      */
6931     return EVP_MD_up_ref((EVP_MD *)md);
6932 }
6933
6934 void ssl_evp_md_free(const EVP_MD *md)
6935 {
6936     if (md == NULL)
6937         return;
6938
6939     if (EVP_MD_get0_provider(md) != NULL) {
6940         /*
6941          * The digest was explicitly fetched and therefore it is safe to cast
6942          * away the const
6943          */
6944         EVP_MD_free((EVP_MD *)md);
6945     }
6946 }
6947
6948 int SSL_set0_tmp_dh_pkey(SSL *s, EVP_PKEY *dhpkey)
6949 {
6950     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
6951
6952     if (sc == NULL)
6953         return 0;
6954
6955     if (!ssl_security(sc, SSL_SECOP_TMP_DH,
6956                       EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
6957         ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
6958         return 0;
6959     }
6960     EVP_PKEY_free(sc->cert->dh_tmp);
6961     sc->cert->dh_tmp = dhpkey;
6962     return 1;
6963 }
6964
6965 int SSL_CTX_set0_tmp_dh_pkey(SSL_CTX *ctx, EVP_PKEY *dhpkey)
6966 {
6967     if (!ssl_ctx_security(ctx, SSL_SECOP_TMP_DH,
6968                           EVP_PKEY_get_security_bits(dhpkey), 0, dhpkey)) {
6969         ERR_raise(ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL);
6970         return 0;
6971     }
6972     EVP_PKEY_free(ctx->cert->dh_tmp);
6973     ctx->cert->dh_tmp = dhpkey;
6974     return 1;
6975 }