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