2 * ! \file ssl/ssl_lib.c \brief Version independent SSL functions.
4 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
7 * This package is an SSL implementation written
8 * by Eric Young (eay@cryptsoft.com).
9 * The implementation was written so as to conform with Netscapes SSL.
11 * This library is free for commercial and non-commercial use as long as
12 * the following conditions are aheared to. The following conditions
13 * apply to all code found in this distribution, be it the RC4, RSA,
14 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
15 * included with this distribution is covered by the same copyright terms
16 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
18 * Copyright remains Eric Young's, and as such any Copyright notices in
19 * the code are not to be removed.
20 * If this package is used in a product, Eric Young should be given attribution
21 * as the author of the parts of the library used.
22 * This can be in the form of a textual message at program startup or
23 * in documentation (online or textual) provided with the package.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
33 * 3. All advertising materials mentioning features or use of this software
34 * must display the following acknowledgement:
35 * "This product includes cryptographic software written by
36 * Eric Young (eay@cryptsoft.com)"
37 * The word 'cryptographic' can be left out if the rouines from the library
38 * being used are not cryptographic related :-).
39 * 4. If you include any Windows specific code (or a derivative thereof) from
40 * the apps directory (application code) you must include an acknowledgement:
41 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
43 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * The licence and distribution terms for any publically available version or
56 * derivative of this code cannot be changed. i.e. this code cannot simply be
57 * copied and put under another distribution licence
58 * [including the GNU Public Licence.]
60 /* ====================================================================
61 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
63 * Redistribution and use in source and binary forms, with or without
64 * modification, are permitted provided that the following conditions
67 * 1. Redistributions of source code must retain the above copyright
68 * notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 * notice, this list of conditions and the following disclaimer in
72 * the documentation and/or other materials provided with the
75 * 3. All advertising materials mentioning features or use of this
76 * software must display the following acknowledgment:
77 * "This product includes software developed by the OpenSSL Project
78 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
80 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
81 * endorse or promote products derived from this software without
82 * prior written permission. For written permission, please contact
83 * openssl-core@openssl.org.
85 * 5. Products derived from this software may not be called "OpenSSL"
86 * nor may "OpenSSL" appear in their names without prior written
87 * permission of the OpenSSL Project.
89 * 6. Redistributions of any form whatsoever must retain the following
91 * "This product includes software developed by the OpenSSL Project
92 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
94 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
95 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
97 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
98 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
99 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
100 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
101 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
103 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
104 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
105 * OF THE POSSIBILITY OF SUCH DAMAGE.
106 * ====================================================================
108 * This product includes cryptographic software written by Eric Young
109 * (eay@cryptsoft.com). This product includes software written by Tim
110 * Hudson (tjh@cryptsoft.com).
113 /* ====================================================================
114 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
115 * ECC cipher suite support in OpenSSL originally developed by
116 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
118 /* ====================================================================
119 * Copyright 2005 Nokia. All rights reserved.
121 * The portions of the attached software ("Contribution") is developed by
122 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
125 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
126 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
127 * support (see RFC 4279) to OpenSSL.
129 * No patent licenses or other rights except those expressly stated in
130 * the OpenSSL open source license shall be deemed granted or received
131 * expressly, by implication, estoppel, or otherwise.
133 * No assurances are provided by Nokia that the Contribution does not
134 * infringe the patent or other intellectual property rights of any third
135 * party or that the license provides you with all the necessary rights
136 * to make use of the Contribution.
138 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
139 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
140 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
141 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147 #include "ssl_locl.h"
148 #include <openssl/objects.h>
149 #include <openssl/lhash.h>
150 #include <openssl/x509v3.h>
151 #include <openssl/rand.h>
152 #include <openssl/ocsp.h>
153 #include <openssl/dh.h>
154 #include <openssl/engine.h>
155 #include <openssl/async.h>
156 #include <openssl/ct.h>
158 const char SSL_version_str[] = OPENSSL_VERSION_TEXT;
160 SSL3_ENC_METHOD ssl3_undef_enc_method = {
162 * evil casts, but these functions are only called if there's a library
165 (int (*)(SSL *, SSL3_RECORD *, unsigned int, int))ssl_undefined_function,
166 (int (*)(SSL *, SSL3_RECORD *, unsigned char *, int))ssl_undefined_function,
167 ssl_undefined_function,
168 (int (*)(SSL *, unsigned char *, unsigned char *, int))
169 ssl_undefined_function,
170 (int (*)(SSL *, int))ssl_undefined_function,
171 (int (*)(SSL *, const char *, int, unsigned char *))
172 ssl_undefined_function,
173 0, /* finish_mac_length */
174 NULL, /* client_finished_label */
175 0, /* client_finished_label_len */
176 NULL, /* server_finished_label */
177 0, /* server_finished_label_len */
178 (int (*)(int))ssl_undefined_function,
179 (int (*)(SSL *, unsigned char *, size_t, const char *,
180 size_t, const unsigned char *, size_t,
181 int use_context))ssl_undefined_function,
184 struct ssl_async_args {
188 enum { READFUNC, WRITEFUNC, OTHERFUNC} type;
190 int (*func_read)(SSL *, void *, int);
191 int (*func_write)(SSL *, const void *, int);
192 int (*func_other)(SSL *);
196 static const struct {
201 { DANETLS_MATCHING_FULL, 0, NID_undef },
202 { DANETLS_MATCHING_2256, 1, NID_sha256 },
203 { DANETLS_MATCHING_2512, 2, NID_sha512 },
206 static int dane_ctx_enable(struct dane_ctx_st *dctx)
208 const EVP_MD **mdevp;
210 uint8_t mdmax = DANETLS_MATCHING_LAST;
211 int n = ((int) mdmax) + 1; /* int to handle PrivMatch(255) */
214 mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
215 mdord = OPENSSL_zalloc(n * sizeof(*mdord));
217 if (mdord == NULL || mdevp == NULL) {
219 SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
223 /* Install default entries */
224 for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
227 if (dane_mds[i].nid == NID_undef ||
228 (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
230 mdevp[dane_mds[i].mtype] = md;
231 mdord[dane_mds[i].mtype] = dane_mds[i].ord;
241 static void dane_ctx_final(struct dane_ctx_st *dctx)
243 OPENSSL_free(dctx->mdevp);
246 OPENSSL_free(dctx->mdord);
251 static void tlsa_free(danetls_record *t)
255 OPENSSL_free(t->data);
256 EVP_PKEY_free(t->spki);
260 static void dane_final(SSL_DANE *dane)
262 sk_danetls_record_pop_free(dane->trecs, tlsa_free);
265 sk_X509_pop_free(dane->certs, X509_free);
268 X509_free(dane->mcert);
276 * dane_copy - Copy dane configuration, sans verification state.
278 static int ssl_dane_dup(SSL *to, SSL *from)
283 if (!DANETLS_ENABLED(&from->dane))
286 dane_final(&to->dane);
287 to->dane.dctx = &to->ctx->dane;
288 to->dane.trecs = sk_danetls_record_new_null();
290 if (to->dane.trecs == NULL) {
291 SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
295 num = sk_danetls_record_num(from->dane.trecs);
296 for (i = 0; i < num; ++i) {
297 danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
299 if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
300 t->data, t->dlen) <= 0)
306 static int dane_mtype_set(
307 struct dane_ctx_st *dctx,
314 if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
315 SSLerr(SSL_F_DANE_MTYPE_SET,
316 SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
320 if (mtype > dctx->mdmax) {
321 const EVP_MD **mdevp;
323 int n = ((int) mtype) + 1;
325 mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
327 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
332 mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
334 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
339 /* Zero-fill any gaps */
340 for (i = dctx->mdmax+1; i < mtype; ++i) {
348 dctx->mdevp[mtype] = md;
349 /* Coerce ordinal of disabled matching types to 0 */
350 dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
355 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
357 if (mtype > dane->dctx->mdmax)
359 return dane->dctx->mdevp[mtype];
362 static int dane_tlsa_add(
371 const EVP_MD *md = NULL;
372 int ilen = (int)dlen;
376 if (dane->trecs == NULL) {
377 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
381 if (ilen < 0 || dlen != (size_t)ilen) {
382 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
386 if (usage > DANETLS_USAGE_LAST) {
387 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
391 if (selector > DANETLS_SELECTOR_LAST) {
392 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
396 if (mtype != DANETLS_MATCHING_FULL) {
397 md = tlsa_md_get(dane, mtype);
399 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
404 if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
405 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
409 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
413 if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
414 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
419 t->selector = selector;
421 t->data = OPENSSL_malloc(ilen);
422 if (t->data == NULL) {
424 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
427 memcpy(t->data, data, ilen);
430 /* Validate and cache full certificate or public key */
431 if (mtype == DANETLS_MATCHING_FULL) {
432 const unsigned char *p = data;
434 EVP_PKEY *pkey = NULL;
437 case DANETLS_SELECTOR_CERT:
438 if (!d2i_X509(&cert, &p, dlen) || p < data ||
439 dlen != (size_t)(p - data)) {
441 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
444 if (X509_get0_pubkey(cert) == NULL) {
446 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
450 if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
456 * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
457 * records that contain full certificates of trust-anchors that are
458 * not present in the wire chain. For usage PKIX-TA(0), we augment
459 * the chain with untrusted Full(0) certificates from DNS, in case
460 * they are missing from the chain.
462 if ((dane->certs == NULL &&
463 (dane->certs = sk_X509_new_null()) == NULL) ||
464 !sk_X509_push(dane->certs, cert)) {
465 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
472 case DANETLS_SELECTOR_SPKI:
473 if (!d2i_PUBKEY(&pkey, &p, dlen) || p < data ||
474 dlen != (size_t)(p - data)) {
476 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
481 * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
482 * records that contain full bare keys of trust-anchors that are
483 * not present in the wire chain.
485 if (usage == DANETLS_USAGE_DANE_TA)
494 * Find the right insertion point for the new record.
496 * See crypto/x509/x509_vfy.c. We sort DANE-EE(3) records first, so that
497 * they can be processed first, as they require no chain building, and no
498 * expiration or hostname checks. Because DANE-EE(3) is numerically
499 * largest, this is accomplished via descending sort by "usage".
501 * We also sort in descending order by matching ordinal to simplify
502 * the implementation of digest agility in the verification code.
504 * The choice of order for the selector is not significant, so we
505 * use the same descending order for consistency.
507 num = sk_danetls_record_num(dane->trecs);
508 for (i = 0; i < num; ++i) {
509 danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
511 if (rec->usage > usage)
513 if (rec->usage < usage)
515 if (rec->selector > selector)
517 if (rec->selector < selector)
519 if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
524 if (!sk_danetls_record_insert(dane->trecs, t, i)) {
526 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
529 dane->umask |= DANETLS_USAGE_BIT(usage);
534 static void clear_ciphers(SSL *s)
536 /* clear the current cipher */
537 ssl_clear_cipher_ctx(s);
538 ssl_clear_hash_ctx(&s->read_hash);
539 ssl_clear_hash_ctx(&s->write_hash);
542 int SSL_clear(SSL *s)
544 if (s->method == NULL) {
545 SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
549 if (ssl_clear_bad_session(s)) {
550 SSL_SESSION_free(s->session);
558 if (s->renegotiate) {
559 SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
563 ossl_statem_clear(s);
565 s->version = s->method->version;
566 s->client_version = s->version;
567 s->rwstate = SSL_NOTHING;
569 BUF_MEM_free(s->init_buf);
574 /* Reset DANE verification result state */
577 X509_free(s->dane.mcert);
578 s->dane.mcert = NULL;
579 s->dane.mtlsa = NULL;
581 /* Clear the verification result peername */
582 X509_VERIFY_PARAM_move_peername(s->param, NULL);
585 * Check to see if we were changed into a different method, if so, revert
586 * back if we are not doing session-id reuse.
588 if (!ossl_statem_get_in_handshake(s) && (s->session == NULL)
589 && (s->method != s->ctx->method)) {
590 s->method->ssl_free(s);
591 s->method = s->ctx->method;
592 if (!s->method->ssl_new(s))
595 s->method->ssl_clear(s);
597 RECORD_LAYER_clear(&s->rlayer);
602 /** Used to change an SSL_CTXs default SSL method type */
603 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
605 STACK_OF(SSL_CIPHER) *sk;
609 sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
610 &(ctx->cipher_list_by_id),
611 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
612 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
613 SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
614 SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
620 SSL *SSL_new(SSL_CTX *ctx)
625 SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
628 if (ctx->method == NULL) {
629 SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
633 s = OPENSSL_zalloc(sizeof(*s));
637 s->lock = CRYPTO_THREAD_lock_new();
638 if (s->lock == NULL) {
639 SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
644 RECORD_LAYER_init(&s->rlayer, s);
646 s->options = ctx->options;
647 s->min_proto_version = ctx->min_proto_version;
648 s->max_proto_version = ctx->max_proto_version;
650 s->max_cert_list = ctx->max_cert_list;
654 * Earlier library versions used to copy the pointer to the CERT, not
655 * its contents; only when setting new parameters for the per-SSL
656 * copy, ssl_cert_new would be called (and the direct reference to
657 * the per-SSL_CTX settings would be lost, but those still were
658 * indirectly accessed for various purposes, and for that reason they
659 * used to be known as s->ctx->default_cert). Now we don't look at the
660 * SSL_CTX's CERT after having duplicated it once.
662 s->cert = ssl_cert_dup(ctx->cert);
666 RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
667 s->msg_callback = ctx->msg_callback;
668 s->msg_callback_arg = ctx->msg_callback_arg;
669 s->verify_mode = ctx->verify_mode;
670 s->not_resumable_session_cb = ctx->not_resumable_session_cb;
671 s->sid_ctx_length = ctx->sid_ctx_length;
672 OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
673 memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
674 s->verify_callback = ctx->default_verify_callback;
675 s->generate_session_id = ctx->generate_session_id;
677 s->param = X509_VERIFY_PARAM_new();
678 if (s->param == NULL)
680 X509_VERIFY_PARAM_inherit(s->param, ctx->param);
681 s->quiet_shutdown = ctx->quiet_shutdown;
682 s->max_send_fragment = ctx->max_send_fragment;
683 s->split_send_fragment = ctx->split_send_fragment;
684 s->max_pipelines = ctx->max_pipelines;
685 if (s->max_pipelines > 1)
686 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
687 if (ctx->default_read_buf_len > 0)
688 SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
692 s->tlsext_debug_cb = 0;
693 s->tlsext_debug_arg = NULL;
694 s->tlsext_ticket_expected = 0;
695 s->tlsext_status_type = -1;
696 s->tlsext_status_expected = 0;
697 s->tlsext_ocsp_ids = NULL;
698 s->tlsext_ocsp_exts = NULL;
699 s->tlsext_ocsp_resp = NULL;
700 s->tlsext_ocsp_resplen = -1;
702 s->initial_ctx = ctx;
703 # ifndef OPENSSL_NO_EC
704 if (ctx->tlsext_ecpointformatlist) {
705 s->tlsext_ecpointformatlist =
706 OPENSSL_memdup(ctx->tlsext_ecpointformatlist,
707 ctx->tlsext_ecpointformatlist_length);
708 if (!s->tlsext_ecpointformatlist)
710 s->tlsext_ecpointformatlist_length =
711 ctx->tlsext_ecpointformatlist_length;
713 if (ctx->tlsext_ellipticcurvelist) {
714 s->tlsext_ellipticcurvelist =
715 OPENSSL_memdup(ctx->tlsext_ellipticcurvelist,
716 ctx->tlsext_ellipticcurvelist_length);
717 if (!s->tlsext_ellipticcurvelist)
719 s->tlsext_ellipticcurvelist_length =
720 ctx->tlsext_ellipticcurvelist_length;
723 # ifndef OPENSSL_NO_NEXTPROTONEG
724 s->next_proto_negotiated = NULL;
727 if (s->ctx->alpn_client_proto_list) {
728 s->alpn_client_proto_list =
729 OPENSSL_malloc(s->ctx->alpn_client_proto_list_len);
730 if (s->alpn_client_proto_list == NULL)
732 memcpy(s->alpn_client_proto_list, s->ctx->alpn_client_proto_list,
733 s->ctx->alpn_client_proto_list_len);
734 s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
737 s->verified_chain = NULL;
738 s->verify_result = X509_V_OK;
740 s->default_passwd_callback = ctx->default_passwd_callback;
741 s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
743 s->method = ctx->method;
745 if (!s->method->ssl_new(s))
748 s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
753 CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
755 #ifndef OPENSSL_NO_PSK
756 s->psk_client_callback = ctx->psk_client_callback;
757 s->psk_server_callback = ctx->psk_server_callback;
762 #ifndef OPENSSL_NO_CT
763 if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
764 ctx->ct_validation_callback_arg))
771 SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
775 void SSL_up_ref(SSL *s)
778 CRYPTO_atomic_add(&s->references, 1, &i, s->lock);
781 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
782 unsigned int sid_ctx_len)
784 if (sid_ctx_len > sizeof ctx->sid_ctx) {
785 SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
786 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
789 ctx->sid_ctx_length = sid_ctx_len;
790 memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
795 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
796 unsigned int sid_ctx_len)
798 if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
799 SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
800 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
803 ssl->sid_ctx_length = sid_ctx_len;
804 memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
809 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
811 CRYPTO_THREAD_write_lock(ctx->lock);
812 ctx->generate_session_id = cb;
813 CRYPTO_THREAD_unlock(ctx->lock);
817 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
819 CRYPTO_THREAD_write_lock(ssl->lock);
820 ssl->generate_session_id = cb;
821 CRYPTO_THREAD_unlock(ssl->lock);
825 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
829 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
830 * we can "construct" a session to give us the desired check - ie. to
831 * find if there's a session in the hash table that would conflict with
832 * any new session built out of this id/id_len and the ssl_version in use
837 if (id_len > sizeof r.session_id)
840 r.ssl_version = ssl->version;
841 r.session_id_length = id_len;
842 memcpy(r.session_id, id, id_len);
844 CRYPTO_THREAD_read_lock(ssl->ctx->lock);
845 p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
846 CRYPTO_THREAD_unlock(ssl->ctx->lock);
850 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
852 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
855 int SSL_set_purpose(SSL *s, int purpose)
857 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
860 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
862 return X509_VERIFY_PARAM_set_trust(s->param, trust);
865 int SSL_set_trust(SSL *s, int trust)
867 return X509_VERIFY_PARAM_set_trust(s->param, trust);
870 int SSL_set1_host(SSL *s, const char *hostname)
872 return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
875 int SSL_add1_host(SSL *s, const char *hostname)
877 return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
880 void SSL_set_hostflags(SSL *s, unsigned int flags)
882 X509_VERIFY_PARAM_set_hostflags(s->param, flags);
885 const char *SSL_get0_peername(SSL *s)
887 return X509_VERIFY_PARAM_get0_peername(s->param);
890 int SSL_CTX_dane_enable(SSL_CTX *ctx)
892 return dane_ctx_enable(&ctx->dane);
895 int SSL_dane_enable(SSL *s, const char *basedomain)
897 SSL_DANE *dane = &s->dane;
899 if (s->ctx->dane.mdmax == 0) {
900 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
903 if (dane->trecs != NULL) {
904 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
909 * Default SNI name. This rejects empty names, while set1_host below
910 * accepts them and disables host name checks. To avoid side-effects with
911 * invalid input, set the SNI name first.
913 if (s->tlsext_hostname == NULL) {
914 if (!SSL_set_tlsext_host_name(s, basedomain)) {
915 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
920 /* Primary RFC6125 reference identifier */
921 if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
922 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
928 dane->dctx = &s->ctx->dane;
929 dane->trecs = sk_danetls_record_new_null();
931 if (dane->trecs == NULL) {
932 SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
938 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
940 SSL_DANE *dane = &s->dane;
942 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
946 *mcert = dane->mcert;
948 *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
953 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
954 uint8_t *mtype, unsigned const char **data, size_t *dlen)
956 SSL_DANE *dane = &s->dane;
958 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
962 *usage = dane->mtlsa->usage;
964 *selector = dane->mtlsa->selector;
966 *mtype = dane->mtlsa->mtype;
968 *data = dane->mtlsa->data;
970 *dlen = dane->mtlsa->dlen;
975 SSL_DANE *SSL_get0_dane(SSL *s)
980 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
981 uint8_t mtype, unsigned char *data, size_t dlen)
983 return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
986 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype, uint8_t ord)
988 return dane_mtype_set(&ctx->dane, md, mtype, ord);
991 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
993 return X509_VERIFY_PARAM_set1(ctx->param, vpm);
996 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
998 return X509_VERIFY_PARAM_set1(ssl->param, vpm);
1001 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
1006 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
1011 void SSL_certs_clear(SSL *s)
1013 ssl_cert_clear_certs(s->cert);
1016 void SSL_free(SSL *s)
1023 CRYPTO_atomic_add(&s->references, -1, &i, s->lock);
1024 REF_PRINT_COUNT("SSL", s);
1027 REF_ASSERT_ISNT(i < 0);
1029 X509_VERIFY_PARAM_free(s->param);
1030 dane_final(&s->dane);
1031 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
1033 if (s->bbio != NULL) {
1034 /* If the buffering BIO is in place, pop it off */
1035 if (s->bbio == s->wbio) {
1036 s->wbio = BIO_pop(s->wbio);
1041 BIO_free_all(s->rbio);
1042 if (s->wbio != s->rbio)
1043 BIO_free_all(s->wbio);
1045 BUF_MEM_free(s->init_buf);
1047 /* add extra stuff */
1048 sk_SSL_CIPHER_free(s->cipher_list);
1049 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1051 /* Make the next call work :-) */
1052 if (s->session != NULL) {
1053 ssl_clear_bad_session(s);
1054 SSL_SESSION_free(s->session);
1059 ssl_cert_free(s->cert);
1060 /* Free up if allocated */
1062 OPENSSL_free(s->tlsext_hostname);
1063 SSL_CTX_free(s->initial_ctx);
1064 #ifndef OPENSSL_NO_EC
1065 OPENSSL_free(s->tlsext_ecpointformatlist);
1066 OPENSSL_free(s->tlsext_ellipticcurvelist);
1067 #endif /* OPENSSL_NO_EC */
1068 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
1069 #ifndef OPENSSL_NO_OCSP
1070 sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
1072 #ifndef OPENSSL_NO_CT
1073 SCT_LIST_free(s->scts);
1074 OPENSSL_free(s->tlsext_scts);
1076 OPENSSL_free(s->tlsext_ocsp_resp);
1077 OPENSSL_free(s->alpn_client_proto_list);
1079 sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
1081 sk_X509_pop_free(s->verified_chain, X509_free);
1083 if (s->method != NULL)
1084 s->method->ssl_free(s);
1086 RECORD_LAYER_release(&s->rlayer);
1088 SSL_CTX_free(s->ctx);
1090 ASYNC_WAIT_CTX_free(s->waitctx);
1092 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1093 OPENSSL_free(s->next_proto_negotiated);
1096 #ifndef OPENSSL_NO_SRTP
1097 sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1100 CRYPTO_THREAD_lock_free(s->lock);
1105 void SSL_set_rbio(SSL *s, BIO *rbio)
1107 if (s->rbio != rbio)
1108 BIO_free_all(s->rbio);
1112 void SSL_set_wbio(SSL *s, BIO *wbio)
1115 * If the output buffering BIO is still in place, remove it
1117 if (s->bbio != NULL) {
1118 if (s->wbio == s->bbio) {
1119 s->wbio = BIO_next(s->wbio);
1120 BIO_set_next(s->bbio, NULL);
1123 if (s->wbio != wbio && s->rbio != s->wbio)
1124 BIO_free_all(s->wbio);
1128 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1130 SSL_set_wbio(s, wbio);
1131 SSL_set_rbio(s, rbio);
1134 BIO *SSL_get_rbio(const SSL *s)
1139 BIO *SSL_get_wbio(const SSL *s)
1144 int SSL_get_fd(const SSL *s)
1146 return (SSL_get_rfd(s));
1149 int SSL_get_rfd(const SSL *s)
1154 b = SSL_get_rbio(s);
1155 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1157 BIO_get_fd(r, &ret);
1161 int SSL_get_wfd(const SSL *s)
1166 b = SSL_get_wbio(s);
1167 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1169 BIO_get_fd(r, &ret);
1173 #ifndef OPENSSL_NO_SOCK
1174 int SSL_set_fd(SSL *s, int fd)
1179 bio = BIO_new(BIO_s_socket());
1182 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1185 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1186 SSL_set_bio(s, bio, bio);
1192 int SSL_set_wfd(SSL *s, int fd)
1197 if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
1198 || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
1199 bio = BIO_new(BIO_s_socket());
1202 SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1205 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1206 SSL_set_bio(s, SSL_get_rbio(s), bio);
1208 SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
1214 int SSL_set_rfd(SSL *s, int fd)
1219 if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
1220 || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
1221 bio = BIO_new(BIO_s_socket());
1224 SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1227 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1228 SSL_set_bio(s, bio, SSL_get_wbio(s));
1230 SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
1237 /* return length of latest Finished message we sent, copy to 'buf' */
1238 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1242 if (s->s3 != NULL) {
1243 ret = s->s3->tmp.finish_md_len;
1246 memcpy(buf, s->s3->tmp.finish_md, count);
1251 /* return length of latest Finished message we expected, copy to 'buf' */
1252 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1256 if (s->s3 != NULL) {
1257 ret = s->s3->tmp.peer_finish_md_len;
1260 memcpy(buf, s->s3->tmp.peer_finish_md, count);
1265 int SSL_get_verify_mode(const SSL *s)
1267 return (s->verify_mode);
1270 int SSL_get_verify_depth(const SSL *s)
1272 return X509_VERIFY_PARAM_get_depth(s->param);
1275 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1276 return (s->verify_callback);
1279 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1281 return (ctx->verify_mode);
1284 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1286 return X509_VERIFY_PARAM_get_depth(ctx->param);
1289 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1290 return (ctx->default_verify_callback);
1293 void SSL_set_verify(SSL *s, int mode,
1294 int (*callback) (int ok, X509_STORE_CTX *ctx))
1296 s->verify_mode = mode;
1297 if (callback != NULL)
1298 s->verify_callback = callback;
1301 void SSL_set_verify_depth(SSL *s, int depth)
1303 X509_VERIFY_PARAM_set_depth(s->param, depth);
1306 void SSL_set_read_ahead(SSL *s, int yes)
1308 RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1311 int SSL_get_read_ahead(const SSL *s)
1313 return RECORD_LAYER_get_read_ahead(&s->rlayer);
1316 int SSL_pending(const SSL *s)
1319 * SSL_pending cannot work properly if read-ahead is enabled
1320 * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1321 * impossible to fix since SSL_pending cannot report errors that may be
1322 * observed while scanning the new data. (Note that SSL_pending() is
1323 * often used as a boolean value, so we'd better not return -1.)
1325 return (s->method->ssl_pending(s));
1328 int SSL_has_pending(const SSL *s)
1331 * Similar to SSL_pending() but returns a 1 to indicate that we have
1332 * unprocessed data available or 0 otherwise (as opposed to the number of
1333 * bytes available). Unlike SSL_pending() this will take into account
1334 * read_ahead data. A 1 return simply indicates that we have unprocessed
1335 * data. That data may not result in any application data, or we may fail
1336 * to parse the records for some reason.
1341 return RECORD_LAYER_read_pending(&s->rlayer);
1344 X509 *SSL_get_peer_certificate(const SSL *s)
1348 if ((s == NULL) || (s->session == NULL))
1351 r = s->session->peer;
1361 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1365 if ((s == NULL) || (s->session == NULL))
1368 r = s->session->peer_chain;
1371 * If we are a client, cert_chain includes the peer's own certificate; if
1372 * we are a server, it does not.
1379 * Now in theory, since the calling process own 't' it should be safe to
1380 * modify. We need to be able to read f without being hassled
1382 int SSL_copy_session_id(SSL *t, const SSL *f)
1385 /* Do we need to to SSL locking? */
1386 if (!SSL_set_session(t, SSL_get_session(f))) {
1391 * what if we are setup for one protocol version but want to talk another
1393 if (t->method != f->method) {
1394 t->method->ssl_free(t);
1395 t->method = f->method;
1396 if (t->method->ssl_new(t) == 0)
1400 CRYPTO_atomic_add(&f->cert->references, 1, &i, f->cert->lock);
1401 ssl_cert_free(t->cert);
1403 if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length)) {
1410 /* Fix this so it checks all the valid key/cert options */
1411 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1413 if ((ctx == NULL) ||
1414 (ctx->cert->key->x509 == NULL)) {
1415 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
1416 SSL_R_NO_CERTIFICATE_ASSIGNED);
1419 if (ctx->cert->key->privatekey == NULL) {
1420 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
1421 SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1424 return (X509_check_private_key
1425 (ctx->cert->key->x509, ctx->cert->key->privatekey));
1428 /* Fix this function so that it takes an optional type parameter */
1429 int SSL_check_private_key(const SSL *ssl)
1432 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1435 if (ssl->cert->key->x509 == NULL) {
1436 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1439 if (ssl->cert->key->privatekey == NULL) {
1440 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1443 return (X509_check_private_key(ssl->cert->key->x509,
1444 ssl->cert->key->privatekey));
1447 int SSL_waiting_for_async(SSL *s)
1455 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1457 ASYNC_WAIT_CTX *ctx = s->waitctx;
1461 return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1464 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1465 OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1467 ASYNC_WAIT_CTX *ctx = s->waitctx;
1471 return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1475 int SSL_accept(SSL *s)
1477 if (s->handshake_func == NULL) {
1478 /* Not properly initialized yet */
1479 SSL_set_accept_state(s);
1482 return SSL_do_handshake(s);
1485 int SSL_connect(SSL *s)
1487 if (s->handshake_func == NULL) {
1488 /* Not properly initialized yet */
1489 SSL_set_connect_state(s);
1492 return SSL_do_handshake(s);
1495 long SSL_get_default_timeout(const SSL *s)
1497 return (s->method->get_timeout());
1500 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1501 int (*func)(void *)) {
1503 if (s->waitctx == NULL) {
1504 s->waitctx = ASYNC_WAIT_CTX_new();
1505 if (s->waitctx == NULL)
1508 switch(ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1509 sizeof(struct ssl_async_args))) {
1511 s->rwstate = SSL_NOTHING;
1512 SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1515 s->rwstate = SSL_ASYNC_PAUSED;
1521 s->rwstate = SSL_NOTHING;
1522 SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1523 /* Shouldn't happen */
1528 static int ssl_io_intern(void *vargs)
1530 struct ssl_async_args *args;
1535 args = (struct ssl_async_args *)vargs;
1539 switch (args->type) {
1541 return args->f.func_read(s, buf, num);
1543 return args->f.func_write(s, buf, num);
1545 return args->f.func_other(s);
1550 int SSL_read(SSL *s, void *buf, int num)
1552 if (s->handshake_func == NULL) {
1553 SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
1557 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1558 s->rwstate = SSL_NOTHING;
1562 if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1563 struct ssl_async_args args;
1568 args.type = READFUNC;
1569 args.f.func_read = s->method->ssl_read;
1571 return ssl_start_async_job(s, &args, ssl_io_intern);
1573 return s->method->ssl_read(s, buf, num);
1577 int SSL_peek(SSL *s, void *buf, int num)
1579 if (s->handshake_func == NULL) {
1580 SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
1584 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1587 if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1588 struct ssl_async_args args;
1593 args.type = READFUNC;
1594 args.f.func_read = s->method->ssl_peek;
1596 return ssl_start_async_job(s, &args, ssl_io_intern);
1598 return s->method->ssl_peek(s, buf, num);
1602 int SSL_write(SSL *s, const void *buf, int num)
1604 if (s->handshake_func == NULL) {
1605 SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
1609 if (s->shutdown & SSL_SENT_SHUTDOWN) {
1610 s->rwstate = SSL_NOTHING;
1611 SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
1615 if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1616 struct ssl_async_args args;
1619 args.buf = (void *)buf;
1621 args.type = WRITEFUNC;
1622 args.f.func_write = s->method->ssl_write;
1624 return ssl_start_async_job(s, &args, ssl_io_intern);
1626 return s->method->ssl_write(s, buf, num);
1630 int SSL_shutdown(SSL *s)
1633 * Note that this function behaves differently from what one might
1634 * expect. Return values are 0 for no success (yet), 1 for success; but
1635 * calling it once is usually not enough, even if blocking I/O is used
1636 * (see ssl3_shutdown).
1639 if (s->handshake_func == NULL) {
1640 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1644 if (!SSL_in_init(s)) {
1645 if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1646 struct ssl_async_args args;
1649 args.type = OTHERFUNC;
1650 args.f.func_other = s->method->ssl_shutdown;
1652 return ssl_start_async_job(s, &args, ssl_io_intern);
1654 return s->method->ssl_shutdown(s);
1657 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
1662 int SSL_renegotiate(SSL *s)
1664 if (s->renegotiate == 0)
1669 return (s->method->ssl_renegotiate(s));
1672 int SSL_renegotiate_abbreviated(SSL *s)
1674 if (s->renegotiate == 0)
1679 return (s->method->ssl_renegotiate(s));
1682 int SSL_renegotiate_pending(SSL *s)
1685 * becomes true when negotiation is requested; false again once a
1686 * handshake has finished
1688 return (s->renegotiate != 0);
1691 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1696 case SSL_CTRL_GET_READ_AHEAD:
1697 return (RECORD_LAYER_get_read_ahead(&s->rlayer));
1698 case SSL_CTRL_SET_READ_AHEAD:
1699 l = RECORD_LAYER_get_read_ahead(&s->rlayer);
1700 RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
1703 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1704 s->msg_callback_arg = parg;
1708 return (s->mode |= larg);
1709 case SSL_CTRL_CLEAR_MODE:
1710 return (s->mode &= ~larg);
1711 case SSL_CTRL_GET_MAX_CERT_LIST:
1712 return (s->max_cert_list);
1713 case SSL_CTRL_SET_MAX_CERT_LIST:
1714 l = s->max_cert_list;
1715 s->max_cert_list = larg;
1717 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1718 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1720 s->max_send_fragment = larg;
1721 if (s->max_send_fragment < s->split_send_fragment)
1722 s->split_send_fragment = s->max_send_fragment;
1724 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1725 if ((unsigned int)larg > s->max_send_fragment || larg == 0)
1727 s->split_send_fragment = larg;
1729 case SSL_CTRL_SET_MAX_PIPELINES:
1730 if (larg < 1 || larg > SSL_MAX_PIPELINES)
1732 s->max_pipelines = larg;
1734 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
1736 case SSL_CTRL_GET_RI_SUPPORT:
1738 return s->s3->send_connection_binding;
1741 case SSL_CTRL_CERT_FLAGS:
1742 return (s->cert->cert_flags |= larg);
1743 case SSL_CTRL_CLEAR_CERT_FLAGS:
1744 return (s->cert->cert_flags &= ~larg);
1746 case SSL_CTRL_GET_RAW_CIPHERLIST:
1748 if (s->s3->tmp.ciphers_raw == NULL)
1750 *(unsigned char **)parg = s->s3->tmp.ciphers_raw;
1751 return (int)s->s3->tmp.ciphers_rawlen;
1753 return TLS_CIPHER_LEN;
1755 case SSL_CTRL_GET_EXTMS_SUPPORT:
1756 if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
1758 if (s->session->flags & SSL_SESS_FLAG_EXTMS)
1762 case SSL_CTRL_SET_MIN_PROTO_VERSION:
1763 return ssl_set_version_bound(s->ctx->method->version, (int)larg,
1764 &s->min_proto_version);
1765 case SSL_CTRL_SET_MAX_PROTO_VERSION:
1766 return ssl_set_version_bound(s->ctx->method->version, (int)larg,
1767 &s->max_proto_version);
1769 return (s->method->ssl_ctrl(s, cmd, larg, parg));
1773 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1776 case SSL_CTRL_SET_MSG_CALLBACK:
1777 s->msg_callback = (void (*)
1778 (int write_p, int version, int content_type,
1779 const void *buf, size_t len, SSL *ssl,
1784 return (s->method->ssl_callback_ctrl(s, cmd, fp));
1788 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
1790 return ctx->sessions;
1793 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1796 /* For some cases with ctx == NULL perform syntax checks */
1799 #ifndef OPENSSL_NO_EC
1800 case SSL_CTRL_SET_CURVES_LIST:
1801 return tls1_set_curves_list(NULL, NULL, parg);
1803 case SSL_CTRL_SET_SIGALGS_LIST:
1804 case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
1805 return tls1_set_sigalgs_list(NULL, parg, 0);
1812 case SSL_CTRL_GET_READ_AHEAD:
1813 return (ctx->read_ahead);
1814 case SSL_CTRL_SET_READ_AHEAD:
1815 l = ctx->read_ahead;
1816 ctx->read_ahead = larg;
1819 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1820 ctx->msg_callback_arg = parg;
1823 case SSL_CTRL_GET_MAX_CERT_LIST:
1824 return (ctx->max_cert_list);
1825 case SSL_CTRL_SET_MAX_CERT_LIST:
1826 l = ctx->max_cert_list;
1827 ctx->max_cert_list = larg;
1830 case SSL_CTRL_SET_SESS_CACHE_SIZE:
1831 l = ctx->session_cache_size;
1832 ctx->session_cache_size = larg;
1834 case SSL_CTRL_GET_SESS_CACHE_SIZE:
1835 return (ctx->session_cache_size);
1836 case SSL_CTRL_SET_SESS_CACHE_MODE:
1837 l = ctx->session_cache_mode;
1838 ctx->session_cache_mode = larg;
1840 case SSL_CTRL_GET_SESS_CACHE_MODE:
1841 return (ctx->session_cache_mode);
1843 case SSL_CTRL_SESS_NUMBER:
1844 return (lh_SSL_SESSION_num_items(ctx->sessions));
1845 case SSL_CTRL_SESS_CONNECT:
1846 return (ctx->stats.sess_connect);
1847 case SSL_CTRL_SESS_CONNECT_GOOD:
1848 return (ctx->stats.sess_connect_good);
1849 case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1850 return (ctx->stats.sess_connect_renegotiate);
1851 case SSL_CTRL_SESS_ACCEPT:
1852 return (ctx->stats.sess_accept);
1853 case SSL_CTRL_SESS_ACCEPT_GOOD:
1854 return (ctx->stats.sess_accept_good);
1855 case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1856 return (ctx->stats.sess_accept_renegotiate);
1857 case SSL_CTRL_SESS_HIT:
1858 return (ctx->stats.sess_hit);
1859 case SSL_CTRL_SESS_CB_HIT:
1860 return (ctx->stats.sess_cb_hit);
1861 case SSL_CTRL_SESS_MISSES:
1862 return (ctx->stats.sess_miss);
1863 case SSL_CTRL_SESS_TIMEOUTS:
1864 return (ctx->stats.sess_timeout);
1865 case SSL_CTRL_SESS_CACHE_FULL:
1866 return (ctx->stats.sess_cache_full);
1868 return (ctx->mode |= larg);
1869 case SSL_CTRL_CLEAR_MODE:
1870 return (ctx->mode &= ~larg);
1871 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1872 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1874 ctx->max_send_fragment = larg;
1875 if (ctx->max_send_fragment < ctx->split_send_fragment)
1876 ctx->split_send_fragment = ctx->max_send_fragment;
1878 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1879 if ((unsigned int)larg > ctx->max_send_fragment || larg == 0)
1881 ctx->split_send_fragment = larg;
1883 case SSL_CTRL_SET_MAX_PIPELINES:
1884 if (larg < 1 || larg > SSL_MAX_PIPELINES)
1886 ctx->max_pipelines = larg;
1888 case SSL_CTRL_CERT_FLAGS:
1889 return (ctx->cert->cert_flags |= larg);
1890 case SSL_CTRL_CLEAR_CERT_FLAGS:
1891 return (ctx->cert->cert_flags &= ~larg);
1892 case SSL_CTRL_SET_MIN_PROTO_VERSION:
1893 return ssl_set_version_bound(ctx->method->version, (int)larg,
1894 &ctx->min_proto_version);
1895 case SSL_CTRL_SET_MAX_PROTO_VERSION:
1896 return ssl_set_version_bound(ctx->method->version, (int)larg,
1897 &ctx->max_proto_version);
1899 return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
1903 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
1906 case SSL_CTRL_SET_MSG_CALLBACK:
1907 ctx->msg_callback = (void (*)
1908 (int write_p, int version, int content_type,
1909 const void *buf, size_t len, SSL *ssl,
1914 return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
1918 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1927 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
1928 const SSL_CIPHER *const *bp)
1930 if ((*ap)->id > (*bp)->id)
1932 if ((*ap)->id < (*bp)->id)
1937 /** return a STACK of the ciphers available for the SSL and in order of
1939 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
1942 if (s->cipher_list != NULL) {
1943 return (s->cipher_list);
1944 } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1945 return (s->ctx->cipher_list);
1951 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
1953 if ((s == NULL) || (s->session == NULL) || !s->server)
1955 return s->session->ciphers;
1958 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
1960 STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
1962 ciphers = SSL_get_ciphers(s);
1965 ssl_set_client_disabled(s);
1966 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1967 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
1968 if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED)) {
1970 sk = sk_SSL_CIPHER_new_null();
1973 if (!sk_SSL_CIPHER_push(sk, c)) {
1974 sk_SSL_CIPHER_free(sk);
1982 /** return a STACK of the ciphers available for the SSL and in order of
1984 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
1987 if (s->cipher_list_by_id != NULL) {
1988 return (s->cipher_list_by_id);
1989 } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
1990 return (s->ctx->cipher_list_by_id);
1996 /** The old interface to get the same thing as SSL_get_ciphers() */
1997 const char *SSL_get_cipher_list(const SSL *s, int n)
1999 const SSL_CIPHER *c;
2000 STACK_OF(SSL_CIPHER) *sk;
2004 sk = SSL_get_ciphers(s);
2005 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2007 c = sk_SSL_CIPHER_value(sk, n);
2013 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2015 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2018 return ctx->cipher_list;
2022 /** specify the ciphers to be used by default by the SSL_CTX */
2023 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2025 STACK_OF(SSL_CIPHER) *sk;
2027 sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
2028 &ctx->cipher_list_by_id, str, ctx->cert);
2030 * ssl_create_cipher_list may return an empty stack if it was unable to
2031 * find a cipher matching the given rule string (for example if the rule
2032 * string specifies a cipher which has been disabled). This is not an
2033 * error as far as ssl_create_cipher_list is concerned, and hence
2034 * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2038 else if (sk_SSL_CIPHER_num(sk) == 0) {
2039 SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2045 /** specify the ciphers to be used by the SSL */
2046 int SSL_set_cipher_list(SSL *s, const char *str)
2048 STACK_OF(SSL_CIPHER) *sk;
2050 sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
2051 &s->cipher_list_by_id, str, s->cert);
2052 /* see comment in SSL_CTX_set_cipher_list */
2055 else if (sk_SSL_CIPHER_num(sk) == 0) {
2056 SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2062 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
2065 STACK_OF(SSL_CIPHER) *sk;
2066 const SSL_CIPHER *c;
2069 if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
2073 sk = s->session->ciphers;
2075 if (sk_SSL_CIPHER_num(sk) == 0)
2078 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2081 c = sk_SSL_CIPHER_value(sk, i);
2082 n = strlen(c->name);
2089 memcpy(p, c->name, n + 1);
2098 /** return a servername extension value if provided in Client Hello, or NULL.
2099 * So far, only host_name types are defined (RFC 3546).
2102 const char *SSL_get_servername(const SSL *s, const int type)
2104 if (type != TLSEXT_NAMETYPE_host_name)
2107 return s->session && !s->tlsext_hostname ?
2108 s->session->tlsext_hostname : s->tlsext_hostname;
2111 int SSL_get_servername_type(const SSL *s)
2114 && (!s->tlsext_hostname ? s->session->
2115 tlsext_hostname : s->tlsext_hostname))
2116 return TLSEXT_NAMETYPE_host_name;
2121 * SSL_select_next_proto implements the standard protocol selection. It is
2122 * expected that this function is called from the callback set by
2123 * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2124 * vector of 8-bit, length prefixed byte strings. The length byte itself is
2125 * not included in the length. A byte string of length 0 is invalid. No byte
2126 * string may be truncated. The current, but experimental algorithm for
2127 * selecting the protocol is: 1) If the server doesn't support NPN then this
2128 * is indicated to the callback. In this case, the client application has to
2129 * abort the connection or have a default application level protocol. 2) If
2130 * the server supports NPN, but advertises an empty list then the client
2131 * selects the first protcol in its list, but indicates via the API that this
2132 * fallback case was enacted. 3) Otherwise, the client finds the first
2133 * protocol in the server's list that it supports and selects this protocol.
2134 * This is because it's assumed that the server has better information about
2135 * which protocol a client should use. 4) If the client doesn't support any
2136 * of the server's advertised protocols, then this is treated the same as
2137 * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2138 * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2140 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2141 const unsigned char *server,
2142 unsigned int server_len,
2143 const unsigned char *client,
2144 unsigned int client_len)
2147 const unsigned char *result;
2148 int status = OPENSSL_NPN_UNSUPPORTED;
2151 * For each protocol in server preference order, see if we support it.
2153 for (i = 0; i < server_len;) {
2154 for (j = 0; j < client_len;) {
2155 if (server[i] == client[j] &&
2156 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2157 /* We found a match */
2158 result = &server[i];
2159 status = OPENSSL_NPN_NEGOTIATED;
2169 /* There's no overlap between our protocols and the server's list. */
2171 status = OPENSSL_NPN_NO_OVERLAP;
2174 *out = (unsigned char *)result + 1;
2175 *outlen = result[0];
2179 #ifndef OPENSSL_NO_NEXTPROTONEG
2181 * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2182 * client's requested protocol for this connection and returns 0. If the
2183 * client didn't request any protocol, then *data is set to NULL. Note that
2184 * the client can request any protocol it chooses. The value returned from
2185 * this function need not be a member of the list of supported protocols
2186 * provided by the callback.
2188 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2191 *data = s->next_proto_negotiated;
2195 *len = s->next_proto_negotiated_len;
2200 * SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when
2201 * a TLS server needs a list of supported protocols for Next Protocol
2202 * Negotiation. The returned list must be in wire format. The list is
2203 * returned by setting |out| to point to it and |outlen| to its length. This
2204 * memory will not be modified, but one should assume that the SSL* keeps a
2205 * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2206 * wishes to advertise. Otherwise, no such extension will be included in the
2209 void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx,
2210 int (*cb) (SSL *ssl,
2213 unsigned int *outlen,
2214 void *arg), void *arg)
2216 ctx->next_protos_advertised_cb = cb;
2217 ctx->next_protos_advertised_cb_arg = arg;
2221 * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2222 * client needs to select a protocol from the server's provided list. |out|
2223 * must be set to point to the selected protocol (which may be within |in|).
2224 * The length of the protocol name must be written into |outlen|. The
2225 * server's advertised protocols are provided in |in| and |inlen|. The
2226 * callback can assume that |in| is syntactically valid. The client must
2227 * select a protocol. It is fatal to the connection if this callback returns
2228 * a value other than SSL_TLSEXT_ERR_OK.
2230 void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,
2231 int (*cb) (SSL *s, unsigned char **out,
2232 unsigned char *outlen,
2233 const unsigned char *in,
2235 void *arg), void *arg)
2237 ctx->next_proto_select_cb = cb;
2238 ctx->next_proto_select_cb_arg = arg;
2243 * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2244 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2245 * length-prefixed strings). Returns 0 on success.
2247 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2248 unsigned int protos_len)
2250 OPENSSL_free(ctx->alpn_client_proto_list);
2251 ctx->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2252 if (ctx->alpn_client_proto_list == NULL) {
2253 SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2256 ctx->alpn_client_proto_list_len = protos_len;
2262 * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2263 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2264 * length-prefixed strings). Returns 0 on success.
2266 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2267 unsigned int protos_len)
2269 OPENSSL_free(ssl->alpn_client_proto_list);
2270 ssl->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2271 if (ssl->alpn_client_proto_list == NULL) {
2272 SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2275 ssl->alpn_client_proto_list_len = protos_len;
2281 * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2282 * called during ClientHello processing in order to select an ALPN protocol
2283 * from the client's list of offered protocols.
2285 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2286 int (*cb) (SSL *ssl,
2287 const unsigned char **out,
2288 unsigned char *outlen,
2289 const unsigned char *in,
2291 void *arg), void *arg)
2293 ctx->alpn_select_cb = cb;
2294 ctx->alpn_select_cb_arg = arg;
2298 * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from
2299 * |ssl|. On return it sets |*data| to point to |*len| bytes of protocol name
2300 * (not including the leading length-prefix byte). If the server didn't
2301 * respond with a negotiated protocol then |*len| will be zero.
2303 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
2308 *data = ssl->s3->alpn_selected;
2312 *len = ssl->s3->alpn_selected_len;
2316 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2317 const char *label, size_t llen,
2318 const unsigned char *p, size_t plen,
2321 if (s->version < TLS1_VERSION)
2324 return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
2329 static unsigned long ssl_session_hash(const SSL_SESSION *a)
2334 ((unsigned int)a->session_id[0]) |
2335 ((unsigned int)a->session_id[1] << 8L) |
2336 ((unsigned long)a->session_id[2] << 16L) |
2337 ((unsigned long)a->session_id[3] << 24L);
2342 * NB: If this function (or indeed the hash function which uses a sort of
2343 * coarser function than this one) is changed, ensure
2344 * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
2345 * being able to construct an SSL_SESSION that will collide with any existing
2346 * session with a matching session ID.
2348 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
2350 if (a->ssl_version != b->ssl_version)
2352 if (a->session_id_length != b->session_id_length)
2354 return (memcmp(a->session_id, b->session_id, a->session_id_length));
2358 * These wrapper functions should remain rather than redeclaring
2359 * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
2360 * variable. The reason is that the functions aren't static, they're exposed
2364 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
2366 SSL_CTX *ret = NULL;
2369 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
2373 if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
2376 if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
2377 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE);
2381 if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
2382 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
2385 ret = OPENSSL_zalloc(sizeof(*ret));
2390 ret->min_proto_version = 0;
2391 ret->max_proto_version = 0;
2392 ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
2393 ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
2394 /* We take the system default. */
2395 ret->session_timeout = meth->get_timeout();
2396 ret->references = 1;
2397 ret->lock = CRYPTO_THREAD_lock_new();
2398 if (ret->lock == NULL) {
2399 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2403 ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
2404 ret->verify_mode = SSL_VERIFY_NONE;
2405 if ((ret->cert = ssl_cert_new()) == NULL)
2408 ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2409 if (ret->sessions == NULL)
2411 ret->cert_store = X509_STORE_new();
2412 if (ret->cert_store == NULL)
2414 #ifndef OPENSSL_NO_CT
2415 ret->ctlog_store = CTLOG_STORE_new();
2416 if (ret->ctlog_store == NULL)
2419 if (!ssl_create_cipher_list(ret->method,
2420 &ret->cipher_list, &ret->cipher_list_by_id,
2421 SSL_DEFAULT_CIPHER_LIST, ret->cert)
2422 || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2423 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2427 ret->param = X509_VERIFY_PARAM_new();
2428 if (ret->param == NULL)
2431 if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
2432 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
2435 if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
2436 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
2440 if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
2443 CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
2445 /* No compression for DTLS */
2446 if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
2447 ret->comp_methods = SSL_COMP_get_compression_methods();
2449 ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2450 ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2452 /* Setup RFC4507 ticket keys */
2453 if ((RAND_bytes(ret->tlsext_tick_key_name, 16) <= 0)
2454 || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
2455 || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
2456 ret->options |= SSL_OP_NO_TICKET;
2458 #ifndef OPENSSL_NO_SRP
2459 if (!SSL_CTX_SRP_CTX_init(ret))
2462 #ifndef OPENSSL_NO_ENGINE
2463 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2464 # define eng_strx(x) #x
2465 # define eng_str(x) eng_strx(x)
2466 /* Use specific client engine automatically... ignore errors */
2469 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2472 ENGINE_load_builtin_engines();
2473 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2475 if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2481 * Default is to connect to non-RI servers. When RI is more widely
2482 * deployed might change this.
2484 ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2486 * Disable compression by default to prevent CRIME. Applications can
2487 * re-enable compression by configuring
2488 * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
2489 * or by using the SSL_CONF library.
2491 ret->options |= SSL_OP_NO_COMPRESSION;
2495 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2501 void SSL_CTX_up_ref(SSL_CTX *ctx)
2504 CRYPTO_atomic_add(&ctx->references, 1, &i, ctx->lock);
2507 void SSL_CTX_free(SSL_CTX *a)
2514 CRYPTO_atomic_add(&a->references, -1, &i, a->lock);
2515 REF_PRINT_COUNT("SSL_CTX", a);
2518 REF_ASSERT_ISNT(i < 0);
2520 X509_VERIFY_PARAM_free(a->param);
2521 dane_ctx_final(&a->dane);
2524 * Free internal session cache. However: the remove_cb() may reference
2525 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2526 * after the sessions were flushed.
2527 * As the ex_data handling routines might also touch the session cache,
2528 * the most secure solution seems to be: empty (flush) the cache, then
2529 * free ex_data, then finally free the cache.
2530 * (See ticket [openssl.org #212].)
2532 if (a->sessions != NULL)
2533 SSL_CTX_flush_sessions(a, 0);
2535 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2536 lh_SSL_SESSION_free(a->sessions);
2537 X509_STORE_free(a->cert_store);
2538 #ifndef OPENSSL_NO_CT
2539 CTLOG_STORE_free(a->ctlog_store);
2541 sk_SSL_CIPHER_free(a->cipher_list);
2542 sk_SSL_CIPHER_free(a->cipher_list_by_id);
2543 ssl_cert_free(a->cert);
2544 sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
2545 sk_X509_pop_free(a->extra_certs, X509_free);
2546 a->comp_methods = NULL;
2547 #ifndef OPENSSL_NO_SRTP
2548 sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2550 #ifndef OPENSSL_NO_SRP
2551 SSL_CTX_SRP_CTX_free(a);
2553 #ifndef OPENSSL_NO_ENGINE
2554 ENGINE_finish(a->client_cert_engine);
2557 #ifndef OPENSSL_NO_EC
2558 OPENSSL_free(a->tlsext_ecpointformatlist);
2559 OPENSSL_free(a->tlsext_ellipticcurvelist);
2561 OPENSSL_free(a->alpn_client_proto_list);
2563 CRYPTO_THREAD_lock_free(a->lock);
2568 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2570 ctx->default_passwd_callback = cb;
2573 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2575 ctx->default_passwd_callback_userdata = u;
2578 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2580 return ctx->default_passwd_callback;
2583 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2585 return ctx->default_passwd_callback_userdata;
2588 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
2590 s->default_passwd_callback = cb;
2593 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
2595 s->default_passwd_callback_userdata = u;
2598 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
2600 return s->default_passwd_callback;
2603 void *SSL_get_default_passwd_cb_userdata(SSL *s)
2605 return s->default_passwd_callback_userdata;
2608 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2609 int (*cb) (X509_STORE_CTX *, void *),
2612 ctx->app_verify_callback = cb;
2613 ctx->app_verify_arg = arg;
2616 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
2617 int (*cb) (int, X509_STORE_CTX *))
2619 ctx->verify_mode = mode;
2620 ctx->default_verify_callback = cb;
2623 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2625 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2628 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
2631 ssl_cert_set_cert_cb(c->cert, cb, arg);
2634 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
2636 ssl_cert_set_cert_cb(s->cert, cb, arg);
2639 void ssl_set_masks(SSL *s)
2641 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_GOST)
2645 uint32_t *pvalid = s->s3->tmp.valid_flags;
2646 int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
2647 unsigned long mask_k, mask_a;
2648 #ifndef OPENSSL_NO_EC
2649 int have_ecc_cert, ecdsa_ok;
2655 #ifndef OPENSSL_NO_DH
2656 dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
2661 rsa_enc = pvalid[SSL_PKEY_RSA_ENC] & CERT_PKEY_VALID;
2662 rsa_sign = pvalid[SSL_PKEY_RSA_SIGN] & CERT_PKEY_SIGN;
2663 dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_SIGN;
2664 #ifndef OPENSSL_NO_EC
2665 have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
2671 fprintf(stderr, "dht=%d re=%d rs=%d ds=%d\n",
2672 dh_tmp, rsa_enc, rsa_sign, dsa_sign);
2675 #ifndef OPENSSL_NO_GOST
2676 cpk = &(c->pkeys[SSL_PKEY_GOST12_512]);
2677 if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2678 mask_k |= SSL_kGOST;
2679 mask_a |= SSL_aGOST12;
2681 cpk = &(c->pkeys[SSL_PKEY_GOST12_256]);
2682 if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2683 mask_k |= SSL_kGOST;
2684 mask_a |= SSL_aGOST12;
2686 cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2687 if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2688 mask_k |= SSL_kGOST;
2689 mask_a |= SSL_aGOST01;
2699 if (rsa_enc || rsa_sign) {
2707 mask_a |= SSL_aNULL;
2710 * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
2711 * depending on the key usage extension.
2713 #ifndef OPENSSL_NO_EC
2714 if (have_ecc_cert) {
2716 cpk = &c->pkeys[SSL_PKEY_ECC];
2718 ex_kusage = X509_get_key_usage(x);
2719 ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
2720 if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
2723 mask_a |= SSL_aECDSA;
2727 #ifndef OPENSSL_NO_EC
2728 mask_k |= SSL_kECDHE;
2731 #ifndef OPENSSL_NO_PSK
2734 if (mask_k & SSL_kRSA)
2735 mask_k |= SSL_kRSAPSK;
2736 if (mask_k & SSL_kDHE)
2737 mask_k |= SSL_kDHEPSK;
2738 if (mask_k & SSL_kECDHE)
2739 mask_k |= SSL_kECDHEPSK;
2742 s->s3->tmp.mask_k = mask_k;
2743 s->s3->tmp.mask_a = mask_a;
2746 #ifndef OPENSSL_NO_EC
2748 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2750 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
2751 /* key usage, if present, must allow signing */
2752 if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
2753 SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2754 SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2758 return 1; /* all checks are ok */
2763 static int ssl_get_server_cert_index(const SSL *s)
2766 idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
2767 if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
2768 idx = SSL_PKEY_RSA_SIGN;
2769 if (idx == SSL_PKEY_GOST_EC) {
2770 if (s->cert->pkeys[SSL_PKEY_GOST12_512].x509)
2771 idx = SSL_PKEY_GOST12_512;
2772 else if (s->cert->pkeys[SSL_PKEY_GOST12_256].x509)
2773 idx = SSL_PKEY_GOST12_256;
2774 else if (s->cert->pkeys[SSL_PKEY_GOST01].x509)
2775 idx = SSL_PKEY_GOST01;
2780 SSLerr(SSL_F_SSL_GET_SERVER_CERT_INDEX, ERR_R_INTERNAL_ERROR);
2784 CERT_PKEY *ssl_get_server_send_pkey(SSL *s)
2790 if (!s->s3 || !s->s3->tmp.new_cipher)
2794 i = ssl_get_server_cert_index(s);
2796 /* This may or may not be an error. */
2801 return &c->pkeys[i];
2804 EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher,
2807 unsigned long alg_a;
2811 alg_a = cipher->algorithm_auth;
2814 if ((alg_a & SSL_aDSS) &&
2815 (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2816 idx = SSL_PKEY_DSA_SIGN;
2817 else if (alg_a & SSL_aRSA) {
2818 if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2819 idx = SSL_PKEY_RSA_SIGN;
2820 else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2821 idx = SSL_PKEY_RSA_ENC;
2822 } else if ((alg_a & SSL_aECDSA) &&
2823 (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2826 SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2830 *pmd = s->s3->tmp.md[idx];
2831 return c->pkeys[idx].privatekey;
2834 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
2835 size_t *serverinfo_length)
2839 *serverinfo_length = 0;
2842 i = ssl_get_server_cert_index(s);
2846 if (c->pkeys[i].serverinfo == NULL)
2849 *serverinfo = c->pkeys[i].serverinfo;
2850 *serverinfo_length = c->pkeys[i].serverinfo_length;
2854 void ssl_update_cache(SSL *s, int mode)
2859 * If the session_id_length is 0, we are not supposed to cache it, and it
2860 * would be rather hard to do anyway :-)
2862 if (s->session->session_id_length == 0)
2865 i = s->session_ctx->session_cache_mode;
2866 if ((i & mode) && (!s->hit)
2867 && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2868 || SSL_CTX_add_session(s->session_ctx, s->session))
2869 && (s->session_ctx->new_session_cb != NULL)) {
2870 SSL_SESSION_up_ref(s->session);
2871 if (!s->session_ctx->new_session_cb(s, s->session))
2872 SSL_SESSION_free(s->session);
2875 /* auto flush every 255 connections */
2876 if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
2877 if ((((mode & SSL_SESS_CACHE_CLIENT)
2878 ? s->session_ctx->stats.sess_connect_good
2879 : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
2880 SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
2885 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
2890 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
2895 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2899 if (s->method != meth) {
2900 const SSL_METHOD *sm = s->method;
2901 int (*hf)(SSL *) = s->handshake_func;
2903 if (sm->version == meth->version)
2908 ret = s->method->ssl_new(s);
2911 if (hf == sm->ssl_connect)
2912 s->handshake_func = meth->ssl_connect;
2913 else if (hf == sm->ssl_accept)
2914 s->handshake_func = meth->ssl_accept;
2919 int SSL_get_error(const SSL *s, int i)
2926 return (SSL_ERROR_NONE);
2929 * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
2930 * where we do encode the error
2932 if ((l = ERR_peek_error()) != 0) {
2933 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2934 return (SSL_ERROR_SYSCALL);
2936 return (SSL_ERROR_SSL);
2939 if ((i < 0) && SSL_want_read(s)) {
2940 bio = SSL_get_rbio(s);
2941 if (BIO_should_read(bio))
2942 return (SSL_ERROR_WANT_READ);
2943 else if (BIO_should_write(bio))
2945 * This one doesn't make too much sense ... We never try to write
2946 * to the rbio, and an application program where rbio and wbio
2947 * are separate couldn't even know what it should wait for.
2948 * However if we ever set s->rwstate incorrectly (so that we have
2949 * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
2950 * wbio *are* the same, this test works around that bug; so it
2951 * might be safer to keep it.
2953 return (SSL_ERROR_WANT_WRITE);
2954 else if (BIO_should_io_special(bio)) {
2955 reason = BIO_get_retry_reason(bio);
2956 if (reason == BIO_RR_CONNECT)
2957 return (SSL_ERROR_WANT_CONNECT);
2958 else if (reason == BIO_RR_ACCEPT)
2959 return (SSL_ERROR_WANT_ACCEPT);
2961 return (SSL_ERROR_SYSCALL); /* unknown */
2965 if ((i < 0) && SSL_want_write(s)) {
2966 bio = SSL_get_wbio(s);
2967 if (BIO_should_write(bio))
2968 return (SSL_ERROR_WANT_WRITE);
2969 else if (BIO_should_read(bio))
2971 * See above (SSL_want_read(s) with BIO_should_write(bio))
2973 return (SSL_ERROR_WANT_READ);
2974 else if (BIO_should_io_special(bio)) {
2975 reason = BIO_get_retry_reason(bio);
2976 if (reason == BIO_RR_CONNECT)
2977 return (SSL_ERROR_WANT_CONNECT);
2978 else if (reason == BIO_RR_ACCEPT)
2979 return (SSL_ERROR_WANT_ACCEPT);
2981 return (SSL_ERROR_SYSCALL);
2984 if ((i < 0) && SSL_want_x509_lookup(s)) {
2985 return (SSL_ERROR_WANT_X509_LOOKUP);
2987 if ((i < 0) && SSL_want_async(s)) {
2988 return SSL_ERROR_WANT_ASYNC;
2992 if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2993 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2994 return (SSL_ERROR_ZERO_RETURN);
2996 return (SSL_ERROR_SYSCALL);
2999 static int ssl_do_handshake_intern(void *vargs)
3001 struct ssl_async_args *args;
3004 args = (struct ssl_async_args *)vargs;
3007 return s->handshake_func(s);
3010 int SSL_do_handshake(SSL *s)
3014 if (s->handshake_func == NULL) {
3015 SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3019 s->method->ssl_renegotiate_check(s);
3021 if (SSL_in_init(s) || SSL_in_before(s)) {
3022 if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3023 struct ssl_async_args args;
3027 ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3029 ret = s->handshake_func(s);
3035 void SSL_set_accept_state(SSL *s)
3039 ossl_statem_clear(s);
3040 s->handshake_func = s->method->ssl_accept;
3044 void SSL_set_connect_state(SSL *s)
3048 ossl_statem_clear(s);
3049 s->handshake_func = s->method->ssl_connect;
3053 int ssl_undefined_function(SSL *s)
3055 SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3059 int ssl_undefined_void_function(void)
3061 SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3062 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3066 int ssl_undefined_const_function(const SSL *s)
3071 const SSL_METHOD *ssl_bad_method(int ver)
3073 SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3077 const char *ssl_protocol_to_string(int version)
3079 if (version == TLS1_2_VERSION)
3081 else if (version == TLS1_1_VERSION)
3083 else if (version == TLS1_VERSION)
3085 else if (version == SSL3_VERSION)
3087 else if (version == DTLS1_BAD_VER)
3089 else if (version == DTLS1_VERSION)
3091 else if (version == DTLS1_2_VERSION)
3097 const char *SSL_get_version(const SSL *s)
3099 return ssl_protocol_to_string(s->version);
3102 SSL *SSL_dup(SSL *s)
3104 STACK_OF(X509_NAME) *sk;
3109 /* If we're not quiescent, just up_ref! */
3110 if (!SSL_in_init(s) || !SSL_in_before(s)) {
3111 CRYPTO_atomic_add(&s->references, 1, &i, s->lock);
3116 * Otherwise, copy configuration state, and session if set.
3118 if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3121 if (s->session != NULL) {
3123 * Arranges to share the same session via up_ref. This "copies"
3124 * session-id, SSL_METHOD, sid_ctx, and 'cert'
3126 if (!SSL_copy_session_id(ret, s))
3130 * No session has been established yet, so we have to expect that
3131 * s->cert or ret->cert will be changed later -- they should not both
3132 * point to the same object, and thus we can't use
3133 * SSL_copy_session_id.
3135 if (!SSL_set_ssl_method(ret, s->method))
3138 if (s->cert != NULL) {
3139 ssl_cert_free(ret->cert);
3140 ret->cert = ssl_cert_dup(s->cert);
3141 if (ret->cert == NULL)
3145 if (!SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length))
3149 if (!ssl_dane_dup(ret, s))
3151 ret->version = s->version;
3152 ret->options = s->options;
3153 ret->mode = s->mode;
3154 SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3155 SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3156 ret->msg_callback = s->msg_callback;
3157 ret->msg_callback_arg = s->msg_callback_arg;
3158 SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3159 SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
3160 ret->generate_session_id = s->generate_session_id;
3162 SSL_set_info_callback(ret, SSL_get_info_callback(s));
3164 /* copy app data, a little dangerous perhaps */
3165 if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
3168 /* setup rbio, and wbio */
3169 if (s->rbio != NULL) {
3170 if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
3173 if (s->wbio != NULL) {
3174 if (s->wbio != s->rbio) {
3175 if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
3178 ret->wbio = ret->rbio;
3181 ret->server = s->server;
3182 if (s->handshake_func) {
3184 SSL_set_accept_state(ret);
3186 SSL_set_connect_state(ret);
3188 ret->shutdown = s->shutdown;
3191 ret->default_passwd_callback = s->default_passwd_callback;
3192 ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
3194 X509_VERIFY_PARAM_inherit(ret->param, s->param);
3196 /* dup the cipher_list and cipher_list_by_id stacks */
3197 if (s->cipher_list != NULL) {
3198 if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
3201 if (s->cipher_list_by_id != NULL)
3202 if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
3206 /* Dup the client_CA list */
3207 if (s->client_CA != NULL) {
3208 if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
3210 ret->client_CA = sk;
3211 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
3212 xn = sk_X509_NAME_value(sk, i);
3213 if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
3226 void ssl_clear_cipher_ctx(SSL *s)
3228 if (s->enc_read_ctx != NULL) {
3229 EVP_CIPHER_CTX_free(s->enc_read_ctx);
3230 s->enc_read_ctx = NULL;
3232 if (s->enc_write_ctx != NULL) {
3233 EVP_CIPHER_CTX_free(s->enc_write_ctx);
3234 s->enc_write_ctx = NULL;
3236 #ifndef OPENSSL_NO_COMP
3237 COMP_CTX_free(s->expand);
3239 COMP_CTX_free(s->compress);
3244 X509 *SSL_get_certificate(const SSL *s)
3246 if (s->cert != NULL)
3247 return (s->cert->key->x509);
3252 EVP_PKEY *SSL_get_privatekey(const SSL *s)
3254 if (s->cert != NULL)
3255 return (s->cert->key->privatekey);
3260 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3262 if (ctx->cert != NULL)
3263 return ctx->cert->key->x509;
3268 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3270 if (ctx->cert != NULL)
3271 return ctx->cert->key->privatekey;
3276 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
3278 if ((s->session != NULL) && (s->session->cipher != NULL))
3279 return (s->session->cipher);
3283 const COMP_METHOD *SSL_get_current_compression(SSL *s)
3285 #ifndef OPENSSL_NO_COMP
3286 return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
3292 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
3294 #ifndef OPENSSL_NO_COMP
3295 return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
3301 int ssl_init_wbio_buffer(SSL *s, int push)
3305 if (s->bbio == NULL) {
3306 bbio = BIO_new(BIO_f_buffer());
3312 if (s->bbio == s->wbio)
3313 s->wbio = BIO_pop(s->wbio);
3315 (void)BIO_reset(bbio);
3316 /* if (!BIO_set_write_buffer_size(bbio,16*1024)) */
3317 if (!BIO_set_read_buffer_size(bbio, 1)) {
3318 SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
3322 if (s->wbio != bbio)
3323 s->wbio = BIO_push(bbio, s->wbio);
3325 if (s->wbio == bbio)
3326 s->wbio = BIO_pop(bbio);
3331 void ssl_free_wbio_buffer(SSL *s)
3333 /* callers ensure s is never null */
3334 if (s->bbio == NULL)
3337 if (s->bbio == s->wbio) {
3338 /* remove buffering */
3339 s->wbio = BIO_pop(s->wbio);
3340 assert(s->wbio != NULL);
3346 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3348 ctx->quiet_shutdown = mode;
3351 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3353 return (ctx->quiet_shutdown);
3356 void SSL_set_quiet_shutdown(SSL *s, int mode)
3358 s->quiet_shutdown = mode;
3361 int SSL_get_quiet_shutdown(const SSL *s)
3363 return (s->quiet_shutdown);
3366 void SSL_set_shutdown(SSL *s, int mode)
3371 int SSL_get_shutdown(const SSL *s)
3373 return (s->shutdown);
3376 int SSL_version(const SSL *s)
3378 return (s->version);
3381 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3386 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3389 if (ssl->ctx == ctx)
3392 ctx = ssl->initial_ctx;
3393 new_cert = ssl_cert_dup(ctx->cert);
3394 if (new_cert == NULL) {
3397 ssl_cert_free(ssl->cert);
3398 ssl->cert = new_cert;
3401 * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3402 * so setter APIs must prevent invalid lengths from entering the system.
3404 OPENSSL_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
3407 * If the session ID context matches that of the parent SSL_CTX,
3408 * inherit it from the new SSL_CTX as well. If however the context does
3409 * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3410 * leave it unchanged.
3412 if ((ssl->ctx != NULL) &&
3413 (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3414 (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3415 ssl->sid_ctx_length = ctx->sid_ctx_length;
3416 memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3419 SSL_CTX_up_ref(ctx);
3420 SSL_CTX_free(ssl->ctx); /* decrement reference count */
3426 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3428 return (X509_STORE_set_default_paths(ctx->cert_store));
3431 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
3433 X509_LOOKUP *lookup;
3435 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
3438 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
3440 /* Clear any errors if the default directory does not exist */
3446 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
3448 X509_LOOKUP *lookup;
3450 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
3454 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
3456 /* Clear any errors if the default file does not exist */
3462 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3465 return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3468 void SSL_set_info_callback(SSL *ssl,
3469 void (*cb) (const SSL *ssl, int type, int val))
3471 ssl->info_callback = cb;
3475 * One compiler (Diab DCC) doesn't like argument names in returned function
3478 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3481 return ssl->info_callback;
3484 void SSL_set_verify_result(SSL *ssl, long arg)
3486 ssl->verify_result = arg;
3489 long SSL_get_verify_result(const SSL *ssl)
3491 return (ssl->verify_result);
3494 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
3497 return sizeof(ssl->s3->client_random);
3498 if (outlen > sizeof(ssl->s3->client_random))
3499 outlen = sizeof(ssl->s3->client_random);
3500 memcpy(out, ssl->s3->client_random, outlen);
3504 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
3507 return sizeof(ssl->s3->server_random);
3508 if (outlen > sizeof(ssl->s3->server_random))
3509 outlen = sizeof(ssl->s3->server_random);
3510 memcpy(out, ssl->s3->server_random, outlen);
3514 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
3515 unsigned char *out, size_t outlen)
3517 if (session->master_key_length < 0) {
3518 /* Should never happen */
3522 return session->master_key_length;
3523 if (outlen > (size_t)session->master_key_length)
3524 outlen = session->master_key_length;
3525 memcpy(out, session->master_key, outlen);
3529 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3531 return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3534 void *SSL_get_ex_data(const SSL *s, int idx)
3536 return (CRYPTO_get_ex_data(&s->ex_data, idx));
3539 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3541 return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3544 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3546 return (CRYPTO_get_ex_data(&s->ex_data, idx));
3554 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3556 return (ctx->cert_store);
3559 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3561 X509_STORE_free(ctx->cert_store);
3562 ctx->cert_store = store;
3565 int SSL_want(const SSL *s)
3567 return (s->rwstate);
3571 * \brief Set the callback for generating temporary DH keys.
3572 * \param ctx the SSL context.
3573 * \param dh the callback
3576 #ifndef OPENSSL_NO_DH
3577 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3578 DH *(*dh) (SSL *ssl, int is_export,
3581 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3584 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3587 SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3591 #ifndef OPENSSL_NO_PSK
3592 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3594 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3595 SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT,
3596 SSL_R_DATA_LENGTH_TOO_LONG);
3599 OPENSSL_free(ctx->cert->psk_identity_hint);
3600 if (identity_hint != NULL) {
3601 ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3602 if (ctx->cert->psk_identity_hint == NULL)
3605 ctx->cert->psk_identity_hint = NULL;
3609 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3614 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3615 SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3618 OPENSSL_free(s->cert->psk_identity_hint);
3619 if (identity_hint != NULL) {
3620 s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3621 if (s->cert->psk_identity_hint == NULL)
3624 s->cert->psk_identity_hint = NULL;
3628 const char *SSL_get_psk_identity_hint(const SSL *s)
3630 if (s == NULL || s->session == NULL)
3632 return (s->session->psk_identity_hint);
3635 const char *SSL_get_psk_identity(const SSL *s)
3637 if (s == NULL || s->session == NULL)
3639 return (s->session->psk_identity);
3642 void SSL_set_psk_client_callback(SSL *s,
3643 unsigned int (*cb) (SSL *ssl,
3652 s->psk_client_callback = cb;
3655 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3656 unsigned int (*cb) (SSL *ssl,
3665 ctx->psk_client_callback = cb;
3668 void SSL_set_psk_server_callback(SSL *s,
3669 unsigned int (*cb) (SSL *ssl,
3670 const char *identity,
3675 s->psk_server_callback = cb;
3678 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3679 unsigned int (*cb) (SSL *ssl,
3680 const char *identity,
3685 ctx->psk_server_callback = cb;
3689 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
3690 void (*cb) (int write_p, int version,
3691 int content_type, const void *buf,
3692 size_t len, SSL *ssl, void *arg))
3694 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3697 void SSL_set_msg_callback(SSL *ssl,
3698 void (*cb) (int write_p, int version,
3699 int content_type, const void *buf,
3700 size_t len, SSL *ssl, void *arg))
3702 SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3705 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
3706 int (*cb) (SSL *ssl,
3710 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3711 (void (*)(void))cb);
3714 void SSL_set_not_resumable_session_callback(SSL *ssl,
3715 int (*cb) (SSL *ssl,
3716 int is_forward_secure))
3718 SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3719 (void (*)(void))cb);
3723 * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3724 * vairable, freeing EVP_MD_CTX previously stored in that variable, if any.
3725 * If EVP_MD pointer is passed, initializes ctx with this md Returns newly
3729 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3731 ssl_clear_hash_ctx(hash);
3732 *hash = EVP_MD_CTX_new();
3733 if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
3734 EVP_MD_CTX_free(*hash);
3741 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3745 EVP_MD_CTX_free(*hash);
3749 /* Retrieve handshake hashes */
3750 int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen)
3752 EVP_MD_CTX *ctx = NULL;
3753 EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
3754 int ret = EVP_MD_CTX_size(hdgst);
3755 if (ret < 0 || ret > outlen) {
3759 ctx = EVP_MD_CTX_new();
3764 if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
3765 || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
3768 EVP_MD_CTX_free(ctx);
3772 int SSL_session_reused(SSL *s)
3777 int SSL_is_server(SSL *s)
3782 #if OPENSSL_API_COMPAT < 0x10100000L
3783 void SSL_set_debug(SSL *s, int debug)
3785 /* Old function was do-nothing anyway... */
3792 void SSL_set_security_level(SSL *s, int level)
3794 s->cert->sec_level = level;
3797 int SSL_get_security_level(const SSL *s)
3799 return s->cert->sec_level;
3802 void SSL_set_security_callback(SSL *s,
3803 int (*cb) (const SSL *s, const SSL_CTX *ctx, int op,
3804 int bits, int nid, void *other,
3807 s->cert->sec_cb = cb;
3810 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s, const SSL_CTX *ctx, int op,
3812 void *other, void *ex) {
3813 return s->cert->sec_cb;
3816 void SSL_set0_security_ex_data(SSL *s, void *ex)
3818 s->cert->sec_ex = ex;
3821 void *SSL_get0_security_ex_data(const SSL *s)
3823 return s->cert->sec_ex;
3826 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
3828 ctx->cert->sec_level = level;
3831 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
3833 return ctx->cert->sec_level;
3836 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
3837 int (*cb) (const SSL *s, const SSL_CTX *ctx, int op,
3838 int bits, int nid, void *other,
3841 ctx->cert->sec_cb = cb;
3844 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
3850 return ctx->cert->sec_cb;
3853 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
3855 ctx->cert->sec_ex = ex;
3858 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
3860 return ctx->cert->sec_ex;
3865 * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
3866 * can return unsigned long, instead of the generic long return value from the
3867 * control interface.
3869 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
3871 return ctx->options;
3873 unsigned long SSL_get_options(const SSL* s)
3877 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
3879 return ctx->options |= op;
3881 unsigned long SSL_set_options(SSL *s, unsigned long op)
3883 return s->options |= op;
3885 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
3887 return ctx->options &= ~op;
3889 unsigned long SSL_clear_options(SSL *s, unsigned long op)
3891 return s->options &= ~op;
3894 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
3896 return s->verified_chain;
3899 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
3901 #ifndef OPENSSL_NO_CT
3904 * Moves SCTs from the |src| stack to the |dst| stack.
3905 * The source of each SCT will be set to |origin|.
3906 * If |dst| points to a NULL pointer, a new stack will be created and owned by
3908 * Returns the number of SCTs moved, or a negative integer if an error occurs.
3910 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src, sct_source_t origin)
3916 *dst = sk_SCT_new_null();
3918 SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
3923 while ((sct = sk_SCT_pop(src)) != NULL) {
3924 if (SCT_set_source(sct, origin) != 1)
3927 if (sk_SCT_push(*dst, sct) <= 0)
3935 sk_SCT_push(src, sct); /* Put the SCT back */
3940 * Look for data collected during ServerHello and parse if found.
3941 * Return 1 on success, 0 on failure.
3943 static int ct_extract_tls_extension_scts(SSL *s)
3945 int scts_extracted = 0;
3947 if (s->tlsext_scts != NULL) {
3948 const unsigned char *p = s->tlsext_scts;
3949 STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->tlsext_scts_len);
3951 scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
3953 SCT_LIST_free(scts);
3956 return scts_extracted;
3960 * Checks for an OCSP response and then attempts to extract any SCTs found if it
3961 * contains an SCT X509 extension. They will be stored in |s->scts|.
3963 * - The number of SCTs extracted, assuming an OCSP response exists.
3964 * - 0 if no OCSP response exists or it contains no SCTs.
3965 * - A negative integer if an error occurs.
3967 static int ct_extract_ocsp_response_scts(SSL *s)
3969 #ifndef OPENSSL_NO_OCSP
3970 int scts_extracted = 0;
3971 const unsigned char *p;
3972 OCSP_BASICRESP *br = NULL;
3973 OCSP_RESPONSE *rsp = NULL;
3974 STACK_OF(SCT) *scts = NULL;
3977 if (s->tlsext_ocsp_resp == NULL || s->tlsext_ocsp_resplen == 0)
3980 p = s->tlsext_ocsp_resp;
3981 rsp = d2i_OCSP_RESPONSE(NULL, &p, s->tlsext_ocsp_resplen);
3985 br = OCSP_response_get1_basic(rsp);
3989 for (i = 0; i < OCSP_resp_count(br); ++i) {
3990 OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
3995 scts = OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
3996 scts_extracted = ct_move_scts(&s->scts, scts,
3997 SCT_SOURCE_OCSP_STAPLED_RESPONSE);
3998 if (scts_extracted < 0)
4002 SCT_LIST_free(scts);
4003 OCSP_BASICRESP_free(br);
4004 OCSP_RESPONSE_free(rsp);
4005 return scts_extracted;
4007 /* Behave as if no OCSP response exists */
4013 * Attempts to extract SCTs from the peer certificate.
4014 * Return the number of SCTs extracted, or a negative integer if an error
4017 static int ct_extract_x509v3_extension_scts(SSL *s)
4019 int scts_extracted = 0;
4020 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4023 STACK_OF(SCT) *scts =
4024 X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
4027 ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
4029 SCT_LIST_free(scts);
4032 return scts_extracted;
4036 * Attempts to find all received SCTs by checking TLS extensions, the OCSP
4037 * response (if it exists) and X509v3 extensions in the certificate.
4038 * Returns NULL if an error occurs.
4040 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
4042 if (!s->scts_parsed) {
4043 if (ct_extract_tls_extension_scts(s) < 0 ||
4044 ct_extract_ocsp_response_scts(s) < 0 ||
4045 ct_extract_x509v3_extension_scts(s) < 0)
4055 static int ct_permissive(const CT_POLICY_EVAL_CTX *ctx,
4056 const STACK_OF(SCT) *scts, void *unused_arg)
4061 static int ct_strict(const CT_POLICY_EVAL_CTX *ctx,
4062 const STACK_OF(SCT) *scts, void *unused_arg)
4064 int count = scts != NULL ? sk_SCT_num(scts) : 0;
4067 for (i = 0; i < count; ++i) {
4068 SCT *sct = sk_SCT_value(scts, i);
4069 int status = SCT_get_validation_status(sct);
4071 if (status == SCT_VALIDATION_STATUS_VALID)
4074 SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
4078 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
4082 * Since code exists that uses the custom extension handler for CT, look
4083 * for this and throw an error if they have already registered to use CT.
4085 if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
4086 TLSEXT_TYPE_signed_certificate_timestamp)) {
4087 SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
4088 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4092 if (callback != NULL) {
4093 /* If we are validating CT, then we MUST accept SCTs served via OCSP */
4094 if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
4098 s->ct_validation_callback = callback;
4099 s->ct_validation_callback_arg = arg;
4104 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
4105 ssl_ct_validation_cb callback,
4109 * Since code exists that uses the custom extension handler for CT, look for
4110 * this and throw an error if they have already registered to use CT.
4112 if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
4113 TLSEXT_TYPE_signed_certificate_timestamp)) {
4114 SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
4115 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4119 ctx->ct_validation_callback = callback;
4120 ctx->ct_validation_callback_arg = arg;
4124 int SSL_ct_is_enabled(const SSL *s)
4126 return s->ct_validation_callback != NULL;
4129 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
4131 return ctx->ct_validation_callback != NULL;
4134 int ssl_validate_ct(SSL *s)
4137 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4139 SSL_DANE *dane = &s->dane;
4140 CT_POLICY_EVAL_CTX *ctx = NULL;
4141 const STACK_OF(SCT) *scts;
4144 * If no callback is set, the peer is anonymous, or its chain is invalid,
4145 * skip SCT validation - just return success. Applications that continue
4146 * handshakes without certificates, with unverified chains, or pinned leaf
4147 * certificates are outside the scope of the WebPKI and CT.
4149 * The above exclusions notwithstanding the vast majority of peers will
4150 * have rather ordinary certificate chains validated by typical
4151 * applications that perform certificate verification and therefore will
4152 * process SCTs when enabled.
4154 if (s->ct_validation_callback == NULL || cert == NULL ||
4155 s->verify_result != X509_V_OK ||
4156 s->verified_chain == NULL ||
4157 sk_X509_num(s->verified_chain) <= 1)
4161 * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
4162 * trust-anchors. See https://tools.ietf.org/html/rfc7671#section-4.2
4164 if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
4165 switch (dane->mtlsa->usage) {
4166 case DANETLS_USAGE_DANE_TA:
4167 case DANETLS_USAGE_DANE_EE:
4172 ctx = CT_POLICY_EVAL_CTX_new();
4174 SSLerr(SSL_F_SSL_VALIDATE_CT, ERR_R_MALLOC_FAILURE);
4178 issuer = sk_X509_value(s->verified_chain, 1);
4179 CT_POLICY_EVAL_CTX_set0_cert(ctx, cert);
4180 CT_POLICY_EVAL_CTX_set0_issuer(ctx, issuer);
4181 CT_POLICY_EVAL_CTX_set0_log_store(ctx, s->ctx->ctlog_store);
4183 scts = SSL_get0_peer_scts(s);
4186 * This function returns success (> 0) only when all the SCTs are valid, 0
4187 * when some are invalid, and < 0 on various internal errors (out of
4188 * memory, etc.). Having some, or even all, invalid SCTs is not sufficient
4189 * reason to abort the handshake, that decision is up to the callback.
4190 * Therefore, we error out only in the unexpected case that the return
4191 * value is negative.
4193 * XXX: One might well argue that the return value of this function is an
4194 * unforunate design choice. Its job is only to determine the validation
4195 * status of each of the provided SCTs. So long as it correctly separates
4196 * the wheat from the chaff it should return success. Failure in this case
4197 * ought to correspond to an inability to carry out its duties.
4199 if (SCT_LIST_validate(scts, ctx) < 0) {
4200 SSLerr(SSL_F_SSL_VALIDATE_CT, SSL_R_SCT_VERIFICATION_FAILED);
4204 ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
4206 ret = 0; /* This function returns 0 on failure */
4209 CT_POLICY_EVAL_CTX_free(ctx);
4213 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
4215 switch (validation_mode) {
4217 SSLerr(SSL_F_SSL_CTX_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4219 case SSL_CT_VALIDATION_PERMISSIVE:
4220 return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
4221 case SSL_CT_VALIDATION_STRICT:
4222 return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
4226 int SSL_enable_ct(SSL *s, int validation_mode)
4228 switch (validation_mode) {
4230 SSLerr(SSL_F_SSL_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4232 case SSL_CT_VALIDATION_PERMISSIVE:
4233 return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
4234 case SSL_CT_VALIDATION_STRICT:
4235 return SSL_set_ct_validation_callback(s, ct_strict, NULL);
4239 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
4241 return CTLOG_STORE_load_default_file(ctx->ctlog_store);
4244 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
4246 return CTLOG_STORE_load_file(ctx->ctlog_store, path);
4249 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs)
4251 CTLOG_STORE_free(ctx->ctlog_store);
4252 ctx->ctlog_store = logs;
4255 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
4257 return ctx->ctlog_store;