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