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