2 * Copyright 1995-2017 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.
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
14 #include <openssl/objects.h>
15 #include <openssl/x509v3.h>
16 #include <openssl/rand.h>
17 #include <openssl/ocsp.h>
18 #include <openssl/dh.h>
19 #include <openssl/engine.h>
20 #include <openssl/async.h>
21 #include <openssl/ct.h>
22 #include "internal/cryptlib.h"
23 #include "internal/rand.h"
24 #include "internal/refcount.h"
26 const char SSL_version_str[] = OPENSSL_VERSION_TEXT;
28 SSL3_ENC_METHOD ssl3_undef_enc_method = {
30 * evil casts, but these functions are only called if there's a library
33 (int (*)(SSL *, SSL3_RECORD *, size_t, int))ssl_undefined_function,
34 (int (*)(SSL *, SSL3_RECORD *, unsigned char *, int))ssl_undefined_function,
35 ssl_undefined_function,
36 (int (*)(SSL *, unsigned char *, unsigned char *, size_t, size_t *))
37 ssl_undefined_function,
38 (int (*)(SSL *, int))ssl_undefined_function,
39 (size_t (*)(SSL *, const char *, size_t, unsigned char *))
40 ssl_undefined_function,
41 NULL, /* client_finished_label */
42 0, /* client_finished_label_len */
43 NULL, /* server_finished_label */
44 0, /* server_finished_label_len */
45 (int (*)(int))ssl_undefined_function,
46 (int (*)(SSL *, unsigned char *, size_t, const char *,
47 size_t, const unsigned char *, size_t,
48 int use_context))ssl_undefined_function,
51 struct ssl_async_args {
55 enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
57 int (*func_read) (SSL *, void *, size_t, size_t *);
58 int (*func_write) (SSL *, const void *, size_t, size_t *);
59 int (*func_other) (SSL *);
69 DANETLS_MATCHING_FULL, 0, NID_undef
72 DANETLS_MATCHING_2256, 1, NID_sha256
75 DANETLS_MATCHING_2512, 2, NID_sha512
79 static int dane_ctx_enable(struct dane_ctx_st *dctx)
83 uint8_t mdmax = DANETLS_MATCHING_LAST;
84 int n = ((int)mdmax) + 1; /* int to handle PrivMatch(255) */
87 if (dctx->mdevp != NULL)
90 mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
91 mdord = OPENSSL_zalloc(n * sizeof(*mdord));
93 if (mdord == NULL || mdevp == NULL) {
96 SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
100 /* Install default entries */
101 for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
104 if (dane_mds[i].nid == NID_undef ||
105 (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
107 mdevp[dane_mds[i].mtype] = md;
108 mdord[dane_mds[i].mtype] = dane_mds[i].ord;
118 static void dane_ctx_final(struct dane_ctx_st *dctx)
120 OPENSSL_free(dctx->mdevp);
123 OPENSSL_free(dctx->mdord);
128 static void tlsa_free(danetls_record *t)
132 OPENSSL_free(t->data);
133 EVP_PKEY_free(t->spki);
137 static void dane_final(SSL_DANE *dane)
139 sk_danetls_record_pop_free(dane->trecs, tlsa_free);
142 sk_X509_pop_free(dane->certs, X509_free);
145 X509_free(dane->mcert);
153 * dane_copy - Copy dane configuration, sans verification state.
155 static int ssl_dane_dup(SSL *to, SSL *from)
160 if (!DANETLS_ENABLED(&from->dane))
163 num = sk_danetls_record_num(from->dane.trecs);
164 dane_final(&to->dane);
165 to->dane.flags = from->dane.flags;
166 to->dane.dctx = &to->ctx->dane;
167 to->dane.trecs = sk_danetls_record_new_null();
169 if (to->dane.trecs == NULL) {
170 SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
173 if (!sk_danetls_record_reserve(to->dane.trecs, num))
176 for (i = 0; i < num; ++i) {
177 danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
179 if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
180 t->data, t->dlen) <= 0)
186 static int dane_mtype_set(struct dane_ctx_st *dctx,
187 const EVP_MD *md, uint8_t mtype, uint8_t ord)
191 if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
192 SSLerr(SSL_F_DANE_MTYPE_SET, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
196 if (mtype > dctx->mdmax) {
197 const EVP_MD **mdevp;
199 int n = ((int)mtype) + 1;
201 mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
203 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
208 mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
210 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
215 /* Zero-fill any gaps */
216 for (i = dctx->mdmax + 1; i < mtype; ++i) {
224 dctx->mdevp[mtype] = md;
225 /* Coerce ordinal of disabled matching types to 0 */
226 dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
231 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
233 if (mtype > dane->dctx->mdmax)
235 return dane->dctx->mdevp[mtype];
238 static int dane_tlsa_add(SSL_DANE *dane,
241 uint8_t mtype, unsigned char *data, size_t dlen)
244 const EVP_MD *md = NULL;
245 int ilen = (int)dlen;
249 if (dane->trecs == NULL) {
250 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
254 if (ilen < 0 || dlen != (size_t)ilen) {
255 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
259 if (usage > DANETLS_USAGE_LAST) {
260 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
264 if (selector > DANETLS_SELECTOR_LAST) {
265 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
269 if (mtype != DANETLS_MATCHING_FULL) {
270 md = tlsa_md_get(dane, mtype);
272 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
277 if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
278 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
282 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
286 if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
287 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
292 t->selector = selector;
294 t->data = OPENSSL_malloc(dlen);
295 if (t->data == NULL) {
297 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
300 memcpy(t->data, data, dlen);
303 /* Validate and cache full certificate or public key */
304 if (mtype == DANETLS_MATCHING_FULL) {
305 const unsigned char *p = data;
307 EVP_PKEY *pkey = NULL;
310 case DANETLS_SELECTOR_CERT:
311 if (!d2i_X509(&cert, &p, ilen) || p < data ||
312 dlen != (size_t)(p - data)) {
314 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
317 if (X509_get0_pubkey(cert) == NULL) {
319 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
323 if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
329 * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
330 * records that contain full certificates of trust-anchors that are
331 * not present in the wire chain. For usage PKIX-TA(0), we augment
332 * the chain with untrusted Full(0) certificates from DNS, in case
333 * they are missing from the chain.
335 if ((dane->certs == NULL &&
336 (dane->certs = sk_X509_new_null()) == NULL) ||
337 !sk_X509_push(dane->certs, cert)) {
338 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
345 case DANETLS_SELECTOR_SPKI:
346 if (!d2i_PUBKEY(&pkey, &p, ilen) || p < data ||
347 dlen != (size_t)(p - data)) {
349 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
354 * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
355 * records that contain full bare keys of trust-anchors that are
356 * not present in the wire chain.
358 if (usage == DANETLS_USAGE_DANE_TA)
367 * Find the right insertion point for the new record.
369 * See crypto/x509/x509_vfy.c. We sort DANE-EE(3) records first, so that
370 * they can be processed first, as they require no chain building, and no
371 * expiration or hostname checks. Because DANE-EE(3) is numerically
372 * largest, this is accomplished via descending sort by "usage".
374 * We also sort in descending order by matching ordinal to simplify
375 * the implementation of digest agility in the verification code.
377 * The choice of order for the selector is not significant, so we
378 * use the same descending order for consistency.
380 num = sk_danetls_record_num(dane->trecs);
381 for (i = 0; i < num; ++i) {
382 danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
384 if (rec->usage > usage)
386 if (rec->usage < usage)
388 if (rec->selector > selector)
390 if (rec->selector < selector)
392 if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
397 if (!sk_danetls_record_insert(dane->trecs, t, i)) {
399 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
402 dane->umask |= DANETLS_USAGE_BIT(usage);
408 * Return 0 if there is only one version configured and it was disabled
409 * at configure time. Return 1 otherwise.
411 static int ssl_check_allowed_versions(int min_version, int max_version)
413 int minisdtls = 0, maxisdtls = 0;
415 /* Figure out if we're doing DTLS versions or TLS versions */
416 if (min_version == DTLS1_BAD_VER
417 || min_version >> 8 == DTLS1_VERSION_MAJOR)
419 if (max_version == DTLS1_BAD_VER
420 || max_version >> 8 == DTLS1_VERSION_MAJOR)
422 /* A wildcard version of 0 could be DTLS or TLS. */
423 if ((minisdtls && !maxisdtls && max_version != 0)
424 || (maxisdtls && !minisdtls && min_version != 0)) {
425 /* Mixing DTLS and TLS versions will lead to sadness; deny it. */
429 if (minisdtls || maxisdtls) {
430 /* Do DTLS version checks. */
431 if (min_version == 0)
432 /* Ignore DTLS1_BAD_VER */
433 min_version = DTLS1_VERSION;
434 if (max_version == 0)
435 max_version = DTLS1_2_VERSION;
436 #ifdef OPENSSL_NO_DTLS1_2
437 if (max_version == DTLS1_2_VERSION)
438 max_version = DTLS1_VERSION;
440 #ifdef OPENSSL_NO_DTLS1
441 if (min_version == DTLS1_VERSION)
442 min_version = DTLS1_2_VERSION;
444 /* Done massaging versions; do the check. */
446 #ifdef OPENSSL_NO_DTLS1
447 || (DTLS_VERSION_GE(min_version, DTLS1_VERSION)
448 && DTLS_VERSION_GE(DTLS1_VERSION, max_version))
450 #ifdef OPENSSL_NO_DTLS1_2
451 || (DTLS_VERSION_GE(min_version, DTLS1_2_VERSION)
452 && DTLS_VERSION_GE(DTLS1_2_VERSION, max_version))
457 /* Regular TLS version checks. */
458 if (min_version == 0)
459 min_version = SSL3_VERSION;
460 if (max_version == 0)
461 max_version = TLS1_3_VERSION;
462 #ifdef OPENSSL_NO_TLS1_3
463 if (max_version == TLS1_3_VERSION)
464 max_version = TLS1_2_VERSION;
466 #ifdef OPENSSL_NO_TLS1_2
467 if (max_version == TLS1_2_VERSION)
468 max_version = TLS1_1_VERSION;
470 #ifdef OPENSSL_NO_TLS1_1
471 if (max_version == TLS1_1_VERSION)
472 max_version = TLS1_VERSION;
474 #ifdef OPENSSL_NO_TLS1
475 if (max_version == TLS1_VERSION)
476 max_version = SSL3_VERSION;
478 #ifdef OPENSSL_NO_SSL3
479 if (min_version == SSL3_VERSION)
480 min_version = TLS1_VERSION;
482 #ifdef OPENSSL_NO_TLS1
483 if (min_version == TLS1_VERSION)
484 min_version = TLS1_1_VERSION;
486 #ifdef OPENSSL_NO_TLS1_1
487 if (min_version == TLS1_1_VERSION)
488 min_version = TLS1_2_VERSION;
490 #ifdef OPENSSL_NO_TLS1_2
491 if (min_version == TLS1_2_VERSION)
492 min_version = TLS1_3_VERSION;
494 /* Done massaging versions; do the check. */
496 #ifdef OPENSSL_NO_SSL3
497 || (min_version <= SSL3_VERSION && SSL3_VERSION <= max_version)
499 #ifdef OPENSSL_NO_TLS1
500 || (min_version <= TLS1_VERSION && TLS1_VERSION <= max_version)
502 #ifdef OPENSSL_NO_TLS1_1
503 || (min_version <= TLS1_1_VERSION && TLS1_1_VERSION <= max_version)
505 #ifdef OPENSSL_NO_TLS1_2
506 || (min_version <= TLS1_2_VERSION && TLS1_2_VERSION <= max_version)
508 #ifdef OPENSSL_NO_TLS1_3
509 || (min_version <= TLS1_3_VERSION && TLS1_3_VERSION <= max_version)
517 static void clear_ciphers(SSL *s)
519 /* clear the current cipher */
520 ssl_clear_cipher_ctx(s);
521 ssl_clear_hash_ctx(&s->read_hash);
522 ssl_clear_hash_ctx(&s->write_hash);
525 int SSL_clear(SSL *s)
527 if (s->method == NULL) {
528 SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
532 if (ssl_clear_bad_session(s)) {
533 SSL_SESSION_free(s->session);
536 SSL_SESSION_free(s->psksession);
537 s->psksession = NULL;
538 OPENSSL_free(s->psksession_id);
539 s->psksession_id = NULL;
540 s->psksession_id_len = 0;
546 if (s->renegotiate) {
547 SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
551 ossl_statem_clear(s);
553 s->version = s->method->version;
554 s->client_version = s->version;
555 s->rwstate = SSL_NOTHING;
557 BUF_MEM_free(s->init_buf);
562 s->key_update = SSL_KEY_UPDATE_NONE;
564 /* Reset DANE verification result state */
567 X509_free(s->dane.mcert);
568 s->dane.mcert = NULL;
569 s->dane.mtlsa = NULL;
571 /* Clear the verification result peername */
572 X509_VERIFY_PARAM_move_peername(s->param, NULL);
575 * Check to see if we were changed into a different method, if so, revert
578 if (s->method != s->ctx->method) {
579 s->method->ssl_free(s);
580 s->method = s->ctx->method;
581 if (!s->method->ssl_new(s))
584 if (!s->method->ssl_clear(s))
588 RECORD_LAYER_clear(&s->rlayer);
593 /** Used to change an SSL_CTXs default SSL method type */
594 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
596 STACK_OF(SSL_CIPHER) *sk;
600 sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
601 &(ctx->cipher_list_by_id),
602 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
603 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
604 SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
610 SSL *SSL_new(SSL_CTX *ctx)
615 SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
618 if (ctx->method == NULL) {
619 SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
623 s = OPENSSL_zalloc(sizeof(*s));
627 s->lock = CRYPTO_THREAD_lock_new();
632 * If not using the standard RAND (say for fuzzing), then don't use a
635 if (RAND_get_rand_method() == RAND_OpenSSL()) {
637 RAND_DRBG_new(RAND_DRBG_NID, RAND_DRBG_FLAG_CTR_USE_DF,
638 RAND_DRBG_get0_global());
640 || RAND_DRBG_instantiate(s->drbg,
641 (const unsigned char *) SSL_version_str,
642 sizeof(SSL_version_str) - 1) == 0) {
643 CRYPTO_THREAD_lock_free(s->lock);
648 RECORD_LAYER_init(&s->rlayer, s);
650 s->options = ctx->options;
651 s->dane.flags = ctx->dane.flags;
652 s->min_proto_version = ctx->min_proto_version;
653 s->max_proto_version = ctx->max_proto_version;
655 s->max_cert_list = ctx->max_cert_list;
657 s->max_early_data = ctx->max_early_data;
660 * Earlier library versions used to copy the pointer to the CERT, not
661 * its contents; only when setting new parameters for the per-SSL
662 * copy, ssl_cert_new would be called (and the direct reference to
663 * the per-SSL_CTX settings would be lost, but those still were
664 * indirectly accessed for various purposes, and for that reason they
665 * used to be known as s->ctx->default_cert). Now we don't look at the
666 * SSL_CTX's CERT after having duplicated it once.
668 s->cert = ssl_cert_dup(ctx->cert);
672 RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
673 s->msg_callback = ctx->msg_callback;
674 s->msg_callback_arg = ctx->msg_callback_arg;
675 s->verify_mode = ctx->verify_mode;
676 s->not_resumable_session_cb = ctx->not_resumable_session_cb;
677 s->record_padding_cb = ctx->record_padding_cb;
678 s->record_padding_arg = ctx->record_padding_arg;
679 s->block_padding = ctx->block_padding;
680 s->sid_ctx_length = ctx->sid_ctx_length;
681 if (!ossl_assert(s->sid_ctx_length <= sizeof s->sid_ctx))
683 memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
684 s->verify_callback = ctx->default_verify_callback;
685 s->generate_session_id = ctx->generate_session_id;
687 s->param = X509_VERIFY_PARAM_new();
688 if (s->param == NULL)
690 X509_VERIFY_PARAM_inherit(s->param, ctx->param);
691 s->quiet_shutdown = ctx->quiet_shutdown;
692 s->max_send_fragment = ctx->max_send_fragment;
693 s->split_send_fragment = ctx->split_send_fragment;
694 s->max_pipelines = ctx->max_pipelines;
695 if (s->max_pipelines > 1)
696 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
697 if (ctx->default_read_buf_len > 0)
698 SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
703 s->ext.debug_arg = NULL;
704 s->ext.ticket_expected = 0;
705 s->ext.status_type = ctx->ext.status_type;
706 s->ext.status_expected = 0;
707 s->ext.ocsp.ids = NULL;
708 s->ext.ocsp.exts = NULL;
709 s->ext.ocsp.resp = NULL;
710 s->ext.ocsp.resp_len = 0;
712 s->session_ctx = ctx;
713 #ifndef OPENSSL_NO_EC
714 if (ctx->ext.ecpointformats) {
715 s->ext.ecpointformats =
716 OPENSSL_memdup(ctx->ext.ecpointformats,
717 ctx->ext.ecpointformats_len);
718 if (!s->ext.ecpointformats)
720 s->ext.ecpointformats_len =
721 ctx->ext.ecpointformats_len;
723 if (ctx->ext.supportedgroups) {
724 s->ext.supportedgroups =
725 OPENSSL_memdup(ctx->ext.supportedgroups,
726 ctx->ext.supportedgroups_len
727 * sizeof(*ctx->ext.supportedgroups));
728 if (!s->ext.supportedgroups)
730 s->ext.supportedgroups_len = ctx->ext.supportedgroups_len;
733 #ifndef OPENSSL_NO_NEXTPROTONEG
737 if (s->ctx->ext.alpn) {
738 s->ext.alpn = OPENSSL_malloc(s->ctx->ext.alpn_len);
739 if (s->ext.alpn == NULL)
741 memcpy(s->ext.alpn, s->ctx->ext.alpn, s->ctx->ext.alpn_len);
742 s->ext.alpn_len = s->ctx->ext.alpn_len;
745 s->verified_chain = NULL;
746 s->verify_result = X509_V_OK;
748 s->default_passwd_callback = ctx->default_passwd_callback;
749 s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
751 s->method = ctx->method;
753 s->key_update = SSL_KEY_UPDATE_NONE;
755 if (!s->method->ssl_new(s))
758 s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
763 if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data))
766 #ifndef OPENSSL_NO_PSK
767 s->psk_client_callback = ctx->psk_client_callback;
768 s->psk_server_callback = ctx->psk_server_callback;
770 s->psk_find_session_cb = ctx->psk_find_session_cb;
771 s->psk_use_session_cb = ctx->psk_use_session_cb;
775 #ifndef OPENSSL_NO_CT
776 if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
777 ctx->ct_validation_callback_arg))
784 SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
788 int SSL_is_dtls(const SSL *s)
790 return SSL_IS_DTLS(s) ? 1 : 0;
793 int SSL_up_ref(SSL *s)
797 if (CRYPTO_UP_REF(&s->references, &i, s->lock) <= 0)
800 REF_PRINT_COUNT("SSL", s);
801 REF_ASSERT_ISNT(i < 2);
802 return ((i > 1) ? 1 : 0);
805 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
806 unsigned int sid_ctx_len)
808 if (sid_ctx_len > sizeof ctx->sid_ctx) {
809 SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
810 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
813 ctx->sid_ctx_length = sid_ctx_len;
814 memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
819 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
820 unsigned int sid_ctx_len)
822 if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
823 SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
824 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
827 ssl->sid_ctx_length = sid_ctx_len;
828 memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
833 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
835 CRYPTO_THREAD_write_lock(ctx->lock);
836 ctx->generate_session_id = cb;
837 CRYPTO_THREAD_unlock(ctx->lock);
841 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
843 CRYPTO_THREAD_write_lock(ssl->lock);
844 ssl->generate_session_id = cb;
845 CRYPTO_THREAD_unlock(ssl->lock);
849 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
853 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
854 * we can "construct" a session to give us the desired check - i.e. to
855 * find if there's a session in the hash table that would conflict with
856 * any new session built out of this id/id_len and the ssl_version in use
861 if (id_len > sizeof r.session_id)
864 r.ssl_version = ssl->version;
865 r.session_id_length = id_len;
866 memcpy(r.session_id, id, id_len);
868 CRYPTO_THREAD_read_lock(ssl->session_ctx->lock);
869 p = lh_SSL_SESSION_retrieve(ssl->session_ctx->sessions, &r);
870 CRYPTO_THREAD_unlock(ssl->session_ctx->lock);
874 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
876 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
879 int SSL_set_purpose(SSL *s, int purpose)
881 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
884 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
886 return X509_VERIFY_PARAM_set_trust(s->param, trust);
889 int SSL_set_trust(SSL *s, int trust)
891 return X509_VERIFY_PARAM_set_trust(s->param, trust);
894 int SSL_set1_host(SSL *s, const char *hostname)
896 return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
899 int SSL_add1_host(SSL *s, const char *hostname)
901 return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
904 void SSL_set_hostflags(SSL *s, unsigned int flags)
906 X509_VERIFY_PARAM_set_hostflags(s->param, flags);
909 const char *SSL_get0_peername(SSL *s)
911 return X509_VERIFY_PARAM_get0_peername(s->param);
914 int SSL_CTX_dane_enable(SSL_CTX *ctx)
916 return dane_ctx_enable(&ctx->dane);
919 unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags)
921 unsigned long orig = ctx->dane.flags;
923 ctx->dane.flags |= flags;
927 unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags)
929 unsigned long orig = ctx->dane.flags;
931 ctx->dane.flags &= ~flags;
935 int SSL_dane_enable(SSL *s, const char *basedomain)
937 SSL_DANE *dane = &s->dane;
939 if (s->ctx->dane.mdmax == 0) {
940 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
943 if (dane->trecs != NULL) {
944 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
949 * Default SNI name. This rejects empty names, while set1_host below
950 * accepts them and disables host name checks. To avoid side-effects with
951 * invalid input, set the SNI name first.
953 if (s->ext.hostname == NULL) {
954 if (!SSL_set_tlsext_host_name(s, basedomain)) {
955 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
960 /* Primary RFC6125 reference identifier */
961 if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
962 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
968 dane->dctx = &s->ctx->dane;
969 dane->trecs = sk_danetls_record_new_null();
971 if (dane->trecs == NULL) {
972 SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
978 unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags)
980 unsigned long orig = ssl->dane.flags;
982 ssl->dane.flags |= flags;
986 unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags)
988 unsigned long orig = ssl->dane.flags;
990 ssl->dane.flags &= ~flags;
994 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
996 SSL_DANE *dane = &s->dane;
998 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1002 *mcert = dane->mcert;
1004 *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
1009 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
1010 uint8_t *mtype, unsigned const char **data, size_t *dlen)
1012 SSL_DANE *dane = &s->dane;
1014 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
1018 *usage = dane->mtlsa->usage;
1020 *selector = dane->mtlsa->selector;
1022 *mtype = dane->mtlsa->mtype;
1024 *data = dane->mtlsa->data;
1026 *dlen = dane->mtlsa->dlen;
1031 SSL_DANE *SSL_get0_dane(SSL *s)
1036 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
1037 uint8_t mtype, unsigned char *data, size_t dlen)
1039 return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
1042 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype,
1045 return dane_mtype_set(&ctx->dane, md, mtype, ord);
1048 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
1050 return X509_VERIFY_PARAM_set1(ctx->param, vpm);
1053 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
1055 return X509_VERIFY_PARAM_set1(ssl->param, vpm);
1058 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
1063 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
1068 void SSL_certs_clear(SSL *s)
1070 ssl_cert_clear_certs(s->cert);
1073 void SSL_free(SSL *s)
1080 CRYPTO_DOWN_REF(&s->references, &i, s->lock);
1081 REF_PRINT_COUNT("SSL", s);
1084 REF_ASSERT_ISNT(i < 0);
1086 X509_VERIFY_PARAM_free(s->param);
1087 dane_final(&s->dane);
1088 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
1090 /* Ignore return value */
1091 ssl_free_wbio_buffer(s);
1093 BIO_free_all(s->wbio);
1094 BIO_free_all(s->rbio);
1096 BUF_MEM_free(s->init_buf);
1098 /* add extra stuff */
1099 sk_SSL_CIPHER_free(s->cipher_list);
1100 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1102 /* Make the next call work :-) */
1103 if (s->session != NULL) {
1104 ssl_clear_bad_session(s);
1105 SSL_SESSION_free(s->session);
1107 SSL_SESSION_free(s->psksession);
1108 OPENSSL_free(s->psksession_id);
1112 ssl_cert_free(s->cert);
1113 /* Free up if allocated */
1115 OPENSSL_free(s->ext.hostname);
1116 SSL_CTX_free(s->session_ctx);
1117 #ifndef OPENSSL_NO_EC
1118 OPENSSL_free(s->ext.ecpointformats);
1119 OPENSSL_free(s->ext.supportedgroups);
1120 #endif /* OPENSSL_NO_EC */
1121 sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts, X509_EXTENSION_free);
1122 #ifndef OPENSSL_NO_OCSP
1123 sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
1125 #ifndef OPENSSL_NO_CT
1126 SCT_LIST_free(s->scts);
1127 OPENSSL_free(s->ext.scts);
1129 OPENSSL_free(s->ext.ocsp.resp);
1130 OPENSSL_free(s->ext.alpn);
1131 OPENSSL_free(s->ext.tls13_cookie);
1132 OPENSSL_free(s->clienthello);
1134 sk_X509_NAME_pop_free(s->ca_names, X509_NAME_free);
1136 sk_X509_pop_free(s->verified_chain, X509_free);
1138 if (s->method != NULL)
1139 s->method->ssl_free(s);
1141 RECORD_LAYER_release(&s->rlayer);
1143 SSL_CTX_free(s->ctx);
1145 ASYNC_WAIT_CTX_free(s->waitctx);
1147 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1148 OPENSSL_free(s->ext.npn);
1151 #ifndef OPENSSL_NO_SRTP
1152 sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1155 RAND_DRBG_free(s->drbg);
1156 CRYPTO_THREAD_lock_free(s->lock);
1161 void SSL_set0_rbio(SSL *s, BIO *rbio)
1163 BIO_free_all(s->rbio);
1167 void SSL_set0_wbio(SSL *s, BIO *wbio)
1170 * If the output buffering BIO is still in place, remove it
1172 if (s->bbio != NULL)
1173 s->wbio = BIO_pop(s->wbio);
1175 BIO_free_all(s->wbio);
1178 /* Re-attach |bbio| to the new |wbio|. */
1179 if (s->bbio != NULL)
1180 s->wbio = BIO_push(s->bbio, s->wbio);
1183 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1186 * For historical reasons, this function has many different cases in
1187 * ownership handling.
1190 /* If nothing has changed, do nothing */
1191 if (rbio == SSL_get_rbio(s) && wbio == SSL_get_wbio(s))
1195 * If the two arguments are equal then one fewer reference is granted by the
1196 * caller than we want to take
1198 if (rbio != NULL && rbio == wbio)
1202 * If only the wbio is changed only adopt one reference.
1204 if (rbio == SSL_get_rbio(s)) {
1205 SSL_set0_wbio(s, wbio);
1209 * There is an asymmetry here for historical reasons. If only the rbio is
1210 * changed AND the rbio and wbio were originally different, then we only
1211 * adopt one reference.
1213 if (wbio == SSL_get_wbio(s) && SSL_get_rbio(s) != SSL_get_wbio(s)) {
1214 SSL_set0_rbio(s, rbio);
1218 /* Otherwise, adopt both references. */
1219 SSL_set0_rbio(s, rbio);
1220 SSL_set0_wbio(s, wbio);
1223 BIO *SSL_get_rbio(const SSL *s)
1228 BIO *SSL_get_wbio(const SSL *s)
1230 if (s->bbio != NULL) {
1232 * If |bbio| is active, the true caller-configured BIO is its
1235 return BIO_next(s->bbio);
1240 int SSL_get_fd(const SSL *s)
1242 return SSL_get_rfd(s);
1245 int SSL_get_rfd(const SSL *s)
1250 b = SSL_get_rbio(s);
1251 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1253 BIO_get_fd(r, &ret);
1257 int SSL_get_wfd(const SSL *s)
1262 b = SSL_get_wbio(s);
1263 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1265 BIO_get_fd(r, &ret);
1269 #ifndef OPENSSL_NO_SOCK
1270 int SSL_set_fd(SSL *s, int fd)
1275 bio = BIO_new(BIO_s_socket());
1278 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1281 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1282 SSL_set_bio(s, bio, bio);
1288 int SSL_set_wfd(SSL *s, int fd)
1290 BIO *rbio = SSL_get_rbio(s);
1292 if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET
1293 || (int)BIO_get_fd(rbio, NULL) != fd) {
1294 BIO *bio = BIO_new(BIO_s_socket());
1297 SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1300 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1301 SSL_set0_wbio(s, bio);
1304 SSL_set0_wbio(s, rbio);
1309 int SSL_set_rfd(SSL *s, int fd)
1311 BIO *wbio = SSL_get_wbio(s);
1313 if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET
1314 || ((int)BIO_get_fd(wbio, NULL) != fd)) {
1315 BIO *bio = BIO_new(BIO_s_socket());
1318 SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1321 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1322 SSL_set0_rbio(s, bio);
1325 SSL_set0_rbio(s, wbio);
1332 /* return length of latest Finished message we sent, copy to 'buf' */
1333 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1337 if (s->s3 != NULL) {
1338 ret = s->s3->tmp.finish_md_len;
1341 memcpy(buf, s->s3->tmp.finish_md, count);
1346 /* return length of latest Finished message we expected, copy to 'buf' */
1347 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1351 if (s->s3 != NULL) {
1352 ret = s->s3->tmp.peer_finish_md_len;
1355 memcpy(buf, s->s3->tmp.peer_finish_md, count);
1360 int SSL_get_verify_mode(const SSL *s)
1362 return s->verify_mode;
1365 int SSL_get_verify_depth(const SSL *s)
1367 return X509_VERIFY_PARAM_get_depth(s->param);
1370 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1371 return s->verify_callback;
1374 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1376 return ctx->verify_mode;
1379 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1381 return X509_VERIFY_PARAM_get_depth(ctx->param);
1384 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1385 return ctx->default_verify_callback;
1388 void SSL_set_verify(SSL *s, int mode,
1389 int (*callback) (int ok, X509_STORE_CTX *ctx))
1391 s->verify_mode = mode;
1392 if (callback != NULL)
1393 s->verify_callback = callback;
1396 void SSL_set_verify_depth(SSL *s, int depth)
1398 X509_VERIFY_PARAM_set_depth(s->param, depth);
1401 void SSL_set_read_ahead(SSL *s, int yes)
1403 RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1406 int SSL_get_read_ahead(const SSL *s)
1408 return RECORD_LAYER_get_read_ahead(&s->rlayer);
1411 int SSL_pending(const SSL *s)
1413 size_t pending = s->method->ssl_pending(s);
1416 * SSL_pending cannot work properly if read-ahead is enabled
1417 * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1418 * impossible to fix since SSL_pending cannot report errors that may be
1419 * observed while scanning the new data. (Note that SSL_pending() is
1420 * often used as a boolean value, so we'd better not return -1.)
1422 * SSL_pending also cannot work properly if the value >INT_MAX. In that case
1423 * we just return INT_MAX.
1425 return pending < INT_MAX ? (int)pending : INT_MAX;
1428 int SSL_has_pending(const SSL *s)
1431 * Similar to SSL_pending() but returns a 1 to indicate that we have
1432 * unprocessed data available or 0 otherwise (as opposed to the number of
1433 * bytes available). Unlike SSL_pending() this will take into account
1434 * read_ahead data. A 1 return simply indicates that we have unprocessed
1435 * data. That data may not result in any application data, or we may fail
1436 * to parse the records for some reason.
1438 if (RECORD_LAYER_processed_read_pending(&s->rlayer))
1441 return RECORD_LAYER_read_pending(&s->rlayer);
1444 X509 *SSL_get_peer_certificate(const SSL *s)
1448 if ((s == NULL) || (s->session == NULL))
1451 r = s->session->peer;
1461 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1465 if ((s == NULL) || (s->session == NULL))
1468 r = s->session->peer_chain;
1471 * If we are a client, cert_chain includes the peer's own certificate; if
1472 * we are a server, it does not.
1479 * Now in theory, since the calling process own 't' it should be safe to
1480 * modify. We need to be able to read f without being hassled
1482 int SSL_copy_session_id(SSL *t, const SSL *f)
1485 /* Do we need to to SSL locking? */
1486 if (!SSL_set_session(t, SSL_get_session(f))) {
1491 * what if we are setup for one protocol version but want to talk another
1493 if (t->method != f->method) {
1494 t->method->ssl_free(t);
1495 t->method = f->method;
1496 if (t->method->ssl_new(t) == 0)
1500 CRYPTO_UP_REF(&f->cert->references, &i, f->cert->lock);
1501 ssl_cert_free(t->cert);
1503 if (!SSL_set_session_id_context(t, f->sid_ctx, (int)f->sid_ctx_length)) {
1510 /* Fix this so it checks all the valid key/cert options */
1511 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1513 if ((ctx == NULL) || (ctx->cert->key->x509 == NULL)) {
1514 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1517 if (ctx->cert->key->privatekey == NULL) {
1518 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1521 return X509_check_private_key
1522 (ctx->cert->key->x509, ctx->cert->key->privatekey);
1525 /* Fix this function so that it takes an optional type parameter */
1526 int SSL_check_private_key(const SSL *ssl)
1529 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1532 if (ssl->cert->key->x509 == NULL) {
1533 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1536 if (ssl->cert->key->privatekey == NULL) {
1537 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1540 return X509_check_private_key(ssl->cert->key->x509,
1541 ssl->cert->key->privatekey);
1544 int SSL_waiting_for_async(SSL *s)
1552 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1554 ASYNC_WAIT_CTX *ctx = s->waitctx;
1558 return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1561 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1562 OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1564 ASYNC_WAIT_CTX *ctx = s->waitctx;
1568 return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1572 int SSL_accept(SSL *s)
1574 if (s->handshake_func == NULL) {
1575 /* Not properly initialized yet */
1576 SSL_set_accept_state(s);
1579 return SSL_do_handshake(s);
1582 int SSL_connect(SSL *s)
1584 if (s->handshake_func == NULL) {
1585 /* Not properly initialized yet */
1586 SSL_set_connect_state(s);
1589 return SSL_do_handshake(s);
1592 long SSL_get_default_timeout(const SSL *s)
1594 return s->method->get_timeout();
1597 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1598 int (*func) (void *))
1601 if (s->waitctx == NULL) {
1602 s->waitctx = ASYNC_WAIT_CTX_new();
1603 if (s->waitctx == NULL)
1606 switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1607 sizeof(struct ssl_async_args))) {
1609 s->rwstate = SSL_NOTHING;
1610 SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1613 s->rwstate = SSL_ASYNC_PAUSED;
1616 s->rwstate = SSL_ASYNC_NO_JOBS;
1622 s->rwstate = SSL_NOTHING;
1623 SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1624 /* Shouldn't happen */
1629 static int ssl_io_intern(void *vargs)
1631 struct ssl_async_args *args;
1636 args = (struct ssl_async_args *)vargs;
1640 switch (args->type) {
1642 return args->f.func_read(s, buf, num, &s->asyncrw);
1644 return args->f.func_write(s, buf, num, &s->asyncrw);
1646 return args->f.func_other(s);
1651 int ssl_read_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1653 if (s->handshake_func == NULL) {
1654 SSLerr(SSL_F_SSL_READ_INTERNAL, SSL_R_UNINITIALIZED);
1658 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1659 s->rwstate = SSL_NOTHING;
1663 if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1664 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY) {
1665 SSLerr(SSL_F_SSL_READ_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1669 * If we are a client and haven't received the ServerHello etc then we
1672 ossl_statem_check_finish_init(s, 0);
1674 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1675 struct ssl_async_args args;
1681 args.type = READFUNC;
1682 args.f.func_read = s->method->ssl_read;
1684 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1685 *readbytes = s->asyncrw;
1688 return s->method->ssl_read(s, buf, num, readbytes);
1692 int SSL_read(SSL *s, void *buf, int num)
1698 SSLerr(SSL_F_SSL_READ, SSL_R_BAD_LENGTH);
1702 ret = ssl_read_internal(s, buf, (size_t)num, &readbytes);
1705 * The cast is safe here because ret should be <= INT_MAX because num is
1709 ret = (int)readbytes;
1714 int SSL_read_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1716 int ret = ssl_read_internal(s, buf, num, readbytes);
1723 int SSL_read_early_data(SSL *s, void *buf, size_t num, size_t *readbytes)
1728 SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1729 return SSL_READ_EARLY_DATA_ERROR;
1732 switch (s->early_data_state) {
1733 case SSL_EARLY_DATA_NONE:
1734 if (!SSL_in_before(s)) {
1735 SSLerr(SSL_F_SSL_READ_EARLY_DATA,
1736 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1737 return SSL_READ_EARLY_DATA_ERROR;
1741 case SSL_EARLY_DATA_ACCEPT_RETRY:
1742 s->early_data_state = SSL_EARLY_DATA_ACCEPTING;
1743 ret = SSL_accept(s);
1746 s->early_data_state = SSL_EARLY_DATA_ACCEPT_RETRY;
1747 return SSL_READ_EARLY_DATA_ERROR;
1751 case SSL_EARLY_DATA_READ_RETRY:
1752 if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
1753 s->early_data_state = SSL_EARLY_DATA_READING;
1754 ret = SSL_read_ex(s, buf, num, readbytes);
1756 * State machine will update early_data_state to
1757 * SSL_EARLY_DATA_FINISHED_READING if we get an EndOfEarlyData
1760 if (ret > 0 || (ret <= 0 && s->early_data_state
1761 != SSL_EARLY_DATA_FINISHED_READING)) {
1762 s->early_data_state = SSL_EARLY_DATA_READ_RETRY;
1763 return ret > 0 ? SSL_READ_EARLY_DATA_SUCCESS
1764 : SSL_READ_EARLY_DATA_ERROR;
1767 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
1770 return SSL_READ_EARLY_DATA_FINISH;
1773 SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1774 return SSL_READ_EARLY_DATA_ERROR;
1778 int SSL_get_early_data_status(const SSL *s)
1780 return s->ext.early_data;
1783 static int ssl_peek_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1785 if (s->handshake_func == NULL) {
1786 SSLerr(SSL_F_SSL_PEEK_INTERNAL, SSL_R_UNINITIALIZED);
1790 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1793 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1794 struct ssl_async_args args;
1800 args.type = READFUNC;
1801 args.f.func_read = s->method->ssl_peek;
1803 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1804 *readbytes = s->asyncrw;
1807 return s->method->ssl_peek(s, buf, num, readbytes);
1811 int SSL_peek(SSL *s, void *buf, int num)
1817 SSLerr(SSL_F_SSL_PEEK, SSL_R_BAD_LENGTH);
1821 ret = ssl_peek_internal(s, buf, (size_t)num, &readbytes);
1824 * The cast is safe here because ret should be <= INT_MAX because num is
1828 ret = (int)readbytes;
1834 int SSL_peek_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1836 int ret = ssl_peek_internal(s, buf, num, readbytes);
1843 int ssl_write_internal(SSL *s, const void *buf, size_t num, size_t *written)
1845 if (s->handshake_func == NULL) {
1846 SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_UNINITIALIZED);
1850 if (s->shutdown & SSL_SENT_SHUTDOWN) {
1851 s->rwstate = SSL_NOTHING;
1852 SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_PROTOCOL_IS_SHUTDOWN);
1856 if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1857 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY
1858 || s->early_data_state == SSL_EARLY_DATA_READ_RETRY) {
1859 SSLerr(SSL_F_SSL_WRITE_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1862 /* If we are a client and haven't sent the Finished we better do that */
1863 ossl_statem_check_finish_init(s, 1);
1865 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1867 struct ssl_async_args args;
1870 args.buf = (void *)buf;
1872 args.type = WRITEFUNC;
1873 args.f.func_write = s->method->ssl_write;
1875 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1876 *written = s->asyncrw;
1879 return s->method->ssl_write(s, buf, num, written);
1883 int SSL_write(SSL *s, const void *buf, int num)
1889 SSLerr(SSL_F_SSL_WRITE, SSL_R_BAD_LENGTH);
1893 ret = ssl_write_internal(s, buf, (size_t)num, &written);
1896 * The cast is safe here because ret should be <= INT_MAX because num is
1905 int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
1907 int ret = ssl_write_internal(s, buf, num, written);
1914 int SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
1916 int ret, early_data_state;
1918 switch (s->early_data_state) {
1919 case SSL_EARLY_DATA_NONE:
1921 || !SSL_in_before(s)
1922 || ((s->session == NULL || s->session->ext.max_early_data == 0)
1923 && (s->psk_use_session_cb == NULL))) {
1924 SSLerr(SSL_F_SSL_WRITE_EARLY_DATA,
1925 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1930 case SSL_EARLY_DATA_CONNECT_RETRY:
1931 s->early_data_state = SSL_EARLY_DATA_CONNECTING;
1932 ret = SSL_connect(s);
1935 s->early_data_state = SSL_EARLY_DATA_CONNECT_RETRY;
1940 case SSL_EARLY_DATA_WRITE_RETRY:
1941 s->early_data_state = SSL_EARLY_DATA_WRITING;
1942 ret = SSL_write_ex(s, buf, num, written);
1943 s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
1946 case SSL_EARLY_DATA_FINISHED_READING:
1947 case SSL_EARLY_DATA_READ_RETRY:
1948 early_data_state = s->early_data_state;
1949 /* We are a server writing to an unauthenticated client */
1950 s->early_data_state = SSL_EARLY_DATA_UNAUTH_WRITING;
1951 ret = SSL_write_ex(s, buf, num, written);
1952 s->early_data_state = early_data_state;
1956 SSLerr(SSL_F_SSL_WRITE_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1961 int SSL_shutdown(SSL *s)
1964 * Note that this function behaves differently from what one might
1965 * expect. Return values are 0 for no success (yet), 1 for success; but
1966 * calling it once is usually not enough, even if blocking I/O is used
1967 * (see ssl3_shutdown).
1970 if (s->handshake_func == NULL) {
1971 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1975 if (!SSL_in_init(s)) {
1976 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1977 struct ssl_async_args args;
1980 args.type = OTHERFUNC;
1981 args.f.func_other = s->method->ssl_shutdown;
1983 return ssl_start_async_job(s, &args, ssl_io_intern);
1985 return s->method->ssl_shutdown(s);
1988 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
1993 int SSL_key_update(SSL *s, int updatetype)
1996 * TODO(TLS1.3): How will applications know whether TLSv1.3 has been
1997 * negotiated, and that it is appropriate to call SSL_key_update() instead
1998 * of SSL_renegotiate().
2000 if (!SSL_IS_TLS13(s)) {
2001 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_WRONG_SSL_VERSION);
2005 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
2006 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
2007 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_INVALID_KEY_UPDATE_TYPE);
2011 if (!SSL_is_init_finished(s)) {
2012 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_STILL_IN_INIT);
2016 ossl_statem_set_in_init(s, 1);
2017 s->key_update = updatetype;
2021 int SSL_get_key_update_type(SSL *s)
2023 return s->key_update;
2026 int SSL_renegotiate(SSL *s)
2028 if (SSL_IS_TLS13(s)) {
2029 SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_WRONG_SSL_VERSION);
2033 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
2034 SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_NO_RENEGOTIATION);
2041 return s->method->ssl_renegotiate(s);
2044 int SSL_renegotiate_abbreviated(SSL *s)
2046 if (SSL_IS_TLS13(s)) {
2047 SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_WRONG_SSL_VERSION);
2051 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
2052 SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_NO_RENEGOTIATION);
2059 return s->method->ssl_renegotiate(s);
2062 int SSL_renegotiate_pending(SSL *s)
2065 * becomes true when negotiation is requested; false again once a
2066 * handshake has finished
2068 return (s->renegotiate != 0);
2071 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
2076 case SSL_CTRL_GET_READ_AHEAD:
2077 return RECORD_LAYER_get_read_ahead(&s->rlayer);
2078 case SSL_CTRL_SET_READ_AHEAD:
2079 l = RECORD_LAYER_get_read_ahead(&s->rlayer);
2080 RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
2083 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2084 s->msg_callback_arg = parg;
2088 return (s->mode |= larg);
2089 case SSL_CTRL_CLEAR_MODE:
2090 return (s->mode &= ~larg);
2091 case SSL_CTRL_GET_MAX_CERT_LIST:
2092 return (long)s->max_cert_list;
2093 case SSL_CTRL_SET_MAX_CERT_LIST:
2096 l = (long)s->max_cert_list;
2097 s->max_cert_list = (size_t)larg;
2099 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2100 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2102 s->max_send_fragment = larg;
2103 if (s->max_send_fragment < s->split_send_fragment)
2104 s->split_send_fragment = s->max_send_fragment;
2106 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2107 if ((size_t)larg > s->max_send_fragment || larg == 0)
2109 s->split_send_fragment = larg;
2111 case SSL_CTRL_SET_MAX_PIPELINES:
2112 if (larg < 1 || larg > SSL_MAX_PIPELINES)
2114 s->max_pipelines = larg;
2116 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
2118 case SSL_CTRL_GET_RI_SUPPORT:
2120 return s->s3->send_connection_binding;
2123 case SSL_CTRL_CERT_FLAGS:
2124 return (s->cert->cert_flags |= larg);
2125 case SSL_CTRL_CLEAR_CERT_FLAGS:
2126 return (s->cert->cert_flags &= ~larg);
2128 case SSL_CTRL_GET_RAW_CIPHERLIST:
2130 if (s->s3->tmp.ciphers_raw == NULL)
2132 *(unsigned char **)parg = s->s3->tmp.ciphers_raw;
2133 return (int)s->s3->tmp.ciphers_rawlen;
2135 return TLS_CIPHER_LEN;
2137 case SSL_CTRL_GET_EXTMS_SUPPORT:
2138 if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
2140 if (s->session->flags & SSL_SESS_FLAG_EXTMS)
2144 case SSL_CTRL_SET_MIN_PROTO_VERSION:
2145 return ssl_check_allowed_versions(larg, s->max_proto_version)
2146 && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2147 &s->min_proto_version);
2148 case SSL_CTRL_GET_MIN_PROTO_VERSION:
2149 return s->min_proto_version;
2150 case SSL_CTRL_SET_MAX_PROTO_VERSION:
2151 return ssl_check_allowed_versions(s->min_proto_version, larg)
2152 && ssl_set_version_bound(s->ctx->method->version, (int)larg,
2153 &s->max_proto_version);
2154 case SSL_CTRL_GET_MAX_PROTO_VERSION:
2155 return s->max_proto_version;
2157 return s->method->ssl_ctrl(s, cmd, larg, parg);
2161 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
2164 case SSL_CTRL_SET_MSG_CALLBACK:
2165 s->msg_callback = (void (*)
2166 (int write_p, int version, int content_type,
2167 const void *buf, size_t len, SSL *ssl,
2172 return s->method->ssl_callback_ctrl(s, cmd, fp);
2176 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
2178 return ctx->sessions;
2181 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
2184 /* For some cases with ctx == NULL perform syntax checks */
2187 #ifndef OPENSSL_NO_EC
2188 case SSL_CTRL_SET_GROUPS_LIST:
2189 return tls1_set_groups_list(NULL, NULL, parg);
2191 case SSL_CTRL_SET_SIGALGS_LIST:
2192 case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
2193 return tls1_set_sigalgs_list(NULL, parg, 0);
2200 case SSL_CTRL_GET_READ_AHEAD:
2201 return ctx->read_ahead;
2202 case SSL_CTRL_SET_READ_AHEAD:
2203 l = ctx->read_ahead;
2204 ctx->read_ahead = larg;
2207 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2208 ctx->msg_callback_arg = parg;
2211 case SSL_CTRL_GET_MAX_CERT_LIST:
2212 return (long)ctx->max_cert_list;
2213 case SSL_CTRL_SET_MAX_CERT_LIST:
2216 l = (long)ctx->max_cert_list;
2217 ctx->max_cert_list = (size_t)larg;
2220 case SSL_CTRL_SET_SESS_CACHE_SIZE:
2223 l = (long)ctx->session_cache_size;
2224 ctx->session_cache_size = (size_t)larg;
2226 case SSL_CTRL_GET_SESS_CACHE_SIZE:
2227 return (long)ctx->session_cache_size;
2228 case SSL_CTRL_SET_SESS_CACHE_MODE:
2229 l = ctx->session_cache_mode;
2230 ctx->session_cache_mode = larg;
2232 case SSL_CTRL_GET_SESS_CACHE_MODE:
2233 return ctx->session_cache_mode;
2235 case SSL_CTRL_SESS_NUMBER:
2236 return lh_SSL_SESSION_num_items(ctx->sessions);
2237 case SSL_CTRL_SESS_CONNECT:
2238 return ctx->stats.sess_connect;
2239 case SSL_CTRL_SESS_CONNECT_GOOD:
2240 return ctx->stats.sess_connect_good;
2241 case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
2242 return ctx->stats.sess_connect_renegotiate;
2243 case SSL_CTRL_SESS_ACCEPT:
2244 return ctx->stats.sess_accept;
2245 case SSL_CTRL_SESS_ACCEPT_GOOD:
2246 return ctx->stats.sess_accept_good;
2247 case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
2248 return ctx->stats.sess_accept_renegotiate;
2249 case SSL_CTRL_SESS_HIT:
2250 return ctx->stats.sess_hit;
2251 case SSL_CTRL_SESS_CB_HIT:
2252 return ctx->stats.sess_cb_hit;
2253 case SSL_CTRL_SESS_MISSES:
2254 return ctx->stats.sess_miss;
2255 case SSL_CTRL_SESS_TIMEOUTS:
2256 return ctx->stats.sess_timeout;
2257 case SSL_CTRL_SESS_CACHE_FULL:
2258 return ctx->stats.sess_cache_full;
2260 return (ctx->mode |= larg);
2261 case SSL_CTRL_CLEAR_MODE:
2262 return (ctx->mode &= ~larg);
2263 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2264 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2266 ctx->max_send_fragment = larg;
2267 if (ctx->max_send_fragment < ctx->split_send_fragment)
2268 ctx->split_send_fragment = ctx->max_send_fragment;
2270 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2271 if ((size_t)larg > ctx->max_send_fragment || larg == 0)
2273 ctx->split_send_fragment = larg;
2275 case SSL_CTRL_SET_MAX_PIPELINES:
2276 if (larg < 1 || larg > SSL_MAX_PIPELINES)
2278 ctx->max_pipelines = larg;
2280 case SSL_CTRL_CERT_FLAGS:
2281 return (ctx->cert->cert_flags |= larg);
2282 case SSL_CTRL_CLEAR_CERT_FLAGS:
2283 return (ctx->cert->cert_flags &= ~larg);
2284 case SSL_CTRL_SET_MIN_PROTO_VERSION:
2285 return ssl_check_allowed_versions(larg, ctx->max_proto_version)
2286 && ssl_set_version_bound(ctx->method->version, (int)larg,
2287 &ctx->min_proto_version);
2288 case SSL_CTRL_GET_MIN_PROTO_VERSION:
2289 return ctx->min_proto_version;
2290 case SSL_CTRL_SET_MAX_PROTO_VERSION:
2291 return ssl_check_allowed_versions(ctx->min_proto_version, larg)
2292 && ssl_set_version_bound(ctx->method->version, (int)larg,
2293 &ctx->max_proto_version);
2294 case SSL_CTRL_GET_MAX_PROTO_VERSION:
2295 return ctx->max_proto_version;
2297 return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
2301 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
2304 case SSL_CTRL_SET_MSG_CALLBACK:
2305 ctx->msg_callback = (void (*)
2306 (int write_p, int version, int content_type,
2307 const void *buf, size_t len, SSL *ssl,
2312 return ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp);
2316 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
2325 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
2326 const SSL_CIPHER *const *bp)
2328 if ((*ap)->id > (*bp)->id)
2330 if ((*ap)->id < (*bp)->id)
2335 /** return a STACK of the ciphers available for the SSL and in order of
2337 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
2340 if (s->cipher_list != NULL) {
2341 return s->cipher_list;
2342 } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
2343 return s->ctx->cipher_list;
2349 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
2351 if ((s == NULL) || (s->session == NULL) || !s->server)
2353 return s->session->ciphers;
2356 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
2358 STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
2360 ciphers = SSL_get_ciphers(s);
2363 ssl_set_client_disabled(s);
2364 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2365 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
2366 if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
2368 sk = sk_SSL_CIPHER_new_null();
2371 if (!sk_SSL_CIPHER_push(sk, c)) {
2372 sk_SSL_CIPHER_free(sk);
2380 /** return a STACK of the ciphers available for the SSL and in order of
2382 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
2385 if (s->cipher_list_by_id != NULL) {
2386 return s->cipher_list_by_id;
2387 } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
2388 return s->ctx->cipher_list_by_id;
2394 /** The old interface to get the same thing as SSL_get_ciphers() */
2395 const char *SSL_get_cipher_list(const SSL *s, int n)
2397 const SSL_CIPHER *c;
2398 STACK_OF(SSL_CIPHER) *sk;
2402 sk = SSL_get_ciphers(s);
2403 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2405 c = sk_SSL_CIPHER_value(sk, n);
2411 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2413 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2416 return ctx->cipher_list;
2420 /** specify the ciphers to be used by default by the SSL_CTX */
2421 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2423 STACK_OF(SSL_CIPHER) *sk;
2425 sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
2426 &ctx->cipher_list_by_id, str, ctx->cert);
2428 * ssl_create_cipher_list may return an empty stack if it was unable to
2429 * find a cipher matching the given rule string (for example if the rule
2430 * string specifies a cipher which has been disabled). This is not an
2431 * error as far as ssl_create_cipher_list is concerned, and hence
2432 * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2436 else if (sk_SSL_CIPHER_num(sk) == 0) {
2437 SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2443 /** specify the ciphers to be used by the SSL */
2444 int SSL_set_cipher_list(SSL *s, const char *str)
2446 STACK_OF(SSL_CIPHER) *sk;
2448 sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
2449 &s->cipher_list_by_id, str, s->cert);
2450 /* see comment in SSL_CTX_set_cipher_list */
2453 else if (sk_SSL_CIPHER_num(sk) == 0) {
2454 SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2460 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
2463 STACK_OF(SSL_CIPHER) *sk;
2464 const SSL_CIPHER *c;
2467 if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
2471 sk = s->session->ciphers;
2473 if (sk_SSL_CIPHER_num(sk) == 0)
2476 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2479 c = sk_SSL_CIPHER_value(sk, i);
2480 n = strlen(c->name);
2496 /** return a servername extension value if provided in Client Hello, or NULL.
2497 * So far, only host_name types are defined (RFC 3546).
2500 const char *SSL_get_servername(const SSL *s, const int type)
2502 if (type != TLSEXT_NAMETYPE_host_name)
2505 return s->session && !s->ext.hostname ?
2506 s->session->ext.hostname : s->ext.hostname;
2509 int SSL_get_servername_type(const SSL *s)
2512 && (!s->ext.hostname ? s->session->
2513 ext.hostname : s->ext.hostname))
2514 return TLSEXT_NAMETYPE_host_name;
2519 * SSL_select_next_proto implements the standard protocol selection. It is
2520 * expected that this function is called from the callback set by
2521 * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2522 * vector of 8-bit, length prefixed byte strings. The length byte itself is
2523 * not included in the length. A byte string of length 0 is invalid. No byte
2524 * string may be truncated. The current, but experimental algorithm for
2525 * selecting the protocol is: 1) If the server doesn't support NPN then this
2526 * is indicated to the callback. In this case, the client application has to
2527 * abort the connection or have a default application level protocol. 2) If
2528 * the server supports NPN, but advertises an empty list then the client
2529 * selects the first protocol in its list, but indicates via the API that this
2530 * fallback case was enacted. 3) Otherwise, the client finds the first
2531 * protocol in the server's list that it supports and selects this protocol.
2532 * This is because it's assumed that the server has better information about
2533 * which protocol a client should use. 4) If the client doesn't support any
2534 * of the server's advertised protocols, then this is treated the same as
2535 * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2536 * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2538 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2539 const unsigned char *server,
2540 unsigned int server_len,
2541 const unsigned char *client, unsigned int client_len)
2544 const unsigned char *result;
2545 int status = OPENSSL_NPN_UNSUPPORTED;
2548 * For each protocol in server preference order, see if we support it.
2550 for (i = 0; i < server_len;) {
2551 for (j = 0; j < client_len;) {
2552 if (server[i] == client[j] &&
2553 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2554 /* We found a match */
2555 result = &server[i];
2556 status = OPENSSL_NPN_NEGOTIATED;
2566 /* There's no overlap between our protocols and the server's list. */
2568 status = OPENSSL_NPN_NO_OVERLAP;
2571 *out = (unsigned char *)result + 1;
2572 *outlen = result[0];
2576 #ifndef OPENSSL_NO_NEXTPROTONEG
2578 * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2579 * client's requested protocol for this connection and returns 0. If the
2580 * client didn't request any protocol, then *data is set to NULL. Note that
2581 * the client can request any protocol it chooses. The value returned from
2582 * this function need not be a member of the list of supported protocols
2583 * provided by the callback.
2585 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2592 *len = (unsigned int)s->ext.npn_len;
2597 * SSL_CTX_set_npn_advertised_cb sets a callback that is called when
2598 * a TLS server needs a list of supported protocols for Next Protocol
2599 * Negotiation. The returned list must be in wire format. The list is
2600 * returned by setting |out| to point to it and |outlen| to its length. This
2601 * memory will not be modified, but one should assume that the SSL* keeps a
2602 * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2603 * wishes to advertise. Otherwise, no such extension will be included in the
2606 void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
2607 SSL_CTX_npn_advertised_cb_func cb,
2610 ctx->ext.npn_advertised_cb = cb;
2611 ctx->ext.npn_advertised_cb_arg = arg;
2615 * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2616 * client needs to select a protocol from the server's provided list. |out|
2617 * must be set to point to the selected protocol (which may be within |in|).
2618 * The length of the protocol name must be written into |outlen|. The
2619 * server's advertised protocols are provided in |in| and |inlen|. The
2620 * callback can assume that |in| is syntactically valid. The client must
2621 * select a protocol. It is fatal to the connection if this callback returns
2622 * a value other than SSL_TLSEXT_ERR_OK.
2624 void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
2625 SSL_CTX_npn_select_cb_func cb,
2628 ctx->ext.npn_select_cb = cb;
2629 ctx->ext.npn_select_cb_arg = arg;
2634 * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2635 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2636 * length-prefixed strings). Returns 0 on success.
2638 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2639 unsigned int protos_len)
2641 OPENSSL_free(ctx->ext.alpn);
2642 ctx->ext.alpn = OPENSSL_memdup(protos, protos_len);
2643 if (ctx->ext.alpn == NULL) {
2644 SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2647 ctx->ext.alpn_len = protos_len;
2653 * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2654 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2655 * length-prefixed strings). Returns 0 on success.
2657 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2658 unsigned int protos_len)
2660 OPENSSL_free(ssl->ext.alpn);
2661 ssl->ext.alpn = OPENSSL_memdup(protos, protos_len);
2662 if (ssl->ext.alpn == NULL) {
2663 SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2666 ssl->ext.alpn_len = protos_len;
2672 * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2673 * called during ClientHello processing in order to select an ALPN protocol
2674 * from the client's list of offered protocols.
2676 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2677 SSL_CTX_alpn_select_cb_func cb,
2680 ctx->ext.alpn_select_cb = cb;
2681 ctx->ext.alpn_select_cb_arg = arg;
2685 * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
2686 * On return it sets |*data| to point to |*len| bytes of protocol name
2687 * (not including the leading length-prefix byte). If the server didn't
2688 * respond with a negotiated protocol then |*len| will be zero.
2690 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
2695 *data = ssl->s3->alpn_selected;
2699 *len = (unsigned int)ssl->s3->alpn_selected_len;
2702 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2703 const char *label, size_t llen,
2704 const unsigned char *context, size_t contextlen,
2707 if (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER)
2710 return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
2712 contextlen, use_context);
2715 static unsigned long ssl_session_hash(const SSL_SESSION *a)
2717 const unsigned char *session_id = a->session_id;
2719 unsigned char tmp_storage[4];
2721 if (a->session_id_length < sizeof(tmp_storage)) {
2722 memset(tmp_storage, 0, sizeof(tmp_storage));
2723 memcpy(tmp_storage, a->session_id, a->session_id_length);
2724 session_id = tmp_storage;
2728 ((unsigned long)session_id[0]) |
2729 ((unsigned long)session_id[1] << 8L) |
2730 ((unsigned long)session_id[2] << 16L) |
2731 ((unsigned long)session_id[3] << 24L);
2736 * NB: If this function (or indeed the hash function which uses a sort of
2737 * coarser function than this one) is changed, ensure
2738 * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
2739 * being able to construct an SSL_SESSION that will collide with any existing
2740 * session with a matching session ID.
2742 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
2744 if (a->ssl_version != b->ssl_version)
2746 if (a->session_id_length != b->session_id_length)
2748 return memcmp(a->session_id, b->session_id, a->session_id_length);
2752 * These wrapper functions should remain rather than redeclaring
2753 * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
2754 * variable. The reason is that the functions aren't static, they're exposed
2758 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
2760 SSL_CTX *ret = NULL;
2763 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
2767 if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
2770 if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
2771 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
2774 ret = OPENSSL_zalloc(sizeof(*ret));
2779 ret->min_proto_version = 0;
2780 ret->max_proto_version = 0;
2781 ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
2782 ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
2783 /* We take the system default. */
2784 ret->session_timeout = meth->get_timeout();
2785 ret->references = 1;
2786 ret->lock = CRYPTO_THREAD_lock_new();
2787 if (ret->lock == NULL) {
2788 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2792 ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
2793 ret->verify_mode = SSL_VERIFY_NONE;
2794 if ((ret->cert = ssl_cert_new()) == NULL)
2797 ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2798 if (ret->sessions == NULL)
2800 ret->cert_store = X509_STORE_new();
2801 if (ret->cert_store == NULL)
2803 #ifndef OPENSSL_NO_CT
2804 ret->ctlog_store = CTLOG_STORE_new();
2805 if (ret->ctlog_store == NULL)
2808 if (!ssl_create_cipher_list(ret->method,
2809 &ret->cipher_list, &ret->cipher_list_by_id,
2810 SSL_DEFAULT_CIPHER_LIST, ret->cert)
2811 || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2812 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2816 ret->param = X509_VERIFY_PARAM_new();
2817 if (ret->param == NULL)
2820 if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
2821 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
2824 if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
2825 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
2829 if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL)
2832 if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data))
2835 /* No compression for DTLS */
2836 if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
2837 ret->comp_methods = SSL_COMP_get_compression_methods();
2839 ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2840 ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2842 /* Setup RFC5077 ticket keys */
2843 if ((RAND_bytes(ret->ext.tick_key_name,
2844 sizeof(ret->ext.tick_key_name)) <= 0)
2845 || (RAND_bytes(ret->ext.tick_hmac_key,
2846 sizeof(ret->ext.tick_hmac_key)) <= 0)
2847 || (RAND_bytes(ret->ext.tick_aes_key,
2848 sizeof(ret->ext.tick_aes_key)) <= 0))
2849 ret->options |= SSL_OP_NO_TICKET;
2851 #ifndef OPENSSL_NO_SRP
2852 if (!SSL_CTX_SRP_CTX_init(ret))
2855 #ifndef OPENSSL_NO_ENGINE
2856 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2857 # define eng_strx(x) #x
2858 # define eng_str(x) eng_strx(x)
2859 /* Use specific client engine automatically... ignore errors */
2862 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2865 ENGINE_load_builtin_engines();
2866 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2868 if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2874 * Default is to connect to non-RI servers. When RI is more widely
2875 * deployed might change this.
2877 ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2879 * Disable compression by default to prevent CRIME. Applications can
2880 * re-enable compression by configuring
2881 * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
2882 * or by using the SSL_CONF library.
2884 ret->options |= SSL_OP_NO_COMPRESSION;
2886 ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
2889 * Default max early data is a fully loaded single record. Could be split
2890 * across multiple records in practice
2892 ret->max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
2896 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2902 int SSL_CTX_up_ref(SSL_CTX *ctx)
2906 if (CRYPTO_UP_REF(&ctx->references, &i, ctx->lock) <= 0)
2909 REF_PRINT_COUNT("SSL_CTX", ctx);
2910 REF_ASSERT_ISNT(i < 2);
2911 return ((i > 1) ? 1 : 0);
2914 void SSL_CTX_free(SSL_CTX *a)
2921 CRYPTO_DOWN_REF(&a->references, &i, a->lock);
2922 REF_PRINT_COUNT("SSL_CTX", a);
2925 REF_ASSERT_ISNT(i < 0);
2927 X509_VERIFY_PARAM_free(a->param);
2928 dane_ctx_final(&a->dane);
2931 * Free internal session cache. However: the remove_cb() may reference
2932 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2933 * after the sessions were flushed.
2934 * As the ex_data handling routines might also touch the session cache,
2935 * the most secure solution seems to be: empty (flush) the cache, then
2936 * free ex_data, then finally free the cache.
2937 * (See ticket [openssl.org #212].)
2939 if (a->sessions != NULL)
2940 SSL_CTX_flush_sessions(a, 0);
2942 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2943 lh_SSL_SESSION_free(a->sessions);
2944 X509_STORE_free(a->cert_store);
2945 #ifndef OPENSSL_NO_CT
2946 CTLOG_STORE_free(a->ctlog_store);
2948 sk_SSL_CIPHER_free(a->cipher_list);
2949 sk_SSL_CIPHER_free(a->cipher_list_by_id);
2950 ssl_cert_free(a->cert);
2951 sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
2952 sk_X509_pop_free(a->extra_certs, X509_free);
2953 a->comp_methods = NULL;
2954 #ifndef OPENSSL_NO_SRTP
2955 sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2957 #ifndef OPENSSL_NO_SRP
2958 SSL_CTX_SRP_CTX_free(a);
2960 #ifndef OPENSSL_NO_ENGINE
2961 ENGINE_finish(a->client_cert_engine);
2964 #ifndef OPENSSL_NO_EC
2965 OPENSSL_free(a->ext.ecpointformats);
2966 OPENSSL_free(a->ext.supportedgroups);
2968 OPENSSL_free(a->ext.alpn);
2970 CRYPTO_THREAD_lock_free(a->lock);
2975 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2977 ctx->default_passwd_callback = cb;
2980 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2982 ctx->default_passwd_callback_userdata = u;
2985 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2987 return ctx->default_passwd_callback;
2990 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2992 return ctx->default_passwd_callback_userdata;
2995 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
2997 s->default_passwd_callback = cb;
3000 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
3002 s->default_passwd_callback_userdata = u;
3005 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
3007 return s->default_passwd_callback;
3010 void *SSL_get_default_passwd_cb_userdata(SSL *s)
3012 return s->default_passwd_callback_userdata;
3015 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
3016 int (*cb) (X509_STORE_CTX *, void *),
3019 ctx->app_verify_callback = cb;
3020 ctx->app_verify_arg = arg;
3023 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
3024 int (*cb) (int, X509_STORE_CTX *))
3026 ctx->verify_mode = mode;
3027 ctx->default_verify_callback = cb;
3030 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
3032 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
3035 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
3037 ssl_cert_set_cert_cb(c->cert, cb, arg);
3040 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
3042 ssl_cert_set_cert_cb(s->cert, cb, arg);
3045 void ssl_set_masks(SSL *s)
3048 uint32_t *pvalid = s->s3->tmp.valid_flags;
3049 int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
3050 unsigned long mask_k, mask_a;
3051 #ifndef OPENSSL_NO_EC
3052 int have_ecc_cert, ecdsa_ok;
3057 #ifndef OPENSSL_NO_DH
3058 dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
3063 rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
3064 rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
3065 dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
3066 #ifndef OPENSSL_NO_EC
3067 have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
3073 fprintf(stderr, "dht=%d re=%d rs=%d ds=%d\n",
3074 dh_tmp, rsa_enc, rsa_sign, dsa_sign);
3077 #ifndef OPENSSL_NO_GOST
3078 if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
3079 mask_k |= SSL_kGOST;
3080 mask_a |= SSL_aGOST12;
3082 if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
3083 mask_k |= SSL_kGOST;
3084 mask_a |= SSL_aGOST12;
3086 if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
3087 mask_k |= SSL_kGOST;
3088 mask_a |= SSL_aGOST01;
3099 * If we only have an RSA-PSS certificate allow RSA authentication
3100 * if TLS 1.2 and peer supports it.
3103 if (rsa_enc || rsa_sign || (ssl_has_cert(s, SSL_PKEY_RSA_PSS_SIGN)
3104 && pvalid[SSL_PKEY_RSA_PSS_SIGN] & CERT_PKEY_EXPLICIT_SIGN
3105 && TLS1_get_version(s) == TLS1_2_VERSION))
3112 mask_a |= SSL_aNULL;
3115 * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
3116 * depending on the key usage extension.
3118 #ifndef OPENSSL_NO_EC
3119 if (have_ecc_cert) {
3121 ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
3122 ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
3123 if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
3126 mask_a |= SSL_aECDSA;
3128 /* Allow Ed25519 for TLS 1.2 if peer supports it */
3129 if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
3130 && pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
3131 && TLS1_get_version(s) == TLS1_2_VERSION)
3132 mask_a |= SSL_aECDSA;
3135 #ifndef OPENSSL_NO_EC
3136 mask_k |= SSL_kECDHE;
3139 #ifndef OPENSSL_NO_PSK
3142 if (mask_k & SSL_kRSA)
3143 mask_k |= SSL_kRSAPSK;
3144 if (mask_k & SSL_kDHE)
3145 mask_k |= SSL_kDHEPSK;
3146 if (mask_k & SSL_kECDHE)
3147 mask_k |= SSL_kECDHEPSK;
3150 s->s3->tmp.mask_k = mask_k;
3151 s->s3->tmp.mask_a = mask_a;
3154 #ifndef OPENSSL_NO_EC
3156 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
3158 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
3159 /* key usage, if present, must allow signing */
3160 if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
3161 SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
3162 SSL_R_ECC_CERT_NOT_FOR_SIGNING);
3166 return 1; /* all checks are ok */
3171 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
3172 size_t *serverinfo_length)
3174 CERT_PKEY *cpk = s->s3->tmp.cert;
3175 *serverinfo_length = 0;
3177 if (cpk == NULL || cpk->serverinfo == NULL)
3180 *serverinfo = cpk->serverinfo;
3181 *serverinfo_length = cpk->serverinfo_length;
3185 void ssl_update_cache(SSL *s, int mode)
3190 * If the session_id_length is 0, we are not supposed to cache it, and it
3191 * would be rather hard to do anyway :-)
3193 if (s->session->session_id_length == 0)
3196 i = s->session_ctx->session_cache_mode;
3198 && (!s->hit || SSL_IS_TLS13(s))
3199 && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) != 0
3200 || SSL_CTX_add_session(s->session_ctx, s->session))
3201 && s->session_ctx->new_session_cb != NULL) {
3202 SSL_SESSION_up_ref(s->session);
3203 if (!s->session_ctx->new_session_cb(s, s->session))
3204 SSL_SESSION_free(s->session);
3207 /* auto flush every 255 connections */
3208 if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
3209 if ((((mode & SSL_SESS_CACHE_CLIENT)
3210 ? s->session_ctx->stats.sess_connect_good
3211 : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
3212 SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
3217 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
3222 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
3227 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
3231 if (s->method != meth) {
3232 const SSL_METHOD *sm = s->method;
3233 int (*hf) (SSL *) = s->handshake_func;
3235 if (sm->version == meth->version)
3240 ret = s->method->ssl_new(s);
3243 if (hf == sm->ssl_connect)
3244 s->handshake_func = meth->ssl_connect;
3245 else if (hf == sm->ssl_accept)
3246 s->handshake_func = meth->ssl_accept;
3251 int SSL_get_error(const SSL *s, int i)
3258 return SSL_ERROR_NONE;
3261 * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
3262 * where we do encode the error
3264 if ((l = ERR_peek_error()) != 0) {
3265 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
3266 return SSL_ERROR_SYSCALL;
3268 return SSL_ERROR_SSL;
3271 if (SSL_want_read(s)) {
3272 bio = SSL_get_rbio(s);
3273 if (BIO_should_read(bio))
3274 return SSL_ERROR_WANT_READ;
3275 else if (BIO_should_write(bio))
3277 * This one doesn't make too much sense ... We never try to write
3278 * to the rbio, and an application program where rbio and wbio
3279 * are separate couldn't even know what it should wait for.
3280 * However if we ever set s->rwstate incorrectly (so that we have
3281 * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
3282 * wbio *are* the same, this test works around that bug; so it
3283 * might be safer to keep it.
3285 return SSL_ERROR_WANT_WRITE;
3286 else if (BIO_should_io_special(bio)) {
3287 reason = BIO_get_retry_reason(bio);
3288 if (reason == BIO_RR_CONNECT)
3289 return SSL_ERROR_WANT_CONNECT;
3290 else if (reason == BIO_RR_ACCEPT)
3291 return SSL_ERROR_WANT_ACCEPT;
3293 return SSL_ERROR_SYSCALL; /* unknown */
3297 if (SSL_want_write(s)) {
3298 /* Access wbio directly - in order to use the buffered bio if present */
3300 if (BIO_should_write(bio))
3301 return SSL_ERROR_WANT_WRITE;
3302 else if (BIO_should_read(bio))
3304 * See above (SSL_want_read(s) with BIO_should_write(bio))
3306 return SSL_ERROR_WANT_READ;
3307 else if (BIO_should_io_special(bio)) {
3308 reason = BIO_get_retry_reason(bio);
3309 if (reason == BIO_RR_CONNECT)
3310 return SSL_ERROR_WANT_CONNECT;
3311 else if (reason == BIO_RR_ACCEPT)
3312 return SSL_ERROR_WANT_ACCEPT;
3314 return SSL_ERROR_SYSCALL;
3317 if (SSL_want_x509_lookup(s))
3318 return SSL_ERROR_WANT_X509_LOOKUP;
3319 if (SSL_want_async(s))
3320 return SSL_ERROR_WANT_ASYNC;
3321 if (SSL_want_async_job(s))
3322 return SSL_ERROR_WANT_ASYNC_JOB;
3323 if (SSL_want_client_hello_cb(s))
3324 return SSL_ERROR_WANT_CLIENT_HELLO_CB;
3326 if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
3327 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
3328 return SSL_ERROR_ZERO_RETURN;
3330 return SSL_ERROR_SYSCALL;
3333 static int ssl_do_handshake_intern(void *vargs)
3335 struct ssl_async_args *args;
3338 args = (struct ssl_async_args *)vargs;
3341 return s->handshake_func(s);
3344 int SSL_do_handshake(SSL *s)
3348 if (s->handshake_func == NULL) {
3349 SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3353 ossl_statem_check_finish_init(s, -1);
3355 s->method->ssl_renegotiate_check(s, 0);
3357 if (SSL_is_server(s)) {
3358 /* clear SNI settings at server-side */
3359 OPENSSL_free(s->ext.hostname);
3360 s->ext.hostname = NULL;
3363 if (SSL_in_init(s) || SSL_in_before(s)) {
3364 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3365 struct ssl_async_args args;
3369 ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3371 ret = s->handshake_func(s);
3377 void SSL_set_accept_state(SSL *s)
3381 ossl_statem_clear(s);
3382 s->handshake_func = s->method->ssl_accept;
3386 void SSL_set_connect_state(SSL *s)
3390 ossl_statem_clear(s);
3391 s->handshake_func = s->method->ssl_connect;
3395 int ssl_undefined_function(SSL *s)
3397 SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3401 int ssl_undefined_void_function(void)
3403 SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3404 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3408 int ssl_undefined_const_function(const SSL *s)
3413 const SSL_METHOD *ssl_bad_method(int ver)
3415 SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3419 const char *ssl_protocol_to_string(int version)
3423 case TLS1_3_VERSION:
3426 case TLS1_2_VERSION:
3429 case TLS1_1_VERSION:
3444 case DTLS1_2_VERSION:
3452 const char *SSL_get_version(const SSL *s)
3454 return ssl_protocol_to_string(s->version);
3457 SSL *SSL_dup(SSL *s)
3459 STACK_OF(X509_NAME) *sk;
3464 /* If we're not quiescent, just up_ref! */
3465 if (!SSL_in_init(s) || !SSL_in_before(s)) {
3466 CRYPTO_UP_REF(&s->references, &i, s->lock);
3471 * Otherwise, copy configuration state, and session if set.
3473 if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3476 if (s->session != NULL) {
3478 * Arranges to share the same session via up_ref. This "copies"
3479 * session-id, SSL_METHOD, sid_ctx, and 'cert'
3481 if (!SSL_copy_session_id(ret, s))
3485 * No session has been established yet, so we have to expect that
3486 * s->cert or ret->cert will be changed later -- they should not both
3487 * point to the same object, and thus we can't use
3488 * SSL_copy_session_id.
3490 if (!SSL_set_ssl_method(ret, s->method))
3493 if (s->cert != NULL) {
3494 ssl_cert_free(ret->cert);
3495 ret->cert = ssl_cert_dup(s->cert);
3496 if (ret->cert == NULL)
3500 if (!SSL_set_session_id_context(ret, s->sid_ctx,
3501 (int)s->sid_ctx_length))
3505 if (!ssl_dane_dup(ret, s))
3507 ret->version = s->version;
3508 ret->options = s->options;
3509 ret->mode = s->mode;
3510 SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3511 SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3512 ret->msg_callback = s->msg_callback;
3513 ret->msg_callback_arg = s->msg_callback_arg;
3514 SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3515 SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
3516 ret->generate_session_id = s->generate_session_id;
3518 SSL_set_info_callback(ret, SSL_get_info_callback(s));
3520 /* copy app data, a little dangerous perhaps */
3521 if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
3524 /* setup rbio, and wbio */
3525 if (s->rbio != NULL) {
3526 if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
3529 if (s->wbio != NULL) {
3530 if (s->wbio != s->rbio) {
3531 if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
3534 BIO_up_ref(ret->rbio);
3535 ret->wbio = ret->rbio;
3539 ret->server = s->server;
3540 if (s->handshake_func) {
3542 SSL_set_accept_state(ret);
3544 SSL_set_connect_state(ret);
3546 ret->shutdown = s->shutdown;
3549 ret->default_passwd_callback = s->default_passwd_callback;
3550 ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
3552 X509_VERIFY_PARAM_inherit(ret->param, s->param);
3554 /* dup the cipher_list and cipher_list_by_id stacks */
3555 if (s->cipher_list != NULL) {
3556 if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
3559 if (s->cipher_list_by_id != NULL)
3560 if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
3564 /* Dup the client_CA list */
3565 if (s->ca_names != NULL) {
3566 if ((sk = sk_X509_NAME_dup(s->ca_names)) == NULL)
3569 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
3570 xn = sk_X509_NAME_value(sk, i);
3571 if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
3584 void ssl_clear_cipher_ctx(SSL *s)
3586 if (s->enc_read_ctx != NULL) {
3587 EVP_CIPHER_CTX_free(s->enc_read_ctx);
3588 s->enc_read_ctx = NULL;
3590 if (s->enc_write_ctx != NULL) {
3591 EVP_CIPHER_CTX_free(s->enc_write_ctx);
3592 s->enc_write_ctx = NULL;
3594 #ifndef OPENSSL_NO_COMP
3595 COMP_CTX_free(s->expand);
3597 COMP_CTX_free(s->compress);
3602 X509 *SSL_get_certificate(const SSL *s)
3604 if (s->cert != NULL)
3605 return s->cert->key->x509;
3610 EVP_PKEY *SSL_get_privatekey(const SSL *s)
3612 if (s->cert != NULL)
3613 return s->cert->key->privatekey;
3618 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3620 if (ctx->cert != NULL)
3621 return ctx->cert->key->x509;
3626 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3628 if (ctx->cert != NULL)
3629 return ctx->cert->key->privatekey;
3634 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
3636 if ((s->session != NULL) && (s->session->cipher != NULL))
3637 return s->session->cipher;
3641 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s)
3643 return s->s3->tmp.new_cipher;
3646 const COMP_METHOD *SSL_get_current_compression(SSL *s)
3648 #ifndef OPENSSL_NO_COMP
3649 return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
3655 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
3657 #ifndef OPENSSL_NO_COMP
3658 return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
3664 int ssl_init_wbio_buffer(SSL *s)
3668 if (s->bbio != NULL) {
3669 /* Already buffered. */
3673 bbio = BIO_new(BIO_f_buffer());
3674 if (bbio == NULL || !BIO_set_read_buffer_size(bbio, 1)) {
3676 SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
3680 s->wbio = BIO_push(bbio, s->wbio);
3685 int ssl_free_wbio_buffer(SSL *s)
3687 /* callers ensure s is never null */
3688 if (s->bbio == NULL)
3691 s->wbio = BIO_pop(s->wbio);
3692 if (!ossl_assert(s->wbio != NULL))
3700 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3702 ctx->quiet_shutdown = mode;
3705 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3707 return ctx->quiet_shutdown;
3710 void SSL_set_quiet_shutdown(SSL *s, int mode)
3712 s->quiet_shutdown = mode;
3715 int SSL_get_quiet_shutdown(const SSL *s)
3717 return s->quiet_shutdown;
3720 void SSL_set_shutdown(SSL *s, int mode)
3725 int SSL_get_shutdown(const SSL *s)
3730 int SSL_version(const SSL *s)
3735 int SSL_client_version(const SSL *s)
3737 return s->client_version;
3740 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3745 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3748 if (ssl->ctx == ctx)
3751 ctx = ssl->session_ctx;
3752 new_cert = ssl_cert_dup(ctx->cert);
3753 if (new_cert == NULL) {
3757 if (!custom_exts_copy_flags(&new_cert->custext, &ssl->cert->custext)) {
3758 ssl_cert_free(new_cert);
3762 ssl_cert_free(ssl->cert);
3763 ssl->cert = new_cert;
3766 * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3767 * so setter APIs must prevent invalid lengths from entering the system.
3769 if (!ossl_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx)))
3773 * If the session ID context matches that of the parent SSL_CTX,
3774 * inherit it from the new SSL_CTX as well. If however the context does
3775 * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3776 * leave it unchanged.
3778 if ((ssl->ctx != NULL) &&
3779 (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3780 (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3781 ssl->sid_ctx_length = ctx->sid_ctx_length;
3782 memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3785 SSL_CTX_up_ref(ctx);
3786 SSL_CTX_free(ssl->ctx); /* decrement reference count */
3792 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3794 return X509_STORE_set_default_paths(ctx->cert_store);
3797 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
3799 X509_LOOKUP *lookup;
3801 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
3804 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
3806 /* Clear any errors if the default directory does not exist */
3812 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
3814 X509_LOOKUP *lookup;
3816 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
3820 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
3822 /* Clear any errors if the default file does not exist */
3828 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3831 return X509_STORE_load_locations(ctx->cert_store, CAfile, CApath);
3834 void SSL_set_info_callback(SSL *ssl,
3835 void (*cb) (const SSL *ssl, int type, int val))
3837 ssl->info_callback = cb;
3841 * One compiler (Diab DCC) doesn't like argument names in returned function
3844 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3847 return ssl->info_callback;
3850 void SSL_set_verify_result(SSL *ssl, long arg)
3852 ssl->verify_result = arg;
3855 long SSL_get_verify_result(const SSL *ssl)
3857 return ssl->verify_result;
3860 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
3863 return sizeof(ssl->s3->client_random);
3864 if (outlen > sizeof(ssl->s3->client_random))
3865 outlen = sizeof(ssl->s3->client_random);
3866 memcpy(out, ssl->s3->client_random, outlen);
3870 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
3873 return sizeof(ssl->s3->server_random);
3874 if (outlen > sizeof(ssl->s3->server_random))
3875 outlen = sizeof(ssl->s3->server_random);
3876 memcpy(out, ssl->s3->server_random, outlen);
3880 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
3881 unsigned char *out, size_t outlen)
3884 return session->master_key_length;
3885 if (outlen > session->master_key_length)
3886 outlen = session->master_key_length;
3887 memcpy(out, session->master_key, outlen);
3891 int SSL_SESSION_set1_master_key(SSL_SESSION *sess, const unsigned char *in,
3894 if (len > sizeof(sess->master_key))
3897 memcpy(sess->master_key, in, len);
3898 sess->master_key_length = len;
3903 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3905 return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
3908 void *SSL_get_ex_data(const SSL *s, int idx)
3910 return CRYPTO_get_ex_data(&s->ex_data, idx);
3913 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3915 return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
3918 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3920 return CRYPTO_get_ex_data(&s->ex_data, idx);
3923 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3925 return ctx->cert_store;
3928 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3930 X509_STORE_free(ctx->cert_store);
3931 ctx->cert_store = store;
3934 void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
3937 X509_STORE_up_ref(store);
3938 SSL_CTX_set_cert_store(ctx, store);
3941 int SSL_want(const SSL *s)
3947 * \brief Set the callback for generating temporary DH keys.
3948 * \param ctx the SSL context.
3949 * \param dh the callback
3952 #ifndef OPENSSL_NO_DH
3953 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3954 DH *(*dh) (SSL *ssl, int is_export,
3957 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3960 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3963 SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3967 #ifndef OPENSSL_NO_PSK
3968 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3970 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3971 SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3974 OPENSSL_free(ctx->cert->psk_identity_hint);
3975 if (identity_hint != NULL) {
3976 ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3977 if (ctx->cert->psk_identity_hint == NULL)
3980 ctx->cert->psk_identity_hint = NULL;
3984 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3989 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3990 SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3993 OPENSSL_free(s->cert->psk_identity_hint);
3994 if (identity_hint != NULL) {
3995 s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3996 if (s->cert->psk_identity_hint == NULL)
3999 s->cert->psk_identity_hint = NULL;
4003 const char *SSL_get_psk_identity_hint(const SSL *s)
4005 if (s == NULL || s->session == NULL)
4007 return s->session->psk_identity_hint;
4010 const char *SSL_get_psk_identity(const SSL *s)
4012 if (s == NULL || s->session == NULL)
4014 return s->session->psk_identity;
4017 void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
4019 s->psk_client_callback = cb;
4022 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
4024 ctx->psk_client_callback = cb;
4027 void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
4029 s->psk_server_callback = cb;
4032 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
4034 ctx->psk_server_callback = cb;
4038 void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb)
4040 s->psk_find_session_cb = cb;
4043 void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
4044 SSL_psk_find_session_cb_func cb)
4046 ctx->psk_find_session_cb = cb;
4049 void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
4051 s->psk_use_session_cb = cb;
4054 void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
4055 SSL_psk_use_session_cb_func cb)
4057 ctx->psk_use_session_cb = cb;
4060 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
4061 void (*cb) (int write_p, int version,
4062 int content_type, const void *buf,
4063 size_t len, SSL *ssl, void *arg))
4065 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
4068 void SSL_set_msg_callback(SSL *ssl,
4069 void (*cb) (int write_p, int version,
4070 int content_type, const void *buf,
4071 size_t len, SSL *ssl, void *arg))
4073 SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
4076 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
4077 int (*cb) (SSL *ssl,
4081 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
4082 (void (*)(void))cb);
4085 void SSL_set_not_resumable_session_callback(SSL *ssl,
4086 int (*cb) (SSL *ssl,
4087 int is_forward_secure))
4089 SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
4090 (void (*)(void))cb);
4093 void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
4094 size_t (*cb) (SSL *ssl, int type,
4095 size_t len, void *arg))
4097 ctx->record_padding_cb = cb;
4100 void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
4102 ctx->record_padding_arg = arg;
4105 void *SSL_CTX_get_record_padding_callback_arg(SSL_CTX *ctx)
4107 return ctx->record_padding_arg;
4110 int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
4112 /* block size of 0 or 1 is basically no padding */
4113 if (block_size == 1)
4114 ctx->block_padding = 0;
4115 else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
4116 ctx->block_padding = block_size;
4122 void SSL_set_record_padding_callback(SSL *ssl,
4123 size_t (*cb) (SSL *ssl, int type,
4124 size_t len, void *arg))
4126 ssl->record_padding_cb = cb;
4129 void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
4131 ssl->record_padding_arg = arg;
4134 void *SSL_get_record_padding_callback_arg(SSL *ssl)
4136 return ssl->record_padding_arg;
4139 int SSL_set_block_padding(SSL *ssl, size_t block_size)
4141 /* block size of 0 or 1 is basically no padding */
4142 if (block_size == 1)
4143 ssl->block_padding = 0;
4144 else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
4145 ssl->block_padding = block_size;
4152 * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
4153 * variable, freeing EVP_MD_CTX previously stored in that variable, if any.
4154 * If EVP_MD pointer is passed, initializes ctx with this |md|.
4155 * Returns the newly allocated ctx;
4158 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
4160 ssl_clear_hash_ctx(hash);
4161 *hash = EVP_MD_CTX_new();
4162 if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
4163 EVP_MD_CTX_free(*hash);
4170 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
4173 EVP_MD_CTX_free(*hash);
4177 /* Retrieve handshake hashes */
4178 int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
4181 EVP_MD_CTX *ctx = NULL;
4182 EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
4183 int hashleni = EVP_MD_CTX_size(hdgst);
4186 if (hashleni < 0 || (size_t)hashleni > outlen)
4189 ctx = EVP_MD_CTX_new();
4193 if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
4194 || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
4197 *hashlen = hashleni;
4201 EVP_MD_CTX_free(ctx);
4205 int SSL_session_reused(SSL *s)
4210 int SSL_is_server(const SSL *s)
4215 #if OPENSSL_API_COMPAT < 0x10100000L
4216 void SSL_set_debug(SSL *s, int debug)
4218 /* Old function was do-nothing anyway... */
4224 void SSL_set_security_level(SSL *s, int level)
4226 s->cert->sec_level = level;
4229 int SSL_get_security_level(const SSL *s)
4231 return s->cert->sec_level;
4234 void SSL_set_security_callback(SSL *s,
4235 int (*cb) (const SSL *s, const SSL_CTX *ctx,
4236 int op, int bits, int nid,
4237 void *other, void *ex))
4239 s->cert->sec_cb = cb;
4242 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
4243 const SSL_CTX *ctx, int op,
4244 int bits, int nid, void *other,
4246 return s->cert->sec_cb;
4249 void SSL_set0_security_ex_data(SSL *s, void *ex)
4251 s->cert->sec_ex = ex;
4254 void *SSL_get0_security_ex_data(const SSL *s)
4256 return s->cert->sec_ex;
4259 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
4261 ctx->cert->sec_level = level;
4264 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
4266 return ctx->cert->sec_level;
4269 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
4270 int (*cb) (const SSL *s, const SSL_CTX *ctx,
4271 int op, int bits, int nid,
4272 void *other, void *ex))
4274 ctx->cert->sec_cb = cb;
4277 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
4283 return ctx->cert->sec_cb;
4286 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
4288 ctx->cert->sec_ex = ex;
4291 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
4293 return ctx->cert->sec_ex;
4297 * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
4298 * can return unsigned long, instead of the generic long return value from the
4299 * control interface.
4301 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
4303 return ctx->options;
4306 unsigned long SSL_get_options(const SSL *s)
4311 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
4313 return ctx->options |= op;
4316 unsigned long SSL_set_options(SSL *s, unsigned long op)
4318 return s->options |= op;
4321 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
4323 return ctx->options &= ~op;
4326 unsigned long SSL_clear_options(SSL *s, unsigned long op)
4328 return s->options &= ~op;
4331 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
4333 return s->verified_chain;
4336 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
4338 #ifndef OPENSSL_NO_CT
4341 * Moves SCTs from the |src| stack to the |dst| stack.
4342 * The source of each SCT will be set to |origin|.
4343 * If |dst| points to a NULL pointer, a new stack will be created and owned by
4345 * Returns the number of SCTs moved, or a negative integer if an error occurs.
4347 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
4348 sct_source_t origin)
4354 *dst = sk_SCT_new_null();
4356 SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
4361 while ((sct = sk_SCT_pop(src)) != NULL) {
4362 if (SCT_set_source(sct, origin) != 1)
4365 if (sk_SCT_push(*dst, sct) <= 0)
4373 sk_SCT_push(src, sct); /* Put the SCT back */
4378 * Look for data collected during ServerHello and parse if found.
4379 * Returns the number of SCTs extracted.
4381 static int ct_extract_tls_extension_scts(SSL *s)
4383 int scts_extracted = 0;
4385 if (s->ext.scts != NULL) {
4386 const unsigned char *p = s->ext.scts;
4387 STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
4389 scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
4391 SCT_LIST_free(scts);
4394 return scts_extracted;
4398 * Checks for an OCSP response and then attempts to extract any SCTs found if it
4399 * contains an SCT X509 extension. They will be stored in |s->scts|.
4401 * - The number of SCTs extracted, assuming an OCSP response exists.
4402 * - 0 if no OCSP response exists or it contains no SCTs.
4403 * - A negative integer if an error occurs.
4405 static int ct_extract_ocsp_response_scts(SSL *s)
4407 # ifndef OPENSSL_NO_OCSP
4408 int scts_extracted = 0;
4409 const unsigned char *p;
4410 OCSP_BASICRESP *br = NULL;
4411 OCSP_RESPONSE *rsp = NULL;
4412 STACK_OF(SCT) *scts = NULL;
4415 if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
4418 p = s->ext.ocsp.resp;
4419 rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
4423 br = OCSP_response_get1_basic(rsp);
4427 for (i = 0; i < OCSP_resp_count(br); ++i) {
4428 OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
4434 OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
4436 ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
4437 if (scts_extracted < 0)
4441 SCT_LIST_free(scts);
4442 OCSP_BASICRESP_free(br);
4443 OCSP_RESPONSE_free(rsp);
4444 return scts_extracted;
4446 /* Behave as if no OCSP response exists */
4452 * Attempts to extract SCTs from the peer certificate.
4453 * Return the number of SCTs extracted, or a negative integer if an error
4456 static int ct_extract_x509v3_extension_scts(SSL *s)
4458 int scts_extracted = 0;
4459 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4462 STACK_OF(SCT) *scts =
4463 X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
4466 ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
4468 SCT_LIST_free(scts);
4471 return scts_extracted;
4475 * Attempts to find all received SCTs by checking TLS extensions, the OCSP
4476 * response (if it exists) and X509v3 extensions in the certificate.
4477 * Returns NULL if an error occurs.
4479 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
4481 if (!s->scts_parsed) {
4482 if (ct_extract_tls_extension_scts(s) < 0 ||
4483 ct_extract_ocsp_response_scts(s) < 0 ||
4484 ct_extract_x509v3_extension_scts(s) < 0)
4494 static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
4495 const STACK_OF(SCT) *scts, void *unused_arg)
4500 static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
4501 const STACK_OF(SCT) *scts, void *unused_arg)
4503 int count = scts != NULL ? sk_SCT_num(scts) : 0;
4506 for (i = 0; i < count; ++i) {
4507 SCT *sct = sk_SCT_value(scts, i);
4508 int status = SCT_get_validation_status(sct);
4510 if (status == SCT_VALIDATION_STATUS_VALID)
4513 SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
4517 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
4521 * Since code exists that uses the custom extension handler for CT, look
4522 * for this and throw an error if they have already registered to use CT.
4524 if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
4525 TLSEXT_TYPE_signed_certificate_timestamp))
4527 SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
4528 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4532 if (callback != NULL) {
4534 * If we are validating CT, then we MUST accept SCTs served via OCSP
4536 if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
4540 s->ct_validation_callback = callback;
4541 s->ct_validation_callback_arg = arg;
4546 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
4547 ssl_ct_validation_cb callback, void *arg)
4550 * Since code exists that uses the custom extension handler for CT, look for
4551 * this and throw an error if they have already registered to use CT.
4553 if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
4554 TLSEXT_TYPE_signed_certificate_timestamp))
4556 SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
4557 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4561 ctx->ct_validation_callback = callback;
4562 ctx->ct_validation_callback_arg = arg;
4566 int SSL_ct_is_enabled(const SSL *s)
4568 return s->ct_validation_callback != NULL;
4571 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
4573 return ctx->ct_validation_callback != NULL;
4576 int ssl_validate_ct(SSL *s)
4579 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4581 SSL_DANE *dane = &s->dane;
4582 CT_POLICY_EVAL_CTX *ctx = NULL;
4583 const STACK_OF(SCT) *scts;
4586 * If no callback is set, the peer is anonymous, or its chain is invalid,
4587 * skip SCT validation - just return success. Applications that continue
4588 * handshakes without certificates, with unverified chains, or pinned leaf
4589 * certificates are outside the scope of the WebPKI and CT.
4591 * The above exclusions notwithstanding the vast majority of peers will
4592 * have rather ordinary certificate chains validated by typical
4593 * applications that perform certificate verification and therefore will
4594 * process SCTs when enabled.
4596 if (s->ct_validation_callback == NULL || cert == NULL ||
4597 s->verify_result != X509_V_OK ||
4598 s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
4602 * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
4603 * trust-anchors. See https://tools.ietf.org/html/rfc7671#section-4.2
4605 if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
4606 switch (dane->mtlsa->usage) {
4607 case DANETLS_USAGE_DANE_TA:
4608 case DANETLS_USAGE_DANE_EE:
4613 ctx = CT_POLICY_EVAL_CTX_new();
4615 SSLerr(SSL_F_SSL_VALIDATE_CT, ERR_R_MALLOC_FAILURE);
4619 issuer = sk_X509_value(s->verified_chain, 1);
4620 CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
4621 CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
4622 CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx, s->ctx->ctlog_store);
4623 CT_POLICY_EVAL_CTX_set_time(
4624 ctx, (uint64_t)SSL_SESSION_get_time(SSL_get0_session(s)) * 1000);
4626 scts = SSL_get0_peer_scts(s);
4629 * This function returns success (> 0) only when all the SCTs are valid, 0
4630 * when some are invalid, and < 0 on various internal errors (out of
4631 * memory, etc.). Having some, or even all, invalid SCTs is not sufficient
4632 * reason to abort the handshake, that decision is up to the callback.
4633 * Therefore, we error out only in the unexpected case that the return
4634 * value is negative.
4636 * XXX: One might well argue that the return value of this function is an
4637 * unfortunate design choice. Its job is only to determine the validation
4638 * status of each of the provided SCTs. So long as it correctly separates
4639 * the wheat from the chaff it should return success. Failure in this case
4640 * ought to correspond to an inability to carry out its duties.
4642 if (SCT_LIST_validate(scts, ctx) < 0) {
4643 SSLerr(SSL_F_SSL_VALIDATE_CT, SSL_R_SCT_VERIFICATION_FAILED);
4647 ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
4649 ret = 0; /* This function returns 0 on failure */
4652 CT_POLICY_EVAL_CTX_free(ctx);