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