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