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