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