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