2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
6 * Licensed under the OpenSSL license (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
14 #include <openssl/objects.h>
15 #include <openssl/lhash.h>
16 #include <openssl/x509v3.h>
17 #include <openssl/rand.h>
18 #include <openssl/ocsp.h>
19 #include <openssl/dh.h>
20 #include <openssl/engine.h>
21 #include <openssl/async.h>
22 #include <openssl/ct.h>
24 const char SSL_version_str[] = OPENSSL_VERSION_TEXT;
26 SSL3_ENC_METHOD ssl3_undef_enc_method = {
28 * evil casts, but these functions are only called if there's a library
31 (int (*)(SSL *, SSL3_RECORD *, size_t, int))ssl_undefined_function,
32 (int (*)(SSL *, SSL3_RECORD *, unsigned char *, int))ssl_undefined_function,
33 ssl_undefined_function,
34 (int (*)(SSL *, unsigned char *, unsigned char *, size_t, size_t *))
35 ssl_undefined_function,
36 (int (*)(SSL *, int))ssl_undefined_function,
37 (size_t (*)(SSL *, const char *, size_t, unsigned char *))
38 ssl_undefined_function,
39 NULL, /* client_finished_label */
40 0, /* client_finished_label_len */
41 NULL, /* server_finished_label */
42 0, /* server_finished_label_len */
43 (int (*)(int))ssl_undefined_function,
44 (int (*)(SSL *, unsigned char *, size_t, const char *,
45 size_t, const unsigned char *, size_t,
46 int use_context))ssl_undefined_function,
49 struct ssl_async_args {
53 enum { READFUNC, WRITEFUNC, OTHERFUNC } type;
55 int (*func_read) (SSL *, void *, size_t, size_t *);
56 int (*func_write) (SSL *, const void *, size_t, size_t *);
57 int (*func_other) (SSL *);
67 DANETLS_MATCHING_FULL, 0, NID_undef
70 DANETLS_MATCHING_2256, 1, NID_sha256
73 DANETLS_MATCHING_2512, 2, NID_sha512
77 static int dane_ctx_enable(struct dane_ctx_st *dctx)
81 uint8_t mdmax = DANETLS_MATCHING_LAST;
82 int n = ((int)mdmax) + 1; /* int to handle PrivMatch(255) */
85 if (dctx->mdevp != NULL)
88 mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
89 mdord = OPENSSL_zalloc(n * sizeof(*mdord));
91 if (mdord == NULL || mdevp == NULL) {
94 SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
98 /* Install default entries */
99 for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
102 if (dane_mds[i].nid == NID_undef ||
103 (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
105 mdevp[dane_mds[i].mtype] = md;
106 mdord[dane_mds[i].mtype] = dane_mds[i].ord;
116 static void dane_ctx_final(struct dane_ctx_st *dctx)
118 OPENSSL_free(dctx->mdevp);
121 OPENSSL_free(dctx->mdord);
126 static void tlsa_free(danetls_record *t)
130 OPENSSL_free(t->data);
131 EVP_PKEY_free(t->spki);
135 static void dane_final(SSL_DANE *dane)
137 sk_danetls_record_pop_free(dane->trecs, tlsa_free);
140 sk_X509_pop_free(dane->certs, X509_free);
143 X509_free(dane->mcert);
151 * dane_copy - Copy dane configuration, sans verification state.
153 static int ssl_dane_dup(SSL *to, SSL *from)
158 if (!DANETLS_ENABLED(&from->dane))
161 dane_final(&to->dane);
162 to->dane.flags = from->dane.flags;
163 to->dane.dctx = &to->ctx->dane;
164 to->dane.trecs = sk_danetls_record_new_null();
166 if (to->dane.trecs == NULL) {
167 SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
171 num = sk_danetls_record_num(from->dane.trecs);
172 for (i = 0; i < num; ++i) {
173 danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
175 if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
176 t->data, t->dlen) <= 0)
182 static int dane_mtype_set(struct dane_ctx_st *dctx,
183 const EVP_MD *md, uint8_t mtype, uint8_t ord)
187 if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
188 SSLerr(SSL_F_DANE_MTYPE_SET, SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
192 if (mtype > dctx->mdmax) {
193 const EVP_MD **mdevp;
195 int n = ((int)mtype) + 1;
197 mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
199 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
204 mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
206 SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
211 /* Zero-fill any gaps */
212 for (i = dctx->mdmax + 1; i < mtype; ++i) {
220 dctx->mdevp[mtype] = md;
221 /* Coerce ordinal of disabled matching types to 0 */
222 dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
227 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
229 if (mtype > dane->dctx->mdmax)
231 return dane->dctx->mdevp[mtype];
234 static int dane_tlsa_add(SSL_DANE *dane,
237 uint8_t mtype, unsigned char *data, size_t dlen)
240 const EVP_MD *md = NULL;
241 int ilen = (int)dlen;
245 if (dane->trecs == NULL) {
246 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
250 if (ilen < 0 || dlen != (size_t)ilen) {
251 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
255 if (usage > DANETLS_USAGE_LAST) {
256 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
260 if (selector > DANETLS_SELECTOR_LAST) {
261 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
265 if (mtype != DANETLS_MATCHING_FULL) {
266 md = tlsa_md_get(dane, mtype);
268 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
273 if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
274 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
278 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
282 if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
283 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
288 t->selector = selector;
290 t->data = OPENSSL_malloc(dlen);
291 if (t->data == NULL) {
293 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
296 memcpy(t->data, data, dlen);
299 /* Validate and cache full certificate or public key */
300 if (mtype == DANETLS_MATCHING_FULL) {
301 const unsigned char *p = data;
303 EVP_PKEY *pkey = NULL;
306 case DANETLS_SELECTOR_CERT:
307 if (!d2i_X509(&cert, &p, ilen) || p < data ||
308 dlen != (size_t)(p - data)) {
310 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
313 if (X509_get0_pubkey(cert) == NULL) {
315 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
319 if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
325 * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
326 * records that contain full certificates of trust-anchors that are
327 * not present in the wire chain. For usage PKIX-TA(0), we augment
328 * the chain with untrusted Full(0) certificates from DNS, in case
329 * they are missing from the chain.
331 if ((dane->certs == NULL &&
332 (dane->certs = sk_X509_new_null()) == NULL) ||
333 !sk_X509_push(dane->certs, cert)) {
334 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
341 case DANETLS_SELECTOR_SPKI:
342 if (!d2i_PUBKEY(&pkey, &p, ilen) || p < data ||
343 dlen != (size_t)(p - data)) {
345 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
350 * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
351 * records that contain full bare keys of trust-anchors that are
352 * not present in the wire chain.
354 if (usage == DANETLS_USAGE_DANE_TA)
363 * Find the right insertion point for the new record.
365 * See crypto/x509/x509_vfy.c. We sort DANE-EE(3) records first, so that
366 * they can be processed first, as they require no chain building, and no
367 * expiration or hostname checks. Because DANE-EE(3) is numerically
368 * largest, this is accomplished via descending sort by "usage".
370 * We also sort in descending order by matching ordinal to simplify
371 * the implementation of digest agility in the verification code.
373 * The choice of order for the selector is not significant, so we
374 * use the same descending order for consistency.
376 num = sk_danetls_record_num(dane->trecs);
377 for (i = 0; i < num; ++i) {
378 danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
380 if (rec->usage > usage)
382 if (rec->usage < usage)
384 if (rec->selector > selector)
386 if (rec->selector < selector)
388 if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
393 if (!sk_danetls_record_insert(dane->trecs, t, i)) {
395 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
398 dane->umask |= DANETLS_USAGE_BIT(usage);
403 static void clear_ciphers(SSL *s)
405 /* clear the current cipher */
406 ssl_clear_cipher_ctx(s);
407 ssl_clear_hash_ctx(&s->read_hash);
408 ssl_clear_hash_ctx(&s->write_hash);
411 int SSL_clear(SSL *s)
413 if (s->method == NULL) {
414 SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
418 if (ssl_clear_bad_session(s)) {
419 SSL_SESSION_free(s->session);
422 SSL_SESSION_free(s->psksession);
423 s->psksession = NULL;
429 if (s->renegotiate) {
430 SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
434 ossl_statem_clear(s);
436 s->version = s->method->version;
437 s->client_version = s->version;
438 s->rwstate = SSL_NOTHING;
440 BUF_MEM_free(s->init_buf);
445 s->key_update = SSL_KEY_UPDATE_NONE;
447 /* Reset DANE verification result state */
450 X509_free(s->dane.mcert);
451 s->dane.mcert = NULL;
452 s->dane.mtlsa = NULL;
454 /* Clear the verification result peername */
455 X509_VERIFY_PARAM_move_peername(s->param, NULL);
458 * Check to see if we were changed into a different method, if so, revert
459 * back if we are not doing session-id reuse.
461 if (!ossl_statem_get_in_handshake(s) && (s->session == NULL)
462 && (s->method != s->ctx->method)) {
463 s->method->ssl_free(s);
464 s->method = s->ctx->method;
465 if (!s->method->ssl_new(s))
468 if (!s->method->ssl_clear(s))
472 RECORD_LAYER_clear(&s->rlayer);
477 /** Used to change an SSL_CTXs default SSL method type */
478 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
480 STACK_OF(SSL_CIPHER) *sk;
484 sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
485 &(ctx->cipher_list_by_id),
486 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
487 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
488 SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
494 SSL *SSL_new(SSL_CTX *ctx)
499 SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
502 if (ctx->method == NULL) {
503 SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
507 s = OPENSSL_zalloc(sizeof(*s));
511 s->lock = CRYPTO_THREAD_lock_new();
512 if (s->lock == NULL) {
513 SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
518 RECORD_LAYER_init(&s->rlayer, s);
520 s->options = ctx->options;
521 s->dane.flags = ctx->dane.flags;
522 s->min_proto_version = ctx->min_proto_version;
523 s->max_proto_version = ctx->max_proto_version;
525 s->max_cert_list = ctx->max_cert_list;
527 s->max_early_data = ctx->max_early_data;
530 * Earlier library versions used to copy the pointer to the CERT, not
531 * its contents; only when setting new parameters for the per-SSL
532 * copy, ssl_cert_new would be called (and the direct reference to
533 * the per-SSL_CTX settings would be lost, but those still were
534 * indirectly accessed for various purposes, and for that reason they
535 * used to be known as s->ctx->default_cert). Now we don't look at the
536 * SSL_CTX's CERT after having duplicated it once.
538 s->cert = ssl_cert_dup(ctx->cert);
542 RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
543 s->msg_callback = ctx->msg_callback;
544 s->msg_callback_arg = ctx->msg_callback_arg;
545 s->verify_mode = ctx->verify_mode;
546 s->not_resumable_session_cb = ctx->not_resumable_session_cb;
547 s->record_padding_cb = ctx->record_padding_cb;
548 s->record_padding_arg = ctx->record_padding_arg;
549 s->block_padding = ctx->block_padding;
550 s->sid_ctx_length = ctx->sid_ctx_length;
551 if (!ossl_assert(s->sid_ctx_length <= sizeof s->sid_ctx))
553 memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
554 s->verify_callback = ctx->default_verify_callback;
555 s->generate_session_id = ctx->generate_session_id;
557 s->param = X509_VERIFY_PARAM_new();
558 if (s->param == NULL)
560 X509_VERIFY_PARAM_inherit(s->param, ctx->param);
561 s->quiet_shutdown = ctx->quiet_shutdown;
562 s->max_send_fragment = ctx->max_send_fragment;
563 s->split_send_fragment = ctx->split_send_fragment;
564 s->max_pipelines = ctx->max_pipelines;
565 if (s->max_pipelines > 1)
566 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
567 if (ctx->default_read_buf_len > 0)
568 SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
573 s->ext.debug_arg = NULL;
574 s->ext.ticket_expected = 0;
575 s->ext.status_type = ctx->ext.status_type;
576 s->ext.status_expected = 0;
577 s->ext.ocsp.ids = NULL;
578 s->ext.ocsp.exts = NULL;
579 s->ext.ocsp.resp = NULL;
580 s->ext.ocsp.resp_len = 0;
582 s->session_ctx = ctx;
583 #ifndef OPENSSL_NO_EC
584 if (ctx->ext.ecpointformats) {
585 s->ext.ecpointformats =
586 OPENSSL_memdup(ctx->ext.ecpointformats,
587 ctx->ext.ecpointformats_len);
588 if (!s->ext.ecpointformats)
590 s->ext.ecpointformats_len =
591 ctx->ext.ecpointformats_len;
593 if (ctx->ext.supportedgroups) {
594 s->ext.supportedgroups =
595 OPENSSL_memdup(ctx->ext.supportedgroups,
596 ctx->ext.supportedgroups_len);
597 if (!s->ext.supportedgroups)
599 s->ext.supportedgroups_len = ctx->ext.supportedgroups_len;
602 #ifndef OPENSSL_NO_NEXTPROTONEG
606 if (s->ctx->ext.alpn) {
607 s->ext.alpn = OPENSSL_malloc(s->ctx->ext.alpn_len);
608 if (s->ext.alpn == NULL)
610 memcpy(s->ext.alpn, s->ctx->ext.alpn, s->ctx->ext.alpn_len);
611 s->ext.alpn_len = s->ctx->ext.alpn_len;
614 s->verified_chain = NULL;
615 s->verify_result = X509_V_OK;
617 s->default_passwd_callback = ctx->default_passwd_callback;
618 s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
620 s->method = ctx->method;
622 s->key_update = SSL_KEY_UPDATE_NONE;
624 if (!s->method->ssl_new(s))
627 s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
632 if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data))
635 #ifndef OPENSSL_NO_PSK
636 s->psk_client_callback = ctx->psk_client_callback;
637 s->psk_server_callback = ctx->psk_server_callback;
642 #ifndef OPENSSL_NO_CT
643 if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
644 ctx->ct_validation_callback_arg))
651 SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
655 int SSL_is_dtls(const SSL *s)
657 return SSL_IS_DTLS(s) ? 1 : 0;
660 int SSL_up_ref(SSL *s)
664 if (CRYPTO_UP_REF(&s->references, &i, s->lock) <= 0)
667 REF_PRINT_COUNT("SSL", s);
668 REF_ASSERT_ISNT(i < 2);
669 return ((i > 1) ? 1 : 0);
672 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
673 unsigned int sid_ctx_len)
675 if (sid_ctx_len > sizeof ctx->sid_ctx) {
676 SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
677 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
680 ctx->sid_ctx_length = sid_ctx_len;
681 memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
686 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
687 unsigned int sid_ctx_len)
689 if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
690 SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
691 SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
694 ssl->sid_ctx_length = sid_ctx_len;
695 memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
700 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
702 CRYPTO_THREAD_write_lock(ctx->lock);
703 ctx->generate_session_id = cb;
704 CRYPTO_THREAD_unlock(ctx->lock);
708 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
710 CRYPTO_THREAD_write_lock(ssl->lock);
711 ssl->generate_session_id = cb;
712 CRYPTO_THREAD_unlock(ssl->lock);
716 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
720 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
721 * we can "construct" a session to give us the desired check - i.e. to
722 * find if there's a session in the hash table that would conflict with
723 * any new session built out of this id/id_len and the ssl_version in use
728 if (id_len > sizeof r.session_id)
731 r.ssl_version = ssl->version;
732 r.session_id_length = id_len;
733 memcpy(r.session_id, id, id_len);
735 CRYPTO_THREAD_read_lock(ssl->session_ctx->lock);
736 p = lh_SSL_SESSION_retrieve(ssl->session_ctx->sessions, &r);
737 CRYPTO_THREAD_unlock(ssl->session_ctx->lock);
741 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
743 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
746 int SSL_set_purpose(SSL *s, int purpose)
748 return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
751 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
753 return X509_VERIFY_PARAM_set_trust(s->param, trust);
756 int SSL_set_trust(SSL *s, int trust)
758 return X509_VERIFY_PARAM_set_trust(s->param, trust);
761 int SSL_set1_host(SSL *s, const char *hostname)
763 return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
766 int SSL_add1_host(SSL *s, const char *hostname)
768 return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
771 void SSL_set_hostflags(SSL *s, unsigned int flags)
773 X509_VERIFY_PARAM_set_hostflags(s->param, flags);
776 const char *SSL_get0_peername(SSL *s)
778 return X509_VERIFY_PARAM_get0_peername(s->param);
781 int SSL_CTX_dane_enable(SSL_CTX *ctx)
783 return dane_ctx_enable(&ctx->dane);
786 unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags)
788 unsigned long orig = ctx->dane.flags;
790 ctx->dane.flags |= flags;
794 unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags)
796 unsigned long orig = ctx->dane.flags;
798 ctx->dane.flags &= ~flags;
802 int SSL_dane_enable(SSL *s, const char *basedomain)
804 SSL_DANE *dane = &s->dane;
806 if (s->ctx->dane.mdmax == 0) {
807 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
810 if (dane->trecs != NULL) {
811 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
816 * Default SNI name. This rejects empty names, while set1_host below
817 * accepts them and disables host name checks. To avoid side-effects with
818 * invalid input, set the SNI name first.
820 if (s->ext.hostname == NULL) {
821 if (!SSL_set_tlsext_host_name(s, basedomain)) {
822 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
827 /* Primary RFC6125 reference identifier */
828 if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
829 SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
835 dane->dctx = &s->ctx->dane;
836 dane->trecs = sk_danetls_record_new_null();
838 if (dane->trecs == NULL) {
839 SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
845 unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags)
847 unsigned long orig = ssl->dane.flags;
849 ssl->dane.flags |= flags;
853 unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags)
855 unsigned long orig = ssl->dane.flags;
857 ssl->dane.flags &= ~flags;
861 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
863 SSL_DANE *dane = &s->dane;
865 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
869 *mcert = dane->mcert;
871 *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
876 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
877 uint8_t *mtype, unsigned const char **data, size_t *dlen)
879 SSL_DANE *dane = &s->dane;
881 if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
885 *usage = dane->mtlsa->usage;
887 *selector = dane->mtlsa->selector;
889 *mtype = dane->mtlsa->mtype;
891 *data = dane->mtlsa->data;
893 *dlen = dane->mtlsa->dlen;
898 SSL_DANE *SSL_get0_dane(SSL *s)
903 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
904 uint8_t mtype, unsigned char *data, size_t dlen)
906 return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
909 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype,
912 return dane_mtype_set(&ctx->dane, md, mtype, ord);
915 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
917 return X509_VERIFY_PARAM_set1(ctx->param, vpm);
920 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
922 return X509_VERIFY_PARAM_set1(ssl->param, vpm);
925 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
930 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
935 void SSL_certs_clear(SSL *s)
937 ssl_cert_clear_certs(s->cert);
940 void SSL_free(SSL *s)
947 CRYPTO_DOWN_REF(&s->references, &i, s->lock);
948 REF_PRINT_COUNT("SSL", s);
951 REF_ASSERT_ISNT(i < 0);
953 X509_VERIFY_PARAM_free(s->param);
954 dane_final(&s->dane);
955 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
957 /* Ignore return value */
958 ssl_free_wbio_buffer(s);
960 BIO_free_all(s->wbio);
961 BIO_free_all(s->rbio);
963 BUF_MEM_free(s->init_buf);
965 /* add extra stuff */
966 sk_SSL_CIPHER_free(s->cipher_list);
967 sk_SSL_CIPHER_free(s->cipher_list_by_id);
969 /* Make the next call work :-) */
970 if (s->session != NULL) {
971 ssl_clear_bad_session(s);
972 SSL_SESSION_free(s->session);
974 SSL_SESSION_free(s->psksession);
978 ssl_cert_free(s->cert);
979 /* Free up if allocated */
981 OPENSSL_free(s->ext.hostname);
982 SSL_CTX_free(s->session_ctx);
983 #ifndef OPENSSL_NO_EC
984 OPENSSL_free(s->ext.ecpointformats);
985 OPENSSL_free(s->ext.supportedgroups);
986 #endif /* OPENSSL_NO_EC */
987 sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts, X509_EXTENSION_free);
988 #ifndef OPENSSL_NO_OCSP
989 sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
991 #ifndef OPENSSL_NO_CT
992 SCT_LIST_free(s->scts);
993 OPENSSL_free(s->ext.scts);
995 OPENSSL_free(s->ext.ocsp.resp);
996 OPENSSL_free(s->ext.alpn);
997 OPENSSL_free(s->ext.tls13_cookie);
998 OPENSSL_free(s->clienthello);
1000 sk_X509_NAME_pop_free(s->ca_names, X509_NAME_free);
1002 sk_X509_pop_free(s->verified_chain, X509_free);
1004 if (s->method != NULL)
1005 s->method->ssl_free(s);
1007 RECORD_LAYER_release(&s->rlayer);
1009 SSL_CTX_free(s->ctx);
1011 ASYNC_WAIT_CTX_free(s->waitctx);
1013 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1014 OPENSSL_free(s->ext.npn);
1017 #ifndef OPENSSL_NO_SRTP
1018 sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1021 CRYPTO_THREAD_lock_free(s->lock);
1026 void SSL_set0_rbio(SSL *s, BIO *rbio)
1028 BIO_free_all(s->rbio);
1032 void SSL_set0_wbio(SSL *s, BIO *wbio)
1035 * If the output buffering BIO is still in place, remove it
1037 if (s->bbio != NULL)
1038 s->wbio = BIO_pop(s->wbio);
1040 BIO_free_all(s->wbio);
1043 /* Re-attach |bbio| to the new |wbio|. */
1044 if (s->bbio != NULL)
1045 s->wbio = BIO_push(s->bbio, s->wbio);
1048 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1051 * For historical reasons, this function has many different cases in
1052 * ownership handling.
1055 /* If nothing has changed, do nothing */
1056 if (rbio == SSL_get_rbio(s) && wbio == SSL_get_wbio(s))
1060 * If the two arguments are equal then one fewer reference is granted by the
1061 * caller than we want to take
1063 if (rbio != NULL && rbio == wbio)
1067 * If only the wbio is changed only adopt one reference.
1069 if (rbio == SSL_get_rbio(s)) {
1070 SSL_set0_wbio(s, wbio);
1074 * There is an asymmetry here for historical reasons. If only the rbio is
1075 * changed AND the rbio and wbio were originally different, then we only
1076 * adopt one reference.
1078 if (wbio == SSL_get_wbio(s) && SSL_get_rbio(s) != SSL_get_wbio(s)) {
1079 SSL_set0_rbio(s, rbio);
1083 /* Otherwise, adopt both references. */
1084 SSL_set0_rbio(s, rbio);
1085 SSL_set0_wbio(s, wbio);
1088 BIO *SSL_get_rbio(const SSL *s)
1093 BIO *SSL_get_wbio(const SSL *s)
1095 if (s->bbio != NULL) {
1097 * If |bbio| is active, the true caller-configured BIO is its
1100 return BIO_next(s->bbio);
1105 int SSL_get_fd(const SSL *s)
1107 return SSL_get_rfd(s);
1110 int SSL_get_rfd(const SSL *s)
1115 b = SSL_get_rbio(s);
1116 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1118 BIO_get_fd(r, &ret);
1122 int SSL_get_wfd(const SSL *s)
1127 b = SSL_get_wbio(s);
1128 r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1130 BIO_get_fd(r, &ret);
1134 #ifndef OPENSSL_NO_SOCK
1135 int SSL_set_fd(SSL *s, int fd)
1140 bio = BIO_new(BIO_s_socket());
1143 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1146 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1147 SSL_set_bio(s, bio, bio);
1153 int SSL_set_wfd(SSL *s, int fd)
1155 BIO *rbio = SSL_get_rbio(s);
1157 if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET
1158 || (int)BIO_get_fd(rbio, NULL) != fd) {
1159 BIO *bio = BIO_new(BIO_s_socket());
1162 SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1165 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1166 SSL_set0_wbio(s, bio);
1169 SSL_set0_wbio(s, rbio);
1174 int SSL_set_rfd(SSL *s, int fd)
1176 BIO *wbio = SSL_get_wbio(s);
1178 if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET
1179 || ((int)BIO_get_fd(wbio, NULL) != fd)) {
1180 BIO *bio = BIO_new(BIO_s_socket());
1183 SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1186 BIO_set_fd(bio, fd, BIO_NOCLOSE);
1187 SSL_set0_rbio(s, bio);
1190 SSL_set0_rbio(s, wbio);
1197 /* return length of latest Finished message we sent, copy to 'buf' */
1198 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1202 if (s->s3 != NULL) {
1203 ret = s->s3->tmp.finish_md_len;
1206 memcpy(buf, s->s3->tmp.finish_md, count);
1211 /* return length of latest Finished message we expected, copy to 'buf' */
1212 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1216 if (s->s3 != NULL) {
1217 ret = s->s3->tmp.peer_finish_md_len;
1220 memcpy(buf, s->s3->tmp.peer_finish_md, count);
1225 int SSL_get_verify_mode(const SSL *s)
1227 return (s->verify_mode);
1230 int SSL_get_verify_depth(const SSL *s)
1232 return X509_VERIFY_PARAM_get_depth(s->param);
1235 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1236 return (s->verify_callback);
1239 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1241 return (ctx->verify_mode);
1244 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1246 return X509_VERIFY_PARAM_get_depth(ctx->param);
1249 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1250 return (ctx->default_verify_callback);
1253 void SSL_set_verify(SSL *s, int mode,
1254 int (*callback) (int ok, X509_STORE_CTX *ctx))
1256 s->verify_mode = mode;
1257 if (callback != NULL)
1258 s->verify_callback = callback;
1261 void SSL_set_verify_depth(SSL *s, int depth)
1263 X509_VERIFY_PARAM_set_depth(s->param, depth);
1266 void SSL_set_read_ahead(SSL *s, int yes)
1268 RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1271 int SSL_get_read_ahead(const SSL *s)
1273 return RECORD_LAYER_get_read_ahead(&s->rlayer);
1276 int SSL_pending(const SSL *s)
1278 size_t pending = s->method->ssl_pending(s);
1281 * SSL_pending cannot work properly if read-ahead is enabled
1282 * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1283 * impossible to fix since SSL_pending cannot report errors that may be
1284 * observed while scanning the new data. (Note that SSL_pending() is
1285 * often used as a boolean value, so we'd better not return -1.)
1287 * SSL_pending also cannot work properly if the value >INT_MAX. In that case
1288 * we just return INT_MAX.
1290 return pending < INT_MAX ? (int)pending : INT_MAX;
1293 int SSL_has_pending(const SSL *s)
1296 * Similar to SSL_pending() but returns a 1 to indicate that we have
1297 * unprocessed data available or 0 otherwise (as opposed to the number of
1298 * bytes available). Unlike SSL_pending() this will take into account
1299 * read_ahead data. A 1 return simply indicates that we have unprocessed
1300 * data. That data may not result in any application data, or we may fail
1301 * to parse the records for some reason.
1303 if (RECORD_LAYER_processed_read_pending(&s->rlayer))
1306 return RECORD_LAYER_read_pending(&s->rlayer);
1309 X509 *SSL_get_peer_certificate(const SSL *s)
1313 if ((s == NULL) || (s->session == NULL))
1316 r = s->session->peer;
1326 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1330 if ((s == NULL) || (s->session == NULL))
1333 r = s->session->peer_chain;
1336 * If we are a client, cert_chain includes the peer's own certificate; if
1337 * we are a server, it does not.
1344 * Now in theory, since the calling process own 't' it should be safe to
1345 * modify. We need to be able to read f without being hassled
1347 int SSL_copy_session_id(SSL *t, const SSL *f)
1350 /* Do we need to to SSL locking? */
1351 if (!SSL_set_session(t, SSL_get_session(f))) {
1356 * what if we are setup for one protocol version but want to talk another
1358 if (t->method != f->method) {
1359 t->method->ssl_free(t);
1360 t->method = f->method;
1361 if (t->method->ssl_new(t) == 0)
1365 CRYPTO_UP_REF(&f->cert->references, &i, f->cert->lock);
1366 ssl_cert_free(t->cert);
1368 if (!SSL_set_session_id_context(t, f->sid_ctx, (int)f->sid_ctx_length)) {
1375 /* Fix this so it checks all the valid key/cert options */
1376 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1378 if ((ctx == NULL) || (ctx->cert->key->x509 == NULL)) {
1379 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1382 if (ctx->cert->key->privatekey == NULL) {
1383 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1386 return (X509_check_private_key
1387 (ctx->cert->key->x509, ctx->cert->key->privatekey));
1390 /* Fix this function so that it takes an optional type parameter */
1391 int SSL_check_private_key(const SSL *ssl)
1394 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1397 if (ssl->cert->key->x509 == NULL) {
1398 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1401 if (ssl->cert->key->privatekey == NULL) {
1402 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1405 return (X509_check_private_key(ssl->cert->key->x509,
1406 ssl->cert->key->privatekey));
1409 int SSL_waiting_for_async(SSL *s)
1417 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1419 ASYNC_WAIT_CTX *ctx = s->waitctx;
1423 return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1426 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1427 OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1429 ASYNC_WAIT_CTX *ctx = s->waitctx;
1433 return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1437 int SSL_accept(SSL *s)
1439 if (s->handshake_func == NULL) {
1440 /* Not properly initialized yet */
1441 SSL_set_accept_state(s);
1444 return SSL_do_handshake(s);
1447 int SSL_connect(SSL *s)
1449 if (s->handshake_func == NULL) {
1450 /* Not properly initialized yet */
1451 SSL_set_connect_state(s);
1454 return SSL_do_handshake(s);
1457 long SSL_get_default_timeout(const SSL *s)
1459 return (s->method->get_timeout());
1462 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1463 int (*func) (void *))
1466 if (s->waitctx == NULL) {
1467 s->waitctx = ASYNC_WAIT_CTX_new();
1468 if (s->waitctx == NULL)
1471 switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1472 sizeof(struct ssl_async_args))) {
1474 s->rwstate = SSL_NOTHING;
1475 SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1478 s->rwstate = SSL_ASYNC_PAUSED;
1481 s->rwstate = SSL_ASYNC_NO_JOBS;
1487 s->rwstate = SSL_NOTHING;
1488 SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1489 /* Shouldn't happen */
1494 static int ssl_io_intern(void *vargs)
1496 struct ssl_async_args *args;
1501 args = (struct ssl_async_args *)vargs;
1505 switch (args->type) {
1507 return args->f.func_read(s, buf, num, &s->asyncrw);
1509 return args->f.func_write(s, buf, num, &s->asyncrw);
1511 return args->f.func_other(s);
1516 int ssl_read_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1518 if (s->handshake_func == NULL) {
1519 SSLerr(SSL_F_SSL_READ_INTERNAL, SSL_R_UNINITIALIZED);
1523 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1524 s->rwstate = SSL_NOTHING;
1528 if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1529 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY) {
1530 SSLerr(SSL_F_SSL_READ_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1534 * If we are a client and haven't received the ServerHello etc then we
1537 ossl_statem_check_finish_init(s, 0);
1539 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1540 struct ssl_async_args args;
1546 args.type = READFUNC;
1547 args.f.func_read = s->method->ssl_read;
1549 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1550 *readbytes = s->asyncrw;
1553 return s->method->ssl_read(s, buf, num, readbytes);
1557 int SSL_read(SSL *s, void *buf, int num)
1563 SSLerr(SSL_F_SSL_READ, SSL_R_BAD_LENGTH);
1567 ret = ssl_read_internal(s, buf, (size_t)num, &readbytes);
1570 * The cast is safe here because ret should be <= INT_MAX because num is
1574 ret = (int)readbytes;
1579 int SSL_read_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1581 int ret = ssl_read_internal(s, buf, num, readbytes);
1588 int SSL_read_early_data(SSL *s, void *buf, size_t num, size_t *readbytes)
1593 SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1594 return SSL_READ_EARLY_DATA_ERROR;
1597 switch (s->early_data_state) {
1598 case SSL_EARLY_DATA_NONE:
1599 if (!SSL_in_before(s)) {
1600 SSLerr(SSL_F_SSL_READ_EARLY_DATA,
1601 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1602 return SSL_READ_EARLY_DATA_ERROR;
1606 case SSL_EARLY_DATA_ACCEPT_RETRY:
1607 s->early_data_state = SSL_EARLY_DATA_ACCEPTING;
1608 ret = SSL_accept(s);
1611 s->early_data_state = SSL_EARLY_DATA_ACCEPT_RETRY;
1612 return SSL_READ_EARLY_DATA_ERROR;
1616 case SSL_EARLY_DATA_READ_RETRY:
1617 if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
1618 s->early_data_state = SSL_EARLY_DATA_READING;
1619 ret = SSL_read_ex(s, buf, num, readbytes);
1621 * State machine will update early_data_state to
1622 * SSL_EARLY_DATA_FINISHED_READING if we get an EndOfEarlyData
1625 if (ret > 0 || (ret <= 0 && s->early_data_state
1626 != SSL_EARLY_DATA_FINISHED_READING)) {
1627 s->early_data_state = SSL_EARLY_DATA_READ_RETRY;
1628 return ret > 0 ? SSL_READ_EARLY_DATA_SUCCESS
1629 : SSL_READ_EARLY_DATA_ERROR;
1632 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
1635 return SSL_READ_EARLY_DATA_FINISH;
1638 SSLerr(SSL_F_SSL_READ_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1639 return SSL_READ_EARLY_DATA_ERROR;
1643 int SSL_get_early_data_status(const SSL *s)
1645 return s->ext.early_data;
1648 static int ssl_peek_internal(SSL *s, void *buf, size_t num, size_t *readbytes)
1650 if (s->handshake_func == NULL) {
1651 SSLerr(SSL_F_SSL_PEEK_INTERNAL, SSL_R_UNINITIALIZED);
1655 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1658 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1659 struct ssl_async_args args;
1665 args.type = READFUNC;
1666 args.f.func_read = s->method->ssl_peek;
1668 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1669 *readbytes = s->asyncrw;
1672 return s->method->ssl_peek(s, buf, num, readbytes);
1676 int SSL_peek(SSL *s, void *buf, int num)
1682 SSLerr(SSL_F_SSL_PEEK, SSL_R_BAD_LENGTH);
1686 ret = ssl_peek_internal(s, buf, (size_t)num, &readbytes);
1689 * The cast is safe here because ret should be <= INT_MAX because num is
1693 ret = (int)readbytes;
1699 int SSL_peek_ex(SSL *s, void *buf, size_t num, size_t *readbytes)
1701 int ret = ssl_peek_internal(s, buf, num, readbytes);
1708 int ssl_write_internal(SSL *s, const void *buf, size_t num, size_t *written)
1710 if (s->handshake_func == NULL) {
1711 SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_UNINITIALIZED);
1715 if (s->shutdown & SSL_SENT_SHUTDOWN) {
1716 s->rwstate = SSL_NOTHING;
1717 SSLerr(SSL_F_SSL_WRITE_INTERNAL, SSL_R_PROTOCOL_IS_SHUTDOWN);
1721 if (s->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY
1722 || s->early_data_state == SSL_EARLY_DATA_ACCEPT_RETRY
1723 || s->early_data_state == SSL_EARLY_DATA_READ_RETRY) {
1724 SSLerr(SSL_F_SSL_WRITE_INTERNAL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1727 /* If we are a client and haven't sent the Finished we better do that */
1728 ossl_statem_check_finish_init(s, 1);
1730 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1732 struct ssl_async_args args;
1735 args.buf = (void *)buf;
1737 args.type = WRITEFUNC;
1738 args.f.func_write = s->method->ssl_write;
1740 ret = ssl_start_async_job(s, &args, ssl_io_intern);
1741 *written = s->asyncrw;
1744 return s->method->ssl_write(s, buf, num, written);
1748 int SSL_write(SSL *s, const void *buf, int num)
1754 SSLerr(SSL_F_SSL_WRITE, SSL_R_BAD_LENGTH);
1758 ret = ssl_write_internal(s, buf, (size_t)num, &written);
1761 * The cast is safe here because ret should be <= INT_MAX because num is
1770 int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written)
1772 int ret = ssl_write_internal(s, buf, num, written);
1779 int SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
1781 int ret, early_data_state;
1783 switch (s->early_data_state) {
1784 case SSL_EARLY_DATA_NONE:
1786 || !SSL_in_before(s)
1787 || s->session == NULL
1788 || s->session->ext.max_early_data == 0) {
1789 SSLerr(SSL_F_SSL_WRITE_EARLY_DATA,
1790 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1795 case SSL_EARLY_DATA_CONNECT_RETRY:
1796 s->early_data_state = SSL_EARLY_DATA_CONNECTING;
1797 ret = SSL_connect(s);
1800 s->early_data_state = SSL_EARLY_DATA_CONNECT_RETRY;
1805 case SSL_EARLY_DATA_WRITE_RETRY:
1806 s->early_data_state = SSL_EARLY_DATA_WRITING;
1807 ret = SSL_write_ex(s, buf, num, written);
1808 s->early_data_state = SSL_EARLY_DATA_WRITE_RETRY;
1811 case SSL_EARLY_DATA_FINISHED_READING:
1812 case SSL_EARLY_DATA_READ_RETRY:
1813 early_data_state = s->early_data_state;
1814 /* We are a server writing to an unauthenticated client */
1815 s->early_data_state = SSL_EARLY_DATA_UNAUTH_WRITING;
1816 ret = SSL_write_ex(s, buf, num, written);
1817 s->early_data_state = early_data_state;
1821 SSLerr(SSL_F_SSL_WRITE_EARLY_DATA, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1826 int SSL_shutdown(SSL *s)
1829 * Note that this function behaves differently from what one might
1830 * expect. Return values are 0 for no success (yet), 1 for success; but
1831 * calling it once is usually not enough, even if blocking I/O is used
1832 * (see ssl3_shutdown).
1835 if (s->handshake_func == NULL) {
1836 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1840 if (!SSL_in_init(s)) {
1841 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1842 struct ssl_async_args args;
1845 args.type = OTHERFUNC;
1846 args.f.func_other = s->method->ssl_shutdown;
1848 return ssl_start_async_job(s, &args, ssl_io_intern);
1850 return s->method->ssl_shutdown(s);
1853 SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
1858 int SSL_key_update(SSL *s, int updatetype)
1861 * TODO(TLS1.3): How will applications know whether TLSv1.3 has been
1862 * negotiated, and that it is appropriate to call SSL_key_update() instead
1863 * of SSL_renegotiate().
1865 if (!SSL_IS_TLS13(s)) {
1866 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_WRONG_SSL_VERSION);
1870 if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
1871 && updatetype != SSL_KEY_UPDATE_REQUESTED) {
1872 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_INVALID_KEY_UPDATE_TYPE);
1876 if (!SSL_is_init_finished(s)) {
1877 SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_STILL_IN_INIT);
1881 ossl_statem_set_in_init(s, 1);
1882 s->key_update = updatetype;
1886 int SSL_get_key_update_type(SSL *s)
1888 return s->key_update;
1891 int SSL_renegotiate(SSL *s)
1893 if (SSL_IS_TLS13(s)) {
1894 SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_WRONG_SSL_VERSION);
1898 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1899 SSLerr(SSL_F_SSL_RENEGOTIATE, SSL_R_NO_RENEGOTIATION);
1906 return (s->method->ssl_renegotiate(s));
1909 int SSL_renegotiate_abbreviated(SSL *s)
1911 if (SSL_IS_TLS13(s)) {
1912 SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_WRONG_SSL_VERSION);
1916 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1917 SSLerr(SSL_F_SSL_RENEGOTIATE_ABBREVIATED, SSL_R_NO_RENEGOTIATION);
1924 return (s->method->ssl_renegotiate(s));
1927 int SSL_renegotiate_pending(SSL *s)
1930 * becomes true when negotiation is requested; false again once a
1931 * handshake has finished
1933 return (s->renegotiate != 0);
1936 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1941 case SSL_CTRL_GET_READ_AHEAD:
1942 return (RECORD_LAYER_get_read_ahead(&s->rlayer));
1943 case SSL_CTRL_SET_READ_AHEAD:
1944 l = RECORD_LAYER_get_read_ahead(&s->rlayer);
1945 RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
1948 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1949 s->msg_callback_arg = parg;
1953 return (s->mode |= larg);
1954 case SSL_CTRL_CLEAR_MODE:
1955 return (s->mode &= ~larg);
1956 case SSL_CTRL_GET_MAX_CERT_LIST:
1957 return (long)(s->max_cert_list);
1958 case SSL_CTRL_SET_MAX_CERT_LIST:
1961 l = (long)s->max_cert_list;
1962 s->max_cert_list = (size_t)larg;
1964 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1965 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1967 s->max_send_fragment = larg;
1968 if (s->max_send_fragment < s->split_send_fragment)
1969 s->split_send_fragment = s->max_send_fragment;
1971 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1972 if ((size_t)larg > s->max_send_fragment || larg == 0)
1974 s->split_send_fragment = larg;
1976 case SSL_CTRL_SET_MAX_PIPELINES:
1977 if (larg < 1 || larg > SSL_MAX_PIPELINES)
1979 s->max_pipelines = larg;
1981 RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
1983 case SSL_CTRL_GET_RI_SUPPORT:
1985 return s->s3->send_connection_binding;
1988 case SSL_CTRL_CERT_FLAGS:
1989 return (s->cert->cert_flags |= larg);
1990 case SSL_CTRL_CLEAR_CERT_FLAGS:
1991 return (s->cert->cert_flags &= ~larg);
1993 case SSL_CTRL_GET_RAW_CIPHERLIST:
1995 if (s->s3->tmp.ciphers_raw == NULL)
1997 *(unsigned char **)parg = s->s3->tmp.ciphers_raw;
1998 return (int)s->s3->tmp.ciphers_rawlen;
2000 return TLS_CIPHER_LEN;
2002 case SSL_CTRL_GET_EXTMS_SUPPORT:
2003 if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
2005 if (s->session->flags & SSL_SESS_FLAG_EXTMS)
2009 case SSL_CTRL_SET_MIN_PROTO_VERSION:
2010 return ssl_set_version_bound(s->ctx->method->version, (int)larg,
2011 &s->min_proto_version);
2012 case SSL_CTRL_SET_MAX_PROTO_VERSION:
2013 return ssl_set_version_bound(s->ctx->method->version, (int)larg,
2014 &s->max_proto_version);
2016 return (s->method->ssl_ctrl(s, cmd, larg, parg));
2020 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
2023 case SSL_CTRL_SET_MSG_CALLBACK:
2024 s->msg_callback = (void (*)
2025 (int write_p, int version, int content_type,
2026 const void *buf, size_t len, SSL *ssl,
2031 return (s->method->ssl_callback_ctrl(s, cmd, fp));
2035 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
2037 return ctx->sessions;
2040 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
2043 /* For some cases with ctx == NULL perform syntax checks */
2046 #ifndef OPENSSL_NO_EC
2047 case SSL_CTRL_SET_GROUPS_LIST:
2048 return tls1_set_groups_list(NULL, NULL, parg);
2050 case SSL_CTRL_SET_SIGALGS_LIST:
2051 case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
2052 return tls1_set_sigalgs_list(NULL, parg, 0);
2059 case SSL_CTRL_GET_READ_AHEAD:
2060 return (ctx->read_ahead);
2061 case SSL_CTRL_SET_READ_AHEAD:
2062 l = ctx->read_ahead;
2063 ctx->read_ahead = larg;
2066 case SSL_CTRL_SET_MSG_CALLBACK_ARG:
2067 ctx->msg_callback_arg = parg;
2070 case SSL_CTRL_GET_MAX_CERT_LIST:
2071 return (long)(ctx->max_cert_list);
2072 case SSL_CTRL_SET_MAX_CERT_LIST:
2075 l = (long)ctx->max_cert_list;
2076 ctx->max_cert_list = (size_t)larg;
2079 case SSL_CTRL_SET_SESS_CACHE_SIZE:
2082 l = (long)ctx->session_cache_size;
2083 ctx->session_cache_size = (size_t)larg;
2085 case SSL_CTRL_GET_SESS_CACHE_SIZE:
2086 return (long)(ctx->session_cache_size);
2087 case SSL_CTRL_SET_SESS_CACHE_MODE:
2088 l = ctx->session_cache_mode;
2089 ctx->session_cache_mode = larg;
2091 case SSL_CTRL_GET_SESS_CACHE_MODE:
2092 return (ctx->session_cache_mode);
2094 case SSL_CTRL_SESS_NUMBER:
2095 return (lh_SSL_SESSION_num_items(ctx->sessions));
2096 case SSL_CTRL_SESS_CONNECT:
2097 return (ctx->stats.sess_connect);
2098 case SSL_CTRL_SESS_CONNECT_GOOD:
2099 return (ctx->stats.sess_connect_good);
2100 case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
2101 return (ctx->stats.sess_connect_renegotiate);
2102 case SSL_CTRL_SESS_ACCEPT:
2103 return (ctx->stats.sess_accept);
2104 case SSL_CTRL_SESS_ACCEPT_GOOD:
2105 return (ctx->stats.sess_accept_good);
2106 case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
2107 return (ctx->stats.sess_accept_renegotiate);
2108 case SSL_CTRL_SESS_HIT:
2109 return (ctx->stats.sess_hit);
2110 case SSL_CTRL_SESS_CB_HIT:
2111 return (ctx->stats.sess_cb_hit);
2112 case SSL_CTRL_SESS_MISSES:
2113 return (ctx->stats.sess_miss);
2114 case SSL_CTRL_SESS_TIMEOUTS:
2115 return (ctx->stats.sess_timeout);
2116 case SSL_CTRL_SESS_CACHE_FULL:
2117 return (ctx->stats.sess_cache_full);
2119 return (ctx->mode |= larg);
2120 case SSL_CTRL_CLEAR_MODE:
2121 return (ctx->mode &= ~larg);
2122 case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
2123 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
2125 ctx->max_send_fragment = larg;
2126 if (ctx->max_send_fragment < ctx->split_send_fragment)
2127 ctx->split_send_fragment = ctx->max_send_fragment;
2129 case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
2130 if ((size_t)larg > ctx->max_send_fragment || larg == 0)
2132 ctx->split_send_fragment = larg;
2134 case SSL_CTRL_SET_MAX_PIPELINES:
2135 if (larg < 1 || larg > SSL_MAX_PIPELINES)
2137 ctx->max_pipelines = larg;
2139 case SSL_CTRL_CERT_FLAGS:
2140 return (ctx->cert->cert_flags |= larg);
2141 case SSL_CTRL_CLEAR_CERT_FLAGS:
2142 return (ctx->cert->cert_flags &= ~larg);
2143 case SSL_CTRL_SET_MIN_PROTO_VERSION:
2144 return ssl_set_version_bound(ctx->method->version, (int)larg,
2145 &ctx->min_proto_version);
2146 case SSL_CTRL_SET_MAX_PROTO_VERSION:
2147 return ssl_set_version_bound(ctx->method->version, (int)larg,
2148 &ctx->max_proto_version);
2150 return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
2154 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
2157 case SSL_CTRL_SET_MSG_CALLBACK:
2158 ctx->msg_callback = (void (*)
2159 (int write_p, int version, int content_type,
2160 const void *buf, size_t len, SSL *ssl,
2165 return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
2169 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
2178 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
2179 const SSL_CIPHER *const *bp)
2181 if ((*ap)->id > (*bp)->id)
2183 if ((*ap)->id < (*bp)->id)
2188 /** return a STACK of the ciphers available for the SSL and in order of
2190 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
2193 if (s->cipher_list != NULL) {
2194 return (s->cipher_list);
2195 } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
2196 return (s->ctx->cipher_list);
2202 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
2204 if ((s == NULL) || (s->session == NULL) || !s->server)
2206 return s->session->ciphers;
2209 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
2211 STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
2213 ciphers = SSL_get_ciphers(s);
2216 ssl_set_client_disabled(s);
2217 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2218 const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
2219 if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0)) {
2221 sk = sk_SSL_CIPHER_new_null();
2224 if (!sk_SSL_CIPHER_push(sk, c)) {
2225 sk_SSL_CIPHER_free(sk);
2233 /** return a STACK of the ciphers available for the SSL and in order of
2235 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
2238 if (s->cipher_list_by_id != NULL) {
2239 return (s->cipher_list_by_id);
2240 } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
2241 return (s->ctx->cipher_list_by_id);
2247 /** The old interface to get the same thing as SSL_get_ciphers() */
2248 const char *SSL_get_cipher_list(const SSL *s, int n)
2250 const SSL_CIPHER *c;
2251 STACK_OF(SSL_CIPHER) *sk;
2255 sk = SSL_get_ciphers(s);
2256 if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2258 c = sk_SSL_CIPHER_value(sk, n);
2264 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2266 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2269 return ctx->cipher_list;
2273 /** specify the ciphers to be used by default by the SSL_CTX */
2274 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2276 STACK_OF(SSL_CIPHER) *sk;
2278 sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
2279 &ctx->cipher_list_by_id, str, ctx->cert);
2281 * ssl_create_cipher_list may return an empty stack if it was unable to
2282 * find a cipher matching the given rule string (for example if the rule
2283 * string specifies a cipher which has been disabled). This is not an
2284 * error as far as ssl_create_cipher_list is concerned, and hence
2285 * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2289 else if (sk_SSL_CIPHER_num(sk) == 0) {
2290 SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2296 /** specify the ciphers to be used by the SSL */
2297 int SSL_set_cipher_list(SSL *s, const char *str)
2299 STACK_OF(SSL_CIPHER) *sk;
2301 sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
2302 &s->cipher_list_by_id, str, s->cert);
2303 /* see comment in SSL_CTX_set_cipher_list */
2306 else if (sk_SSL_CIPHER_num(sk) == 0) {
2307 SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2313 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
2316 STACK_OF(SSL_CIPHER) *sk;
2317 const SSL_CIPHER *c;
2320 if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
2324 sk = s->session->ciphers;
2326 if (sk_SSL_CIPHER_num(sk) == 0)
2329 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2332 c = sk_SSL_CIPHER_value(sk, i);
2333 n = strlen(c->name);
2340 memcpy(p, c->name, n + 1);
2349 /** return a servername extension value if provided in Client Hello, or NULL.
2350 * So far, only host_name types are defined (RFC 3546).
2353 const char *SSL_get_servername(const SSL *s, const int type)
2355 if (type != TLSEXT_NAMETYPE_host_name)
2358 return s->session && !s->ext.hostname ?
2359 s->session->ext.hostname : s->ext.hostname;
2362 int SSL_get_servername_type(const SSL *s)
2365 && (!s->ext.hostname ? s->session->
2366 ext.hostname : s->ext.hostname))
2367 return TLSEXT_NAMETYPE_host_name;
2372 * SSL_select_next_proto implements the standard protocol selection. It is
2373 * expected that this function is called from the callback set by
2374 * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2375 * vector of 8-bit, length prefixed byte strings. The length byte itself is
2376 * not included in the length. A byte string of length 0 is invalid. No byte
2377 * string may be truncated. The current, but experimental algorithm for
2378 * selecting the protocol is: 1) If the server doesn't support NPN then this
2379 * is indicated to the callback. In this case, the client application has to
2380 * abort the connection or have a default application level protocol. 2) If
2381 * the server supports NPN, but advertises an empty list then the client
2382 * selects the first protocol in its list, but indicates via the API that this
2383 * fallback case was enacted. 3) Otherwise, the client finds the first
2384 * protocol in the server's list that it supports and selects this protocol.
2385 * This is because it's assumed that the server has better information about
2386 * which protocol a client should use. 4) If the client doesn't support any
2387 * of the server's advertised protocols, then this is treated the same as
2388 * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2389 * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2391 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2392 const unsigned char *server,
2393 unsigned int server_len,
2394 const unsigned char *client, unsigned int client_len)
2397 const unsigned char *result;
2398 int status = OPENSSL_NPN_UNSUPPORTED;
2401 * For each protocol in server preference order, see if we support it.
2403 for (i = 0; i < server_len;) {
2404 for (j = 0; j < client_len;) {
2405 if (server[i] == client[j] &&
2406 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2407 /* We found a match */
2408 result = &server[i];
2409 status = OPENSSL_NPN_NEGOTIATED;
2419 /* There's no overlap between our protocols and the server's list. */
2421 status = OPENSSL_NPN_NO_OVERLAP;
2424 *out = (unsigned char *)result + 1;
2425 *outlen = result[0];
2429 #ifndef OPENSSL_NO_NEXTPROTONEG
2431 * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2432 * client's requested protocol for this connection and returns 0. If the
2433 * client didn't request any protocol, then *data is set to NULL. Note that
2434 * the client can request any protocol it chooses. The value returned from
2435 * this function need not be a member of the list of supported protocols
2436 * provided by the callback.
2438 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2445 *len = (unsigned int)s->ext.npn_len;
2450 * SSL_CTX_set_npn_advertised_cb sets a callback that is called when
2451 * a TLS server needs a list of supported protocols for Next Protocol
2452 * Negotiation. The returned list must be in wire format. The list is
2453 * returned by setting |out| to point to it and |outlen| to its length. This
2454 * memory will not be modified, but one should assume that the SSL* keeps a
2455 * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2456 * wishes to advertise. Otherwise, no such extension will be included in the
2459 void SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,
2460 SSL_CTX_npn_advertised_cb_func cb,
2463 ctx->ext.npn_advertised_cb = cb;
2464 ctx->ext.npn_advertised_cb_arg = arg;
2468 * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2469 * client needs to select a protocol from the server's provided list. |out|
2470 * must be set to point to the selected protocol (which may be within |in|).
2471 * The length of the protocol name must be written into |outlen|. The
2472 * server's advertised protocols are provided in |in| and |inlen|. The
2473 * callback can assume that |in| is syntactically valid. The client must
2474 * select a protocol. It is fatal to the connection if this callback returns
2475 * a value other than SSL_TLSEXT_ERR_OK.
2477 void SSL_CTX_set_npn_select_cb(SSL_CTX *ctx,
2478 SSL_CTX_npn_select_cb_func cb,
2481 ctx->ext.npn_select_cb = cb;
2482 ctx->ext.npn_select_cb_arg = arg;
2487 * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2488 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2489 * length-prefixed strings). Returns 0 on success.
2491 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2492 unsigned int protos_len)
2494 OPENSSL_free(ctx->ext.alpn);
2495 ctx->ext.alpn = OPENSSL_memdup(protos, protos_len);
2496 if (ctx->ext.alpn == NULL) {
2497 SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2500 ctx->ext.alpn_len = protos_len;
2506 * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2507 * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2508 * length-prefixed strings). Returns 0 on success.
2510 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2511 unsigned int protos_len)
2513 OPENSSL_free(ssl->ext.alpn);
2514 ssl->ext.alpn = OPENSSL_memdup(protos, protos_len);
2515 if (ssl->ext.alpn == NULL) {
2516 SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2519 ssl->ext.alpn_len = protos_len;
2525 * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2526 * called during ClientHello processing in order to select an ALPN protocol
2527 * from the client's list of offered protocols.
2529 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2530 SSL_CTX_alpn_select_cb_func cb,
2533 ctx->ext.alpn_select_cb = cb;
2534 ctx->ext.alpn_select_cb_arg = arg;
2538 * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
2539 * On return it sets |*data| to point to |*len| bytes of protocol name
2540 * (not including the leading length-prefix byte). If the server didn't
2541 * respond with a negotiated protocol then |*len| will be zero.
2543 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
2548 *data = ssl->s3->alpn_selected;
2552 *len = (unsigned int)ssl->s3->alpn_selected_len;
2555 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2556 const char *label, size_t llen,
2557 const unsigned char *p, size_t plen,
2560 if (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER)
2563 return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
2568 static unsigned long ssl_session_hash(const SSL_SESSION *a)
2570 const unsigned char *session_id = a->session_id;
2572 unsigned char tmp_storage[4];
2574 if (a->session_id_length < sizeof(tmp_storage)) {
2575 memset(tmp_storage, 0, sizeof(tmp_storage));
2576 memcpy(tmp_storage, a->session_id, a->session_id_length);
2577 session_id = tmp_storage;
2581 ((unsigned long)session_id[0]) |
2582 ((unsigned long)session_id[1] << 8L) |
2583 ((unsigned long)session_id[2] << 16L) |
2584 ((unsigned long)session_id[3] << 24L);
2589 * NB: If this function (or indeed the hash function which uses a sort of
2590 * coarser function than this one) is changed, ensure
2591 * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
2592 * being able to construct an SSL_SESSION that will collide with any existing
2593 * session with a matching session ID.
2595 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
2597 if (a->ssl_version != b->ssl_version)
2599 if (a->session_id_length != b->session_id_length)
2601 return (memcmp(a->session_id, b->session_id, a->session_id_length));
2605 * These wrapper functions should remain rather than redeclaring
2606 * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
2607 * variable. The reason is that the functions aren't static, they're exposed
2611 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
2613 SSL_CTX *ret = NULL;
2616 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
2620 if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
2623 if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
2624 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
2627 ret = OPENSSL_zalloc(sizeof(*ret));
2632 ret->min_proto_version = 0;
2633 ret->max_proto_version = 0;
2634 ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
2635 ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
2636 /* We take the system default. */
2637 ret->session_timeout = meth->get_timeout();
2638 ret->references = 1;
2639 ret->lock = CRYPTO_THREAD_lock_new();
2640 if (ret->lock == NULL) {
2641 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2645 ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
2646 ret->verify_mode = SSL_VERIFY_NONE;
2647 if ((ret->cert = ssl_cert_new()) == NULL)
2650 ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2651 if (ret->sessions == NULL)
2653 ret->cert_store = X509_STORE_new();
2654 if (ret->cert_store == NULL)
2656 #ifndef OPENSSL_NO_CT
2657 ret->ctlog_store = CTLOG_STORE_new();
2658 if (ret->ctlog_store == NULL)
2661 if (!ssl_create_cipher_list(ret->method,
2662 &ret->cipher_list, &ret->cipher_list_by_id,
2663 SSL_DEFAULT_CIPHER_LIST, ret->cert)
2664 || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2665 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2669 ret->param = X509_VERIFY_PARAM_new();
2670 if (ret->param == NULL)
2673 if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
2674 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
2677 if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
2678 SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
2682 if ((ret->ca_names = sk_X509_NAME_new_null()) == NULL)
2685 if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data))
2688 /* No compression for DTLS */
2689 if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
2690 ret->comp_methods = SSL_COMP_get_compression_methods();
2692 ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2693 ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2695 /* Setup RFC5077 ticket keys */
2696 if ((RAND_bytes(ret->ext.tick_key_name,
2697 sizeof(ret->ext.tick_key_name)) <= 0)
2698 || (RAND_bytes(ret->ext.tick_hmac_key,
2699 sizeof(ret->ext.tick_hmac_key)) <= 0)
2700 || (RAND_bytes(ret->ext.tick_aes_key,
2701 sizeof(ret->ext.tick_aes_key)) <= 0))
2702 ret->options |= SSL_OP_NO_TICKET;
2704 #ifndef OPENSSL_NO_SRP
2705 if (!SSL_CTX_SRP_CTX_init(ret))
2708 #ifndef OPENSSL_NO_ENGINE
2709 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2710 # define eng_strx(x) #x
2711 # define eng_str(x) eng_strx(x)
2712 /* Use specific client engine automatically... ignore errors */
2715 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2718 ENGINE_load_builtin_engines();
2719 eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2721 if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2727 * Default is to connect to non-RI servers. When RI is more widely
2728 * deployed might change this.
2730 ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2732 * Disable compression by default to prevent CRIME. Applications can
2733 * re-enable compression by configuring
2734 * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
2735 * or by using the SSL_CONF library.
2737 ret->options |= SSL_OP_NO_COMPRESSION;
2739 ret->ext.status_type = TLSEXT_STATUSTYPE_nothing;
2742 * Default max early data is a fully loaded single record. Could be split
2743 * across multiple records in practice
2745 ret->max_early_data = SSL3_RT_MAX_PLAIN_LENGTH;
2749 SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2755 int SSL_CTX_up_ref(SSL_CTX *ctx)
2759 if (CRYPTO_UP_REF(&ctx->references, &i, ctx->lock) <= 0)
2762 REF_PRINT_COUNT("SSL_CTX", ctx);
2763 REF_ASSERT_ISNT(i < 2);
2764 return ((i > 1) ? 1 : 0);
2767 void SSL_CTX_free(SSL_CTX *a)
2774 CRYPTO_DOWN_REF(&a->references, &i, a->lock);
2775 REF_PRINT_COUNT("SSL_CTX", a);
2778 REF_ASSERT_ISNT(i < 0);
2780 X509_VERIFY_PARAM_free(a->param);
2781 dane_ctx_final(&a->dane);
2784 * Free internal session cache. However: the remove_cb() may reference
2785 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2786 * after the sessions were flushed.
2787 * As the ex_data handling routines might also touch the session cache,
2788 * the most secure solution seems to be: empty (flush) the cache, then
2789 * free ex_data, then finally free the cache.
2790 * (See ticket [openssl.org #212].)
2792 if (a->sessions != NULL)
2793 SSL_CTX_flush_sessions(a, 0);
2795 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2796 lh_SSL_SESSION_free(a->sessions);
2797 X509_STORE_free(a->cert_store);
2798 #ifndef OPENSSL_NO_CT
2799 CTLOG_STORE_free(a->ctlog_store);
2801 sk_SSL_CIPHER_free(a->cipher_list);
2802 sk_SSL_CIPHER_free(a->cipher_list_by_id);
2803 ssl_cert_free(a->cert);
2804 sk_X509_NAME_pop_free(a->ca_names, X509_NAME_free);
2805 sk_X509_pop_free(a->extra_certs, X509_free);
2806 a->comp_methods = NULL;
2807 #ifndef OPENSSL_NO_SRTP
2808 sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2810 #ifndef OPENSSL_NO_SRP
2811 SSL_CTX_SRP_CTX_free(a);
2813 #ifndef OPENSSL_NO_ENGINE
2814 ENGINE_finish(a->client_cert_engine);
2817 #ifndef OPENSSL_NO_EC
2818 OPENSSL_free(a->ext.ecpointformats);
2819 OPENSSL_free(a->ext.supportedgroups);
2821 OPENSSL_free(a->ext.alpn);
2823 CRYPTO_THREAD_lock_free(a->lock);
2828 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2830 ctx->default_passwd_callback = cb;
2833 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2835 ctx->default_passwd_callback_userdata = u;
2838 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2840 return ctx->default_passwd_callback;
2843 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2845 return ctx->default_passwd_callback_userdata;
2848 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
2850 s->default_passwd_callback = cb;
2853 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
2855 s->default_passwd_callback_userdata = u;
2858 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
2860 return s->default_passwd_callback;
2863 void *SSL_get_default_passwd_cb_userdata(SSL *s)
2865 return s->default_passwd_callback_userdata;
2868 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2869 int (*cb) (X509_STORE_CTX *, void *),
2872 ctx->app_verify_callback = cb;
2873 ctx->app_verify_arg = arg;
2876 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
2877 int (*cb) (int, X509_STORE_CTX *))
2879 ctx->verify_mode = mode;
2880 ctx->default_verify_callback = cb;
2883 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2885 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2888 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), void *arg)
2890 ssl_cert_set_cert_cb(c->cert, cb, arg);
2893 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
2895 ssl_cert_set_cert_cb(s->cert, cb, arg);
2898 void ssl_set_masks(SSL *s)
2901 uint32_t *pvalid = s->s3->tmp.valid_flags;
2902 int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
2903 unsigned long mask_k, mask_a;
2904 #ifndef OPENSSL_NO_EC
2905 int have_ecc_cert, ecdsa_ok;
2910 #ifndef OPENSSL_NO_DH
2911 dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
2916 rsa_enc = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
2917 rsa_sign = pvalid[SSL_PKEY_RSA] & CERT_PKEY_VALID;
2918 dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_VALID;
2919 #ifndef OPENSSL_NO_EC
2920 have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
2926 fprintf(stderr, "dht=%d re=%d rs=%d ds=%d\n",
2927 dh_tmp, rsa_enc, rsa_sign, dsa_sign);
2930 #ifndef OPENSSL_NO_GOST
2931 if (ssl_has_cert(s, SSL_PKEY_GOST12_512)) {
2932 mask_k |= SSL_kGOST;
2933 mask_a |= SSL_aGOST12;
2935 if (ssl_has_cert(s, SSL_PKEY_GOST12_256)) {
2936 mask_k |= SSL_kGOST;
2937 mask_a |= SSL_aGOST12;
2939 if (ssl_has_cert(s, SSL_PKEY_GOST01)) {
2940 mask_k |= SSL_kGOST;
2941 mask_a |= SSL_aGOST01;
2951 if (rsa_enc || rsa_sign) {
2959 mask_a |= SSL_aNULL;
2962 * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
2963 * depending on the key usage extension.
2965 #ifndef OPENSSL_NO_EC
2966 if (have_ecc_cert) {
2968 ex_kusage = X509_get_key_usage(c->pkeys[SSL_PKEY_ECC].x509);
2969 ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
2970 if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
2973 mask_a |= SSL_aECDSA;
2975 /* Allow Ed25519 for TLS 1.2 if peer supports it */
2976 if (!(mask_a & SSL_aECDSA) && ssl_has_cert(s, SSL_PKEY_ED25519)
2977 && pvalid[SSL_PKEY_ED25519] & CERT_PKEY_EXPLICIT_SIGN
2978 && TLS1_get_version(s) == TLS1_2_VERSION)
2979 mask_a |= SSL_aECDSA;
2982 #ifndef OPENSSL_NO_EC
2983 mask_k |= SSL_kECDHE;
2986 #ifndef OPENSSL_NO_PSK
2989 if (mask_k & SSL_kRSA)
2990 mask_k |= SSL_kRSAPSK;
2991 if (mask_k & SSL_kDHE)
2992 mask_k |= SSL_kDHEPSK;
2993 if (mask_k & SSL_kECDHE)
2994 mask_k |= SSL_kECDHEPSK;
2997 s->s3->tmp.mask_k = mask_k;
2998 s->s3->tmp.mask_a = mask_a;
3001 #ifndef OPENSSL_NO_EC
3003 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
3005 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
3006 /* key usage, if present, must allow signing */
3007 if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
3008 SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
3009 SSL_R_ECC_CERT_NOT_FOR_SIGNING);
3013 return 1; /* all checks are ok */
3018 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
3019 size_t *serverinfo_length)
3021 CERT_PKEY *cpk = s->s3->tmp.cert;
3022 *serverinfo_length = 0;
3024 if (cpk == NULL || cpk->serverinfo == NULL)
3027 *serverinfo = cpk->serverinfo;
3028 *serverinfo_length = cpk->serverinfo_length;
3032 void ssl_update_cache(SSL *s, int mode)
3037 * If the session_id_length is 0, we are not supposed to cache it, and it
3038 * would be rather hard to do anyway :-)
3040 if (s->session->session_id_length == 0)
3043 i = s->session_ctx->session_cache_mode;
3044 if ((i & mode) && (!s->hit)
3045 && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
3046 || SSL_CTX_add_session(s->session_ctx, s->session))
3047 && (s->session_ctx->new_session_cb != NULL)) {
3048 SSL_SESSION_up_ref(s->session);
3049 if (!s->session_ctx->new_session_cb(s, s->session))
3050 SSL_SESSION_free(s->session);
3053 /* auto flush every 255 connections */
3054 if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
3055 if ((((mode & SSL_SESS_CACHE_CLIENT)
3056 ? s->session_ctx->stats.sess_connect_good
3057 : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
3058 SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
3063 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
3068 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
3073 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
3077 if (s->method != meth) {
3078 const SSL_METHOD *sm = s->method;
3079 int (*hf) (SSL *) = s->handshake_func;
3081 if (sm->version == meth->version)
3086 ret = s->method->ssl_new(s);
3089 if (hf == sm->ssl_connect)
3090 s->handshake_func = meth->ssl_connect;
3091 else if (hf == sm->ssl_accept)
3092 s->handshake_func = meth->ssl_accept;
3097 int SSL_get_error(const SSL *s, int i)
3104 return (SSL_ERROR_NONE);
3107 * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
3108 * where we do encode the error
3110 if ((l = ERR_peek_error()) != 0) {
3111 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
3112 return (SSL_ERROR_SYSCALL);
3114 return (SSL_ERROR_SSL);
3117 if (SSL_want_read(s)) {
3118 bio = SSL_get_rbio(s);
3119 if (BIO_should_read(bio))
3120 return (SSL_ERROR_WANT_READ);
3121 else if (BIO_should_write(bio))
3123 * This one doesn't make too much sense ... We never try to write
3124 * to the rbio, and an application program where rbio and wbio
3125 * are separate couldn't even know what it should wait for.
3126 * However if we ever set s->rwstate incorrectly (so that we have
3127 * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
3128 * wbio *are* the same, this test works around that bug; so it
3129 * might be safer to keep it.
3131 return (SSL_ERROR_WANT_WRITE);
3132 else if (BIO_should_io_special(bio)) {
3133 reason = BIO_get_retry_reason(bio);
3134 if (reason == BIO_RR_CONNECT)
3135 return (SSL_ERROR_WANT_CONNECT);
3136 else if (reason == BIO_RR_ACCEPT)
3137 return (SSL_ERROR_WANT_ACCEPT);
3139 return (SSL_ERROR_SYSCALL); /* unknown */
3143 if (SSL_want_write(s)) {
3144 /* Access wbio directly - in order to use the buffered bio if present */
3146 if (BIO_should_write(bio))
3147 return (SSL_ERROR_WANT_WRITE);
3148 else if (BIO_should_read(bio))
3150 * See above (SSL_want_read(s) with BIO_should_write(bio))
3152 return (SSL_ERROR_WANT_READ);
3153 else if (BIO_should_io_special(bio)) {
3154 reason = BIO_get_retry_reason(bio);
3155 if (reason == BIO_RR_CONNECT)
3156 return (SSL_ERROR_WANT_CONNECT);
3157 else if (reason == BIO_RR_ACCEPT)
3158 return (SSL_ERROR_WANT_ACCEPT);
3160 return (SSL_ERROR_SYSCALL);
3163 if (SSL_want_x509_lookup(s))
3164 return (SSL_ERROR_WANT_X509_LOOKUP);
3165 if (SSL_want_async(s))
3166 return SSL_ERROR_WANT_ASYNC;
3167 if (SSL_want_async_job(s))
3168 return SSL_ERROR_WANT_ASYNC_JOB;
3169 if (SSL_want_early(s))
3170 return SSL_ERROR_WANT_EARLY;
3172 if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
3173 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
3174 return (SSL_ERROR_ZERO_RETURN);
3176 return (SSL_ERROR_SYSCALL);
3179 static int ssl_do_handshake_intern(void *vargs)
3181 struct ssl_async_args *args;
3184 args = (struct ssl_async_args *)vargs;
3187 return s->handshake_func(s);
3190 int SSL_do_handshake(SSL *s)
3194 if (s->handshake_func == NULL) {
3195 SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3199 ossl_statem_check_finish_init(s, -1);
3201 s->method->ssl_renegotiate_check(s, 0);
3203 if (SSL_in_init(s) || SSL_in_before(s)) {
3204 if ((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3205 struct ssl_async_args args;
3209 ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3211 ret = s->handshake_func(s);
3217 void SSL_set_accept_state(SSL *s)
3221 ossl_statem_clear(s);
3222 s->handshake_func = s->method->ssl_accept;
3226 void SSL_set_connect_state(SSL *s)
3230 ossl_statem_clear(s);
3231 s->handshake_func = s->method->ssl_connect;
3235 int ssl_undefined_function(SSL *s)
3237 SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3241 int ssl_undefined_void_function(void)
3243 SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3244 ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3248 int ssl_undefined_const_function(const SSL *s)
3253 const SSL_METHOD *ssl_bad_method(int ver)
3255 SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3259 const char *ssl_protocol_to_string(int version)
3263 case TLS1_3_VERSION:
3266 case TLS1_2_VERSION:
3269 case TLS1_1_VERSION:
3284 case DTLS1_2_VERSION:
3292 const char *SSL_get_version(const SSL *s)
3294 return ssl_protocol_to_string(s->version);
3297 SSL *SSL_dup(SSL *s)
3299 STACK_OF(X509_NAME) *sk;
3304 /* If we're not quiescent, just up_ref! */
3305 if (!SSL_in_init(s) || !SSL_in_before(s)) {
3306 CRYPTO_UP_REF(&s->references, &i, s->lock);
3311 * Otherwise, copy configuration state, and session if set.
3313 if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3316 if (s->session != NULL) {
3318 * Arranges to share the same session via up_ref. This "copies"
3319 * session-id, SSL_METHOD, sid_ctx, and 'cert'
3321 if (!SSL_copy_session_id(ret, s))
3325 * No session has been established yet, so we have to expect that
3326 * s->cert or ret->cert will be changed later -- they should not both
3327 * point to the same object, and thus we can't use
3328 * SSL_copy_session_id.
3330 if (!SSL_set_ssl_method(ret, s->method))
3333 if (s->cert != NULL) {
3334 ssl_cert_free(ret->cert);
3335 ret->cert = ssl_cert_dup(s->cert);
3336 if (ret->cert == NULL)
3340 if (!SSL_set_session_id_context(ret, s->sid_ctx,
3341 (int)s->sid_ctx_length))
3345 if (!ssl_dane_dup(ret, s))
3347 ret->version = s->version;
3348 ret->options = s->options;
3349 ret->mode = s->mode;
3350 SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3351 SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3352 ret->msg_callback = s->msg_callback;
3353 ret->msg_callback_arg = s->msg_callback_arg;
3354 SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3355 SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
3356 ret->generate_session_id = s->generate_session_id;
3358 SSL_set_info_callback(ret, SSL_get_info_callback(s));
3360 /* copy app data, a little dangerous perhaps */
3361 if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
3364 /* setup rbio, and wbio */
3365 if (s->rbio != NULL) {
3366 if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
3369 if (s->wbio != NULL) {
3370 if (s->wbio != s->rbio) {
3371 if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
3374 BIO_up_ref(ret->rbio);
3375 ret->wbio = ret->rbio;
3379 ret->server = s->server;
3380 if (s->handshake_func) {
3382 SSL_set_accept_state(ret);
3384 SSL_set_connect_state(ret);
3386 ret->shutdown = s->shutdown;
3389 ret->default_passwd_callback = s->default_passwd_callback;
3390 ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
3392 X509_VERIFY_PARAM_inherit(ret->param, s->param);
3394 /* dup the cipher_list and cipher_list_by_id stacks */
3395 if (s->cipher_list != NULL) {
3396 if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
3399 if (s->cipher_list_by_id != NULL)
3400 if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
3404 /* Dup the client_CA list */
3405 if (s->ca_names != NULL) {
3406 if ((sk = sk_X509_NAME_dup(s->ca_names)) == NULL)
3409 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
3410 xn = sk_X509_NAME_value(sk, i);
3411 if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
3424 void ssl_clear_cipher_ctx(SSL *s)
3426 if (s->enc_read_ctx != NULL) {
3427 EVP_CIPHER_CTX_free(s->enc_read_ctx);
3428 s->enc_read_ctx = NULL;
3430 if (s->enc_write_ctx != NULL) {
3431 EVP_CIPHER_CTX_free(s->enc_write_ctx);
3432 s->enc_write_ctx = NULL;
3434 #ifndef OPENSSL_NO_COMP
3435 COMP_CTX_free(s->expand);
3437 COMP_CTX_free(s->compress);
3442 X509 *SSL_get_certificate(const SSL *s)
3444 if (s->cert != NULL)
3445 return (s->cert->key->x509);
3450 EVP_PKEY *SSL_get_privatekey(const SSL *s)
3452 if (s->cert != NULL)
3453 return (s->cert->key->privatekey);
3458 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3460 if (ctx->cert != NULL)
3461 return ctx->cert->key->x509;
3466 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3468 if (ctx->cert != NULL)
3469 return ctx->cert->key->privatekey;
3474 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
3476 if ((s->session != NULL) && (s->session->cipher != NULL))
3477 return (s->session->cipher);
3481 const COMP_METHOD *SSL_get_current_compression(SSL *s)
3483 #ifndef OPENSSL_NO_COMP
3484 return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
3490 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
3492 #ifndef OPENSSL_NO_COMP
3493 return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
3499 int ssl_init_wbio_buffer(SSL *s)
3503 if (s->bbio != NULL) {
3504 /* Already buffered. */
3508 bbio = BIO_new(BIO_f_buffer());
3509 if (bbio == NULL || !BIO_set_read_buffer_size(bbio, 1)) {
3511 SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
3515 s->wbio = BIO_push(bbio, s->wbio);
3520 int ssl_free_wbio_buffer(SSL *s)
3522 /* callers ensure s is never null */
3523 if (s->bbio == NULL)
3526 s->wbio = BIO_pop(s->wbio);
3527 if (!ossl_assert(s->wbio != NULL))
3535 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3537 ctx->quiet_shutdown = mode;
3540 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3542 return (ctx->quiet_shutdown);
3545 void SSL_set_quiet_shutdown(SSL *s, int mode)
3547 s->quiet_shutdown = mode;
3550 int SSL_get_quiet_shutdown(const SSL *s)
3552 return (s->quiet_shutdown);
3555 void SSL_set_shutdown(SSL *s, int mode)
3560 int SSL_get_shutdown(const SSL *s)
3565 int SSL_version(const SSL *s)
3570 int SSL_client_version(const SSL *s)
3572 return s->client_version;
3575 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3580 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3583 if (ssl->ctx == ctx)
3586 ctx = ssl->session_ctx;
3587 new_cert = ssl_cert_dup(ctx->cert);
3588 if (new_cert == NULL) {
3592 if (!custom_exts_copy_flags(&new_cert->custext, &ssl->cert->custext)) {
3593 ssl_cert_free(new_cert);
3597 ssl_cert_free(ssl->cert);
3598 ssl->cert = new_cert;
3601 * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3602 * so setter APIs must prevent invalid lengths from entering the system.
3604 if (!ossl_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx)))
3608 * If the session ID context matches that of the parent SSL_CTX,
3609 * inherit it from the new SSL_CTX as well. If however the context does
3610 * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3611 * leave it unchanged.
3613 if ((ssl->ctx != NULL) &&
3614 (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3615 (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3616 ssl->sid_ctx_length = ctx->sid_ctx_length;
3617 memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3620 SSL_CTX_up_ref(ctx);
3621 SSL_CTX_free(ssl->ctx); /* decrement reference count */
3627 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3629 return (X509_STORE_set_default_paths(ctx->cert_store));
3632 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
3634 X509_LOOKUP *lookup;
3636 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
3639 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
3641 /* Clear any errors if the default directory does not exist */
3647 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
3649 X509_LOOKUP *lookup;
3651 lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
3655 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
3657 /* Clear any errors if the default file does not exist */
3663 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3666 return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3669 void SSL_set_info_callback(SSL *ssl,
3670 void (*cb) (const SSL *ssl, int type, int val))
3672 ssl->info_callback = cb;
3676 * One compiler (Diab DCC) doesn't like argument names in returned function
3679 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3682 return ssl->info_callback;
3685 void SSL_set_verify_result(SSL *ssl, long arg)
3687 ssl->verify_result = arg;
3690 long SSL_get_verify_result(const SSL *ssl)
3692 return (ssl->verify_result);
3695 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
3698 return sizeof(ssl->s3->client_random);
3699 if (outlen > sizeof(ssl->s3->client_random))
3700 outlen = sizeof(ssl->s3->client_random);
3701 memcpy(out, ssl->s3->client_random, outlen);
3705 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
3708 return sizeof(ssl->s3->server_random);
3709 if (outlen > sizeof(ssl->s3->server_random))
3710 outlen = sizeof(ssl->s3->server_random);
3711 memcpy(out, ssl->s3->server_random, outlen);
3715 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
3716 unsigned char *out, size_t outlen)
3719 return session->master_key_length;
3720 if (outlen > session->master_key_length)
3721 outlen = session->master_key_length;
3722 memcpy(out, session->master_key, outlen);
3726 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3728 return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3731 void *SSL_get_ex_data(const SSL *s, int idx)
3733 return (CRYPTO_get_ex_data(&s->ex_data, idx));
3736 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3738 return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3741 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3743 return (CRYPTO_get_ex_data(&s->ex_data, idx));
3746 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3748 return (ctx->cert_store);
3751 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3753 X509_STORE_free(ctx->cert_store);
3754 ctx->cert_store = store;
3757 void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store)
3760 X509_STORE_up_ref(store);
3761 SSL_CTX_set_cert_store(ctx, store);
3764 int SSL_want(const SSL *s)
3766 return (s->rwstate);
3770 * \brief Set the callback for generating temporary DH keys.
3771 * \param ctx the SSL context.
3772 * \param dh the callback
3775 #ifndef OPENSSL_NO_DH
3776 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3777 DH *(*dh) (SSL *ssl, int is_export,
3780 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3783 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3786 SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3790 #ifndef OPENSSL_NO_PSK
3791 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3793 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3794 SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3797 OPENSSL_free(ctx->cert->psk_identity_hint);
3798 if (identity_hint != NULL) {
3799 ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3800 if (ctx->cert->psk_identity_hint == NULL)
3803 ctx->cert->psk_identity_hint = NULL;
3807 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3812 if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3813 SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3816 OPENSSL_free(s->cert->psk_identity_hint);
3817 if (identity_hint != NULL) {
3818 s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3819 if (s->cert->psk_identity_hint == NULL)
3822 s->cert->psk_identity_hint = NULL;
3826 const char *SSL_get_psk_identity_hint(const SSL *s)
3828 if (s == NULL || s->session == NULL)
3830 return (s->session->psk_identity_hint);
3833 const char *SSL_get_psk_identity(const SSL *s)
3835 if (s == NULL || s->session == NULL)
3837 return (s->session->psk_identity);
3840 void SSL_set_psk_client_callback(SSL *s, SSL_psk_client_cb_func cb)
3842 s->psk_client_callback = cb;
3845 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb)
3847 ctx->psk_client_callback = cb;
3850 void SSL_set_psk_server_callback(SSL *s, SSL_psk_server_cb_func cb)
3852 s->psk_server_callback = cb;
3855 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb)
3857 ctx->psk_server_callback = cb;
3861 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
3862 void (*cb) (int write_p, int version,
3863 int content_type, const void *buf,
3864 size_t len, SSL *ssl, void *arg))
3866 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3869 void SSL_set_msg_callback(SSL *ssl,
3870 void (*cb) (int write_p, int version,
3871 int content_type, const void *buf,
3872 size_t len, SSL *ssl, void *arg))
3874 SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3877 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
3878 int (*cb) (SSL *ssl,
3882 SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3883 (void (*)(void))cb);
3886 void SSL_set_not_resumable_session_callback(SSL *ssl,
3887 int (*cb) (SSL *ssl,
3888 int is_forward_secure))
3890 SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3891 (void (*)(void))cb);
3894 void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
3895 size_t (*cb) (SSL *ssl, int type,
3896 size_t len, void *arg))
3898 ctx->record_padding_cb = cb;
3901 void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg)
3903 ctx->record_padding_arg = arg;
3906 void *SSL_CTX_get_record_padding_callback_arg(SSL_CTX *ctx)
3908 return ctx->record_padding_arg;
3911 int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size)
3913 /* block size of 0 or 1 is basically no padding */
3914 if (block_size == 1)
3915 ctx->block_padding = 0;
3916 else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
3917 ctx->block_padding = block_size;
3923 void SSL_set_record_padding_callback(SSL *ssl,
3924 size_t (*cb) (SSL *ssl, int type,
3925 size_t len, void *arg))
3927 ssl->record_padding_cb = cb;
3930 void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg)
3932 ssl->record_padding_arg = arg;
3935 void *SSL_get_record_padding_callback_arg(SSL *ssl)
3937 return ssl->record_padding_arg;
3940 int SSL_set_block_padding(SSL *ssl, size_t block_size)
3942 /* block size of 0 or 1 is basically no padding */
3943 if (block_size == 1)
3944 ssl->block_padding = 0;
3945 else if (block_size <= SSL3_RT_MAX_PLAIN_LENGTH)
3946 ssl->block_padding = block_size;
3953 * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3954 * variable, freeing EVP_MD_CTX previously stored in that variable, if any.
3955 * If EVP_MD pointer is passed, initializes ctx with this |md|.
3956 * Returns the newly allocated ctx;
3959 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3961 ssl_clear_hash_ctx(hash);
3962 *hash = EVP_MD_CTX_new();
3963 if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
3964 EVP_MD_CTX_free(*hash);
3971 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3974 EVP_MD_CTX_free(*hash);
3978 /* Retrieve handshake hashes */
3979 int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
3982 EVP_MD_CTX *ctx = NULL;
3983 EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
3984 int hashleni = EVP_MD_CTX_size(hdgst);
3987 if (hashleni < 0 || (size_t)hashleni > outlen)
3990 ctx = EVP_MD_CTX_new();
3994 if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
3995 || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
3998 *hashlen = hashleni;
4002 EVP_MD_CTX_free(ctx);
4006 int SSL_session_reused(SSL *s)
4011 int SSL_is_server(const SSL *s)
4016 #if OPENSSL_API_COMPAT < 0x10100000L
4017 void SSL_set_debug(SSL *s, int debug)
4019 /* Old function was do-nothing anyway... */
4025 void SSL_set_security_level(SSL *s, int level)
4027 s->cert->sec_level = level;
4030 int SSL_get_security_level(const SSL *s)
4032 return s->cert->sec_level;
4035 void SSL_set_security_callback(SSL *s,
4036 int (*cb) (const SSL *s, const SSL_CTX *ctx,
4037 int op, int bits, int nid,
4038 void *other, void *ex))
4040 s->cert->sec_cb = cb;
4043 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
4044 const SSL_CTX *ctx, int op,
4045 int bits, int nid, void *other,
4047 return s->cert->sec_cb;
4050 void SSL_set0_security_ex_data(SSL *s, void *ex)
4052 s->cert->sec_ex = ex;
4055 void *SSL_get0_security_ex_data(const SSL *s)
4057 return s->cert->sec_ex;
4060 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
4062 ctx->cert->sec_level = level;
4065 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
4067 return ctx->cert->sec_level;
4070 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
4071 int (*cb) (const SSL *s, const SSL_CTX *ctx,
4072 int op, int bits, int nid,
4073 void *other, void *ex))
4075 ctx->cert->sec_cb = cb;
4078 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
4084 return ctx->cert->sec_cb;
4087 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
4089 ctx->cert->sec_ex = ex;
4092 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
4094 return ctx->cert->sec_ex;
4098 * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
4099 * can return unsigned long, instead of the generic long return value from the
4100 * control interface.
4102 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
4104 return ctx->options;
4107 unsigned long SSL_get_options(const SSL *s)
4112 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
4114 return ctx->options |= op;
4117 unsigned long SSL_set_options(SSL *s, unsigned long op)
4119 return s->options |= op;
4122 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
4124 return ctx->options &= ~op;
4127 unsigned long SSL_clear_options(SSL *s, unsigned long op)
4129 return s->options &= ~op;
4132 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
4134 return s->verified_chain;
4137 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
4139 #ifndef OPENSSL_NO_CT
4142 * Moves SCTs from the |src| stack to the |dst| stack.
4143 * The source of each SCT will be set to |origin|.
4144 * If |dst| points to a NULL pointer, a new stack will be created and owned by
4146 * Returns the number of SCTs moved, or a negative integer if an error occurs.
4148 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src,
4149 sct_source_t origin)
4155 *dst = sk_SCT_new_null();
4157 SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
4162 while ((sct = sk_SCT_pop(src)) != NULL) {
4163 if (SCT_set_source(sct, origin) != 1)
4166 if (sk_SCT_push(*dst, sct) <= 0)
4174 sk_SCT_push(src, sct); /* Put the SCT back */
4179 * Look for data collected during ServerHello and parse if found.
4180 * Returns the number of SCTs extracted.
4182 static int ct_extract_tls_extension_scts(SSL *s)
4184 int scts_extracted = 0;
4186 if (s->ext.scts != NULL) {
4187 const unsigned char *p = s->ext.scts;
4188 STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->ext.scts_len);
4190 scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
4192 SCT_LIST_free(scts);
4195 return scts_extracted;
4199 * Checks for an OCSP response and then attempts to extract any SCTs found if it
4200 * contains an SCT X509 extension. They will be stored in |s->scts|.
4202 * - The number of SCTs extracted, assuming an OCSP response exists.
4203 * - 0 if no OCSP response exists or it contains no SCTs.
4204 * - A negative integer if an error occurs.
4206 static int ct_extract_ocsp_response_scts(SSL *s)
4208 # ifndef OPENSSL_NO_OCSP
4209 int scts_extracted = 0;
4210 const unsigned char *p;
4211 OCSP_BASICRESP *br = NULL;
4212 OCSP_RESPONSE *rsp = NULL;
4213 STACK_OF(SCT) *scts = NULL;
4216 if (s->ext.ocsp.resp == NULL || s->ext.ocsp.resp_len == 0)
4219 p = s->ext.ocsp.resp;
4220 rsp = d2i_OCSP_RESPONSE(NULL, &p, (int)s->ext.ocsp.resp_len);
4224 br = OCSP_response_get1_basic(rsp);
4228 for (i = 0; i < OCSP_resp_count(br); ++i) {
4229 OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
4235 OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
4237 ct_move_scts(&s->scts, scts, SCT_SOURCE_OCSP_STAPLED_RESPONSE);
4238 if (scts_extracted < 0)
4242 SCT_LIST_free(scts);
4243 OCSP_BASICRESP_free(br);
4244 OCSP_RESPONSE_free(rsp);
4245 return scts_extracted;
4247 /* Behave as if no OCSP response exists */
4253 * Attempts to extract SCTs from the peer certificate.
4254 * Return the number of SCTs extracted, or a negative integer if an error
4257 static int ct_extract_x509v3_extension_scts(SSL *s)
4259 int scts_extracted = 0;
4260 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4263 STACK_OF(SCT) *scts =
4264 X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
4267 ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
4269 SCT_LIST_free(scts);
4272 return scts_extracted;
4276 * Attempts to find all received SCTs by checking TLS extensions, the OCSP
4277 * response (if it exists) and X509v3 extensions in the certificate.
4278 * Returns NULL if an error occurs.
4280 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
4282 if (!s->scts_parsed) {
4283 if (ct_extract_tls_extension_scts(s) < 0 ||
4284 ct_extract_ocsp_response_scts(s) < 0 ||
4285 ct_extract_x509v3_extension_scts(s) < 0)
4295 static int ct_permissive(const CT_POLICY_EVAL_CTX * ctx,
4296 const STACK_OF(SCT) *scts, void *unused_arg)
4301 static int ct_strict(const CT_POLICY_EVAL_CTX * ctx,
4302 const STACK_OF(SCT) *scts, void *unused_arg)
4304 int count = scts != NULL ? sk_SCT_num(scts) : 0;
4307 for (i = 0; i < count; ++i) {
4308 SCT *sct = sk_SCT_value(scts, i);
4309 int status = SCT_get_validation_status(sct);
4311 if (status == SCT_VALIDATION_STATUS_VALID)
4314 SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
4318 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
4322 * Since code exists that uses the custom extension handler for CT, look
4323 * for this and throw an error if they have already registered to use CT.
4325 if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
4326 TLSEXT_TYPE_signed_certificate_timestamp))
4328 SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
4329 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4333 if (callback != NULL) {
4335 * If we are validating CT, then we MUST accept SCTs served via OCSP
4337 if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
4341 s->ct_validation_callback = callback;
4342 s->ct_validation_callback_arg = arg;
4347 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
4348 ssl_ct_validation_cb callback, void *arg)
4351 * Since code exists that uses the custom extension handler for CT, look for
4352 * this and throw an error if they have already registered to use CT.
4354 if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
4355 TLSEXT_TYPE_signed_certificate_timestamp))
4357 SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
4358 SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4362 ctx->ct_validation_callback = callback;
4363 ctx->ct_validation_callback_arg = arg;
4367 int SSL_ct_is_enabled(const SSL *s)
4369 return s->ct_validation_callback != NULL;
4372 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
4374 return ctx->ct_validation_callback != NULL;
4377 int ssl_validate_ct(SSL *s)
4380 X509 *cert = s->session != NULL ? s->session->peer : NULL;
4382 SSL_DANE *dane = &s->dane;
4383 CT_POLICY_EVAL_CTX *ctx = NULL;
4384 const STACK_OF(SCT) *scts;
4387 * If no callback is set, the peer is anonymous, or its chain is invalid,
4388 * skip SCT validation - just return success. Applications that continue
4389 * handshakes without certificates, with unverified chains, or pinned leaf
4390 * certificates are outside the scope of the WebPKI and CT.
4392 * The above exclusions notwithstanding the vast majority of peers will
4393 * have rather ordinary certificate chains validated by typical
4394 * applications that perform certificate verification and therefore will
4395 * process SCTs when enabled.
4397 if (s->ct_validation_callback == NULL || cert == NULL ||
4398 s->verify_result != X509_V_OK ||
4399 s->verified_chain == NULL || sk_X509_num(s->verified_chain) <= 1)
4403 * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
4404 * trust-anchors. See https://tools.ietf.org/html/rfc7671#section-4.2
4406 if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
4407 switch (dane->mtlsa->usage) {
4408 case DANETLS_USAGE_DANE_TA:
4409 case DANETLS_USAGE_DANE_EE:
4414 ctx = CT_POLICY_EVAL_CTX_new();
4416 SSLerr(SSL_F_SSL_VALIDATE_CT, ERR_R_MALLOC_FAILURE);
4420 issuer = sk_X509_value(s->verified_chain, 1);
4421 CT_POLICY_EVAL_CTX_set1_cert(ctx, cert);
4422 CT_POLICY_EVAL_CTX_set1_issuer(ctx, issuer);
4423 CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(ctx, s->ctx->ctlog_store);
4424 CT_POLICY_EVAL_CTX_set_time(
4425 ctx, (uint64_t)SSL_SESSION_get_time(SSL_get0_session(s)) * 1000);
4427 scts = SSL_get0_peer_scts(s);
4430 * This function returns success (> 0) only when all the SCTs are valid, 0
4431 * when some are invalid, and < 0 on various internal errors (out of
4432 * memory, etc.). Having some, or even all, invalid SCTs is not sufficient
4433 * reason to abort the handshake, that decision is up to the callback.
4434 * Therefore, we error out only in the unexpected case that the return
4435 * value is negative.
4437 * XXX: One might well argue that the return value of this function is an
4438 * unfortunate design choice. Its job is only to determine the validation
4439 * status of each of the provided SCTs. So long as it correctly separates
4440 * the wheat from the chaff it should return success. Failure in this case
4441 * ought to correspond to an inability to carry out its duties.
4443 if (SCT_LIST_validate(scts, ctx) < 0) {
4444 SSLerr(SSL_F_SSL_VALIDATE_CT, SSL_R_SCT_VERIFICATION_FAILED);
4448 ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
4450 ret = 0; /* This function returns 0 on failure */
4453 CT_POLICY_EVAL_CTX_free(ctx);
4455 * With SSL_VERIFY_NONE the session may be cached and re-used despite a
4456 * failure return code here. Also the application may wish the complete
4457 * the handshake, and then disconnect cleanly at a higher layer, after
4458 * checking the verification status of the completed connection.
4460 * We therefore force a certificate verification failure which will be
4461 * visible via SSL_get_verify_result() and cached as part of any resumed
4464 * Note: the permissive callback is for information gathering only, always
4465 * returns success, and does not affect verification status. Only the
4466 * strict callback or a custom application-specified callback can trigger
4467 * connection failure or record a verification error.
4470 s->verify_result = X509_V_ERR_NO_VALID_SCTS;
4474 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
4476 switch (validation_mode) {
4478 SSLerr(SSL_F_SSL_CTX_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4480 case SSL_CT_VALIDATION_PERMISSIVE:
4481 return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
4482 case SSL_CT_VALIDATION_STRICT:
4483 return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
4487 int SSL_enable_ct(SSL *s, int validation_mode)
4489 switch (validation_mode) {
4491 SSLerr(SSL_F_SSL_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4493 case SSL_CT_VALIDATION_PERMISSIVE:
4494 return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
4495 case SSL_CT_VALIDATION_STRICT:
4496 return SSL_set_ct_validation_callback(s, ct_strict, NULL);
4500 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
4502 return CTLOG_STORE_load_default_file(ctx->ctlog_store);
4505 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
4507 return CTLOG_STORE_load_file(ctx->ctlog_store, path);
4510 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE * logs)
4512 CTLOG_STORE_free(ctx->ctlog_store);
4513 ctx->ctlog_store = logs;
4516 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
4518 return ctx->ctlog_store;
4521 #endif /* OPENSSL_NO_CT */
4523 void SSL_CTX_set_early_cb(SSL_CTX *c, SSL_early_cb_fn cb, void *arg)
4526 c->early_cb_arg = arg;
4529 int SSL_early_isv2(SSL *s)
4531 if (s->clienthello == NULL)
4533 return s->clienthello->isv2;
4536 unsigned int SSL_early_get0_legacy_version(SSL *s)
4538 if (s->clienthello == NULL)
4540 return s->clienthello->legacy_version;
4543 size_t SSL_early_get0_random(SSL *s, const unsigned char **out)
4545 if (s->clienthello == NULL)
4548 *out = s->clienthello->random;
4549 return SSL3_RANDOM_SIZE;
4552 size_t SSL_early_get0_session_id(SSL *s, const unsigned char **out)
4554 if (s->clienthello == NULL)
4557 *out = s->clienthello->session_id;
4558 return s->clienthello->session_id_len;
4561 size_t SSL_early_get0_ciphers(SSL *s, const unsigned char **out)
4563 if (s->clienthello == NULL)
4566 *out = PACKET_data(&s->clienthello->ciphersuites);
4567 return PACKET_remaining(&s->clienthello->ciphersuites);
4570 size_t SSL_early_get0_compression_methods(SSL *s, const unsigned char **out)
4572 if (s->clienthello == NULL)
4575 *out = s->clienthello->compressions;
4576 return s->clienthello->compressions_len;
4579 int SSL_early_get1_extensions_present(SSL *s, int **out, size_t *outlen)
4585 if (s->clienthello == NULL || out == NULL || outlen == NULL)
4587 for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
4588 ext = s->clienthello->pre_proc_exts + i;
4592 present = OPENSSL_malloc(sizeof(*present) * num);
4593 if (present == NULL)
4595 for (i = 0; i < s->clienthello->pre_proc_exts_len; i++) {
4596 ext = s->clienthello->pre_proc_exts + i;
4598 if (ext->received_order >= num)
4600 present[ext->received_order] = ext->type;
4607 OPENSSL_free(present);
4611 int SSL_early_get0_ext(SSL *s, unsigned int type, const unsigned char **out,
4617 if (s->clienthello == NULL)
4619 for (i = 0; i < s->clienthello->pre_proc_exts_len; ++i) {
4620 r = s->clienthello->pre_proc_exts + i;
4621 if (r->present && r->type == type) {
4623 *out = PACKET_data(&r->data);
4625 *outlen = PACKET_remaining(&r->data);
4632 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
4634 ctx->keylog_callback = cb;
4637 SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
4639 return ctx->keylog_callback;
4642 static int nss_keylog_int(const char *prefix,
4644 const uint8_t *parameter_1,
4645 size_t parameter_1_len,
4646 const uint8_t *parameter_2,
4647 size_t parameter_2_len)
4650 char *cursor = NULL;
4655 if (ssl->ctx->keylog_callback == NULL) return 1;
4658 * Our output buffer will contain the following strings, rendered with
4659 * space characters in between, terminated by a NULL character: first the
4660 * prefix, then the first parameter, then the second parameter. The
4661 * meaning of each parameter depends on the specific key material being
4662 * logged. Note that the first and second parameters are encoded in
4663 * hexadecimal, so we need a buffer that is twice their lengths.
4665 prefix_len = strlen(prefix);
4666 out_len = prefix_len + (2*parameter_1_len) + (2*parameter_2_len) + 3;
4667 if ((out = cursor = OPENSSL_malloc(out_len)) == NULL) {
4668 SSLerr(SSL_F_NSS_KEYLOG_INT, ERR_R_MALLOC_FAILURE);
4672 strcpy(cursor, prefix);
4673 cursor += prefix_len;
4676 for (i = 0; i < parameter_1_len; i++) {
4677 sprintf(cursor, "%02x", parameter_1[i]);
4682 for (i = 0; i < parameter_2_len; i++) {
4683 sprintf(cursor, "%02x", parameter_2[i]);
4688 ssl->ctx->keylog_callback(ssl, (const char *)out);
4694 int ssl_log_rsa_client_key_exchange(SSL *ssl,
4695 const uint8_t *encrypted_premaster,
4696 size_t encrypted_premaster_len,
4697 const uint8_t *premaster,
4698 size_t premaster_len)
4700 if (encrypted_premaster_len < 8) {
4701 SSLerr(SSL_F_SSL_LOG_RSA_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
4705 /* We only want the first 8 bytes of the encrypted premaster as a tag. */
4706 return nss_keylog_int("RSA",
4708 encrypted_premaster,
4714 int ssl_log_secret(SSL *ssl,
4716 const uint8_t *secret,
4719 return nss_keylog_int(label,
4721 ssl->s3->client_random,
4727 #define SSLV2_CIPHER_LEN 3
4729 int ssl_cache_cipherlist(SSL *s, PACKET *cipher_suites, int sslv2format,
4734 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
4736 if (PACKET_remaining(cipher_suites) == 0) {
4737 SSLerr(SSL_F_SSL_CACHE_CIPHERLIST, SSL_R_NO_CIPHERS_SPECIFIED);
4738 *al = SSL_AD_ILLEGAL_PARAMETER;
4742 if (PACKET_remaining(cipher_suites) % n != 0) {
4743 SSLerr(SSL_F_SSL_CACHE_CIPHERLIST,
4744 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
4745 *al = SSL_AD_DECODE_ERROR;
4749 OPENSSL_free(s->s3->tmp.ciphers_raw);
4750 s->s3->tmp.ciphers_raw = NULL;
4751 s->s3->tmp.ciphers_rawlen = 0;
4754 size_t numciphers = PACKET_remaining(cipher_suites) / n;
4755 PACKET sslv2ciphers = *cipher_suites;
4756 unsigned int leadbyte;
4760 * We store the raw ciphers list in SSLv3+ format so we need to do some
4761 * preprocessing to convert the list first. If there are any SSLv2 only
4762 * ciphersuites with a non-zero leading byte then we are going to
4763 * slightly over allocate because we won't store those. But that isn't a
4766 raw = OPENSSL_malloc(numciphers * TLS_CIPHER_LEN);
4767 s->s3->tmp.ciphers_raw = raw;
4769 *al = SSL_AD_INTERNAL_ERROR;
4772 for (s->s3->tmp.ciphers_rawlen = 0;
4773 PACKET_remaining(&sslv2ciphers) > 0;
4774 raw += TLS_CIPHER_LEN) {
4775 if (!PACKET_get_1(&sslv2ciphers, &leadbyte)
4777 && !PACKET_copy_bytes(&sslv2ciphers, raw,
4780 && !PACKET_forward(&sslv2ciphers, TLS_CIPHER_LEN))) {
4781 *al = SSL_AD_DECODE_ERROR;
4782 OPENSSL_free(s->s3->tmp.ciphers_raw);
4783 s->s3->tmp.ciphers_raw = NULL;
4784 s->s3->tmp.ciphers_rawlen = 0;
4788 s->s3->tmp.ciphers_rawlen += TLS_CIPHER_LEN;
4790 } else if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
4791 &s->s3->tmp.ciphers_rawlen)) {
4792 *al = SSL_AD_INTERNAL_ERROR;
4800 int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
4801 int isv2format, STACK_OF(SSL_CIPHER) **sk,
4802 STACK_OF(SSL_CIPHER) **scsvs)
4807 if (!PACKET_buf_init(&pkt, bytes, len))
4809 return bytes_to_cipher_list(s, &pkt, sk, scsvs, isv2format, &alert);
4812 int bytes_to_cipher_list(SSL *s, PACKET *cipher_suites,
4813 STACK_OF(SSL_CIPHER) **skp,
4814 STACK_OF(SSL_CIPHER) **scsvs_out,
4815 int sslv2format, int *al)
4817 const SSL_CIPHER *c;
4818 STACK_OF(SSL_CIPHER) *sk = NULL;
4819 STACK_OF(SSL_CIPHER) *scsvs = NULL;
4821 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
4822 unsigned char cipher[SSLV2_CIPHER_LEN];
4824 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
4826 if (PACKET_remaining(cipher_suites) == 0) {
4827 SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
4828 *al = SSL_AD_ILLEGAL_PARAMETER;
4832 if (PACKET_remaining(cipher_suites) % n != 0) {
4833 SSLerr(SSL_F_BYTES_TO_CIPHER_LIST,
4834 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
4835 *al = SSL_AD_DECODE_ERROR;
4839 sk = sk_SSL_CIPHER_new_null();
4840 scsvs = sk_SSL_CIPHER_new_null();
4841 if (sk == NULL || scsvs == NULL) {
4842 SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
4843 *al = SSL_AD_INTERNAL_ERROR;
4847 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
4849 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
4850 * first byte set to zero, while true SSLv2 ciphers have a non-zero
4851 * first byte. We don't support any true SSLv2 ciphers, so skip them.
4853 if (sslv2format && cipher[0] != '\0')
4856 /* For SSLv2-compat, ignore leading 0-byte. */
4857 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher, 1);
4859 if ((c->valid && !sk_SSL_CIPHER_push(sk, c)) ||
4860 (!c->valid && !sk_SSL_CIPHER_push(scsvs, c))) {
4861 SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
4862 *al = SSL_AD_INTERNAL_ERROR;
4867 if (PACKET_remaining(cipher_suites) > 0) {
4868 *al = SSL_AD_DECODE_ERROR;
4869 SSLerr(SSL_F_BYTES_TO_CIPHER_LIST, SSL_R_BAD_LENGTH);
4876 sk_SSL_CIPHER_free(sk);
4877 if (scsvs_out != NULL)
4880 sk_SSL_CIPHER_free(scsvs);
4883 sk_SSL_CIPHER_free(sk);
4884 sk_SSL_CIPHER_free(scsvs);
4888 int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
4890 ctx->max_early_data = max_early_data;
4895 uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
4897 return ctx->max_early_data;
4900 int SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
4902 s->max_early_data = max_early_data;
4907 uint32_t SSL_get_max_early_data(const SSL *s)
4909 return s->max_early_data;