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