Path: blob/main/crypto/openssl/ssl/statem/extensions.c
104925 views
/*1* Copyright 2016-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#if defined(__TANDEM) && defined(_SPT_MODEL_)10#include <spthread.h>11#include <spt_extensions.h> /* timeval */12#endif1314#include <string.h>15#include "internal/nelem.h"16#include "internal/cryptlib.h"17#include "internal/ssl_unwrap.h"18#include "../ssl_local.h"19#include "statem_local.h"2021static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent);22static int init_server_name(SSL_CONNECTION *s, unsigned int context);23static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent);24static int final_ec_pt_formats(SSL_CONNECTION *s, unsigned int context,25int sent);26static int init_session_ticket(SSL_CONNECTION *s, unsigned int context);27#ifndef OPENSSL_NO_OCSP28static int init_status_request(SSL_CONNECTION *s, unsigned int context);29#endif30#ifndef OPENSSL_NO_NEXTPROTONEG31static int init_npn(SSL_CONNECTION *s, unsigned int context);32#endif33static int init_alpn(SSL_CONNECTION *s, unsigned int context);34static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent);35static int init_sig_algs_cert(SSL_CONNECTION *s, unsigned int context);36static int init_sig_algs(SSL_CONNECTION *s, unsigned int context);37static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context);38static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context);39static int init_certificate_authorities(SSL_CONNECTION *s,40unsigned int context);41static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,42WPACKET *pkt,43unsigned int context,44X509 *x,45size_t chainidx);46static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,47unsigned int context, X509 *x,48size_t chainidx);49#ifndef OPENSSL_NO_SRP50static int init_srp(SSL_CONNECTION *s, unsigned int context);51#endif52static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context);53static int init_etm(SSL_CONNECTION *s, unsigned int context);54static int init_ems(SSL_CONNECTION *s, unsigned int context);55static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent);56static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context);57static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent);58#ifndef OPENSSL_NO_SRTP59static int init_srtp(SSL_CONNECTION *s, unsigned int context);60#endif61static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent);62static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,63int sent);64static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent);65static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,66int sent);67static int init_post_handshake_auth(SSL_CONNECTION *s, unsigned int context);68static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent);69static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context);70static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,71unsigned int context,72X509 *x, size_t chainidx);73static int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt,74unsigned int context,75X509 *x, size_t chainidx);7677/* Structure to define a built-in extension */78typedef struct extensions_definition_st {79/* The defined type for the extension */80unsigned int type;81/*82* The context that this extension applies to, e.g. what messages and83* protocol versions84*/85unsigned int context;86/*87* Initialise extension before parsing. Always called for relevant contexts88* even if extension not present89*/90int (*init)(SSL_CONNECTION *s, unsigned int context);91/* Parse extension sent from client to server */92int (*parse_ctos)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,93X509 *x, size_t chainidx);94/* Parse extension send from server to client */95int (*parse_stoc)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,96X509 *x, size_t chainidx);97/* Construct extension sent from server to client */98EXT_RETURN (*construct_stoc)(SSL_CONNECTION *s, WPACKET *pkt,99unsigned int context,100X509 *x, size_t chainidx);101/* Construct extension sent from client to server */102EXT_RETURN (*construct_ctos)(SSL_CONNECTION *s, WPACKET *pkt,103unsigned int context,104X509 *x, size_t chainidx);105/*106* Finalise extension after parsing. Always called where an extensions was107* initialised even if the extension was not present. |sent| is set to 1 if108* the extension was seen, or 0 otherwise.109*/110int (*final)(SSL_CONNECTION *s, unsigned int context, int sent);111} EXTENSION_DEFINITION;112113/*114* Definitions of all built-in extensions. NOTE: Changes in the number or order115* of these extensions should be mirrored with equivalent changes to the116* indexes ( TLSEXT_IDX_* ) defined in ssl_local.h.117* Extensions should be added to test/ext_internal_test.c as well, as that118* tests the ordering of the extensions.119*120* Each extension has an initialiser, a client and121* server side parser and a finaliser. The initialiser is called (if the122* extension is relevant to the given context) even if we did not see the123* extension in the message that we received. The parser functions are only124* called if we see the extension in the message. The finalisers are always125* called if the initialiser was called.126* There are also server and client side constructor functions which are always127* called during message construction if the extension is relevant for the128* given context.129* The initialisation, parsing, finalisation and construction functions are130* always called in the order defined in this list. Some extensions may depend131* on others having been processed first, so the order of this list is132* significant.133* The extension context is defined by a series of flags which specify which134* messages the extension is relevant to. These flags also specify whether the135* extension is relevant to a particular protocol or protocol version.136*137* NOTE: WebSphere Application Server 7+ cannot handle empty extensions at138* the end, keep these extensions before signature_algorithm.139*/140#define INVALID_EXTENSION { TLSEXT_TYPE_invalid, 0, NULL, NULL, NULL, NULL, NULL, NULL }141static const EXTENSION_DEFINITION ext_defs[] = {142{ TLSEXT_TYPE_renegotiate,143SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO144| SSL_EXT_SSL3_ALLOWED | SSL_EXT_TLS1_2_AND_BELOW_ONLY,145NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,146tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,147final_renegotiate },148{ TLSEXT_TYPE_server_name,149SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO150| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,151init_server_name,152tls_parse_ctos_server_name, tls_parse_stoc_server_name,153tls_construct_stoc_server_name, tls_construct_ctos_server_name,154final_server_name },155{ TLSEXT_TYPE_max_fragment_length,156SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO157| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,158NULL, tls_parse_ctos_maxfragmentlen, tls_parse_stoc_maxfragmentlen,159tls_construct_stoc_maxfragmentlen, tls_construct_ctos_maxfragmentlen,160final_maxfragmentlen },161#ifndef OPENSSL_NO_SRP162{ TLSEXT_TYPE_srp,163SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_AND_BELOW_ONLY,164init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL },165#else166INVALID_EXTENSION,167#endif168{ TLSEXT_TYPE_ec_point_formats,169SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO170| SSL_EXT_TLS1_2_AND_BELOW_ONLY,171init_ec_point_formats, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,172tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,173final_ec_pt_formats },174{ /*175* "supported_groups" is spread across several specifications.176* It was originally specified as "elliptic_curves" in RFC 4492,177* and broadened to include named FFDH groups by RFC 7919.178* Both RFCs 4492 and 7919 do not include a provision for the server179* to indicate to the client the complete list of groups supported180* by the server, with the server instead just indicating the181* selected group for this connection in the ServerKeyExchange182* message. TLS 1.3 adds a scheme for the server to indicate183* to the client its list of supported groups in the184* EncryptedExtensions message, but none of the relevant185* specifications permit sending supported_groups in the ServerHello.186* Nonetheless (possibly due to the close proximity to the187* "ec_point_formats" extension, which is allowed in the ServerHello),188* there are several servers that send this extension in the189* ServerHello anyway. Up to and including the 1.1.0 release,190* we did not check for the presence of nonpermitted extensions,191* so to avoid a regression, we must permit this extension in the192* TLS 1.2 ServerHello as well.193*194* Note that there is no tls_parse_stoc_supported_groups function,195* so we do not perform any additional parsing, validation, or196* processing on the server's group list -- this is just a minimal197* change to preserve compatibility with these misbehaving servers.198*/199TLSEXT_TYPE_supported_groups,200SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS201| SSL_EXT_TLS1_2_SERVER_HELLO,202NULL, tls_parse_ctos_supported_groups, NULL,203tls_construct_stoc_supported_groups,204tls_construct_ctos_supported_groups, NULL },205{ TLSEXT_TYPE_session_ticket,206SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO207| SSL_EXT_TLS1_2_AND_BELOW_ONLY,208init_session_ticket, tls_parse_ctos_session_ticket,209tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,210tls_construct_ctos_session_ticket, NULL },211#ifndef OPENSSL_NO_OCSP212{ TLSEXT_TYPE_status_request,213SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO214| SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,215init_status_request, tls_parse_ctos_status_request,216tls_parse_stoc_status_request, tls_construct_stoc_status_request,217tls_construct_ctos_status_request, NULL },218#else219INVALID_EXTENSION,220#endif221#ifndef OPENSSL_NO_NEXTPROTONEG222{ TLSEXT_TYPE_next_proto_neg,223SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO224| SSL_EXT_TLS1_2_AND_BELOW_ONLY,225init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,226tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL },227#else228INVALID_EXTENSION,229#endif230{ /*231* Must appear in this list after server_name so that finalisation232* happens after server_name callbacks233*/234TLSEXT_TYPE_application_layer_protocol_negotiation,235SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO236| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,237init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,238tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn },239#ifndef OPENSSL_NO_SRTP240{ TLSEXT_TYPE_use_srtp,241SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO242| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_DTLS_ONLY,243init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,244tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL },245#else246INVALID_EXTENSION,247#endif248{ TLSEXT_TYPE_encrypt_then_mac,249SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO250| SSL_EXT_TLS1_2_AND_BELOW_ONLY,251init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,252tls_construct_stoc_etm, tls_construct_ctos_etm, NULL },253#ifndef OPENSSL_NO_CT254{ TLSEXT_TYPE_signed_certificate_timestamp,255SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO256| SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,257NULL,258/*259* No server side support for this, but can be provided by a custom260* extension. This is an exception to the rule that custom extensions261* cannot override built in ones.262*/263NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct, NULL },264#else265INVALID_EXTENSION,266#endif267{ TLSEXT_TYPE_extended_master_secret,268SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO269| SSL_EXT_TLS1_2_AND_BELOW_ONLY,270init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,271tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems },272{ TLSEXT_TYPE_signature_algorithms_cert,273SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,274init_sig_algs_cert, tls_parse_ctos_sig_algs_cert,275tls_parse_ctos_sig_algs_cert,276/* We do not generate signature_algorithms_cert at present. */277NULL, NULL, NULL },278{279TLSEXT_TYPE_post_handshake_auth,280SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,281init_post_handshake_auth,282tls_parse_ctos_post_handshake_auth,283NULL,284NULL,285tls_construct_ctos_post_handshake_auth,286NULL,287},288{ TLSEXT_TYPE_client_cert_type,289SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS290| SSL_EXT_TLS1_2_SERVER_HELLO,291init_client_cert_type,292tls_parse_ctos_client_cert_type, tls_parse_stoc_client_cert_type,293tls_construct_stoc_client_cert_type, tls_construct_ctos_client_cert_type,294NULL },295{ TLSEXT_TYPE_server_cert_type,296SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS297| SSL_EXT_TLS1_2_SERVER_HELLO,298init_server_cert_type,299tls_parse_ctos_server_cert_type, tls_parse_stoc_server_cert_type,300tls_construct_stoc_server_cert_type, tls_construct_ctos_server_cert_type,301NULL },302{ TLSEXT_TYPE_signature_algorithms,303SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,304init_sig_algs, tls_parse_ctos_sig_algs,305tls_parse_ctos_sig_algs, tls_construct_ctos_sig_algs,306tls_construct_ctos_sig_algs, final_sig_algs },307{ TLSEXT_TYPE_supported_versions,308SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO309| SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY,310NULL,311/* Processed inline as part of version selection */312NULL, tls_parse_stoc_supported_versions,313tls_construct_stoc_supported_versions,314tls_construct_ctos_supported_versions, final_supported_versions },315{ TLSEXT_TYPE_psk_kex_modes,316SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS_IMPLEMENTATION_ONLY317| SSL_EXT_TLS1_3_ONLY,318init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,319tls_construct_ctos_psk_kex_modes, NULL },320{ /*321* Must be in this list after supported_groups. We need that to have322* been parsed before we do this one.323*/324TLSEXT_TYPE_key_share,325SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO326| SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY327| SSL_EXT_TLS1_3_ONLY,328NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,329tls_construct_stoc_key_share, tls_construct_ctos_key_share,330final_key_share },331{ /* Must be after key_share */332TLSEXT_TYPE_cookie,333SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST334| SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,335NULL, tls_parse_ctos_cookie, tls_parse_stoc_cookie,336tls_construct_stoc_cookie, tls_construct_ctos_cookie, NULL },337{ /*338* Special unsolicited ServerHello extension only used when339* SSL_OP_CRYPTOPRO_TLSEXT_BUG is set. We allow it in a ClientHello but340* ignore it.341*/342TLSEXT_TYPE_cryptopro_bug,343SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO344| SSL_EXT_TLS1_2_AND_BELOW_ONLY,345NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL },346{ TLSEXT_TYPE_compress_certificate,347SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST348| SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,349tls_init_compress_certificate,350tls_parse_compress_certificate, tls_parse_compress_certificate,351tls_construct_compress_certificate, tls_construct_compress_certificate,352NULL },353{ TLSEXT_TYPE_early_data,354SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS355| SSL_EXT_TLS1_3_NEW_SESSION_TICKET | SSL_EXT_TLS1_3_ONLY,356NULL, tls_parse_ctos_early_data, tls_parse_stoc_early_data,357tls_construct_stoc_early_data, tls_construct_ctos_early_data,358final_early_data },359{360TLSEXT_TYPE_certificate_authorities,361SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST362| SSL_EXT_TLS1_3_ONLY,363init_certificate_authorities,364tls_parse_certificate_authorities,365tls_parse_certificate_authorities,366tls_construct_certificate_authorities,367tls_construct_certificate_authorities,368NULL,369},370{ /* Must be immediately before pre_shared_key */371TLSEXT_TYPE_padding,372SSL_EXT_CLIENT_HELLO,373NULL,374/* We send this, but don't read it */375NULL, NULL, NULL, tls_construct_ctos_padding, NULL },376{ /* Required by the TLSv1.3 spec to always be the last extension */377TLSEXT_TYPE_psk,378SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO379| SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,380NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,381tls_construct_ctos_psk, final_psk }382};383384/* Returns a TLSEXT_TYPE for the given index */385unsigned int ossl_get_extension_type(size_t idx)386{387size_t num_exts = OSSL_NELEM(ext_defs);388389if (idx >= num_exts)390return TLSEXT_TYPE_out_of_range;391392return ext_defs[idx].type;393}394395/* Check whether an extension's context matches the current context */396static int validate_context(SSL_CONNECTION *s, unsigned int extctx,397unsigned int thisctx)398{399/* Check we're allowed to use this extension in this context */400if ((thisctx & extctx) == 0)401return 0;402403if (SSL_CONNECTION_IS_DTLS(s)) {404if ((extctx & SSL_EXT_TLS_ONLY) != 0)405return 0;406} else if ((extctx & SSL_EXT_DTLS_ONLY) != 0) {407return 0;408}409410return 1;411}412413int tls_validate_all_contexts(SSL_CONNECTION *s, unsigned int thisctx,414RAW_EXTENSION *exts)415{416size_t i, num_exts, builtin_num = OSSL_NELEM(ext_defs), offset;417RAW_EXTENSION *thisext;418unsigned int context;419ENDPOINT role = ENDPOINT_BOTH;420421if ((thisctx & SSL_EXT_CLIENT_HELLO) != 0)422role = ENDPOINT_SERVER;423else if ((thisctx & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)424role = ENDPOINT_CLIENT;425426/* Calculate the number of extensions in the extensions list */427num_exts = builtin_num + s->cert->custext.meths_count;428429for (thisext = exts, i = 0; i < num_exts; i++, thisext++) {430if (!thisext->present)431continue;432433if (i < builtin_num) {434context = ext_defs[i].context;435} else {436custom_ext_method *meth = NULL;437438meth = custom_ext_find(&s->cert->custext, role, thisext->type,439&offset);440if (!ossl_assert(meth != NULL))441return 0;442context = meth->context;443}444445if (!validate_context(s, context, thisctx))446return 0;447}448449return 1;450}451452/*453* Verify whether we are allowed to use the extension |type| in the current454* |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to455* indicate the extension is not allowed. If returning 1 then |*found| is set to456* the definition for the extension we found.457*/458static int verify_extension(SSL_CONNECTION *s, unsigned int context,459unsigned int type, custom_ext_methods *meths,460RAW_EXTENSION *rawexlist, RAW_EXTENSION **found)461{462size_t i;463size_t builtin_num = OSSL_NELEM(ext_defs);464const EXTENSION_DEFINITION *thisext;465466for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {467if (type == thisext->type) {468if (!validate_context(s, thisext->context, context))469return 0;470471*found = &rawexlist[i];472return 1;473}474}475476/* Check the custom extensions */477if (meths != NULL) {478size_t offset = 0;479ENDPOINT role = ENDPOINT_BOTH;480custom_ext_method *meth = NULL;481482if ((context & SSL_EXT_CLIENT_HELLO) != 0)483role = ENDPOINT_SERVER;484else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)485role = ENDPOINT_CLIENT;486487meth = custom_ext_find(meths, role, type, &offset);488if (meth != NULL) {489if (!validate_context(s, meth->context, context))490return 0;491*found = &rawexlist[offset + builtin_num];492return 1;493}494}495496/* Unknown extension. We allow it */497*found = NULL;498return 1;499}500501/*502* Check whether the context defined for an extension |extctx| means whether503* the extension is relevant for the current context |thisctx| or not. Returns504* 1 if the extension is relevant for this context, and 0 otherwise505*/506int extension_is_relevant(SSL_CONNECTION *s, unsigned int extctx,507unsigned int thisctx)508{509int is_tls13;510511/*512* For HRR we haven't selected the version yet but we know it will be513* TLSv1.3514*/515if ((thisctx & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)516is_tls13 = 1;517else518is_tls13 = SSL_CONNECTION_IS_TLS13(s);519520if ((SSL_CONNECTION_IS_DTLS(s)521&& (extctx & SSL_EXT_TLS_IMPLEMENTATION_ONLY) != 0)522|| (s->version == SSL3_VERSION523&& (extctx & SSL_EXT_SSL3_ALLOWED) == 0)524/*525* Note that SSL_IS_TLS13() means "TLS 1.3 has been negotiated",526* which is never true when generating the ClientHello.527* However, version negotiation *has* occurred by the time the528* ClientHello extensions are being parsed.529* Be careful to allow TLS 1.3-only extensions when generating530* the ClientHello.531*/532|| (is_tls13 && (extctx & SSL_EXT_TLS1_2_AND_BELOW_ONLY) != 0)533|| (!is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0534&& (thisctx & SSL_EXT_CLIENT_HELLO) == 0)535|| (s->server && !is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0)536|| (s->hit && (extctx & SSL_EXT_IGNORE_ON_RESUMPTION) != 0))537return 0;538return 1;539}540541/*542* Gather a list of all the extensions from the data in |packet]. |context|543* tells us which message this extension is for. The raw extension data is544* stored in |*res| on success. We don't actually process the content of the545* extensions yet, except to check their types. This function also runs the546* initialiser functions for all known extensions if |init| is nonzero (whether547* we have collected them or not). If successful the caller is responsible for548* freeing the contents of |*res|.549*550* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be551* more than one extension of the same type in a ClientHello or ServerHello.552* This function returns 1 if all extensions are unique and we have parsed their553* types, and 0 if the extensions contain duplicates, could not be successfully554* found, or an internal error occurred. We only check duplicates for555* extensions that we know about. We ignore others.556*/557int tls_collect_extensions(SSL_CONNECTION *s, PACKET *packet,558unsigned int context,559RAW_EXTENSION **res, size_t *len, int init)560{561PACKET extensions = *packet;562size_t i = 0;563size_t num_exts;564custom_ext_methods *exts = &s->cert->custext;565RAW_EXTENSION *raw_extensions = NULL;566const EXTENSION_DEFINITION *thisexd;567568*res = NULL;569570/*571* Initialise server side custom extensions. Client side is done during572* construction of extensions for the ClientHello.573*/574if ((context & SSL_EXT_CLIENT_HELLO) != 0)575custom_ext_init(&s->cert->custext);576577num_exts = OSSL_NELEM(ext_defs) + (exts != NULL ? exts->meths_count : 0);578raw_extensions = OPENSSL_zalloc(num_exts * sizeof(*raw_extensions));579if (raw_extensions == NULL) {580SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);581return 0;582}583584i = 0;585while (PACKET_remaining(&extensions) > 0) {586unsigned int type, idx;587PACKET extension;588RAW_EXTENSION *thisex;589590if (!PACKET_get_net_2(&extensions, &type) || !PACKET_get_length_prefixed_2(&extensions, &extension)) {591SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);592goto err;593}594/*595* Verify this extension is allowed. We only check duplicates for596* extensions that we recognise. We also have a special case for the597* PSK extension, which must be the last one in the ClientHello.598*/599if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)600|| (thisex != NULL && thisex->present == 1)601|| (type == TLSEXT_TYPE_psk602&& (context & SSL_EXT_CLIENT_HELLO) != 0603&& PACKET_remaining(&extensions) != 0)) {604SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);605goto err;606}607idx = thisex - raw_extensions;608/*-609* Check that we requested this extension (if appropriate). Requests can610* be sent in the ClientHello and CertificateRequest. Unsolicited611* extensions can be sent in the NewSessionTicket. We only do this for612* the built-in extensions. Custom extensions have a different but613* similar check elsewhere.614* Special cases:615* - The HRR cookie extension is unsolicited616* - The renegotiate extension is unsolicited (the client signals617* support via an SCSV)618* - The signed_certificate_timestamp extension can be provided by a619* custom extension or by the built-in version. We let the extension620* itself handle unsolicited response checks.621*/622if (idx < OSSL_NELEM(ext_defs)623&& (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0624&& type != TLSEXT_TYPE_cookie625&& type != TLSEXT_TYPE_renegotiate626&& type != TLSEXT_TYPE_signed_certificate_timestamp627&& (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0628#ifndef OPENSSL_NO_GOST629&& !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0630&& type == TLSEXT_TYPE_cryptopro_bug)631#endif632) {633SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,634SSL_R_UNSOLICITED_EXTENSION);635goto err;636}637if (thisex != NULL) {638thisex->data = extension;639thisex->present = 1;640thisex->type = type;641thisex->received_order = i++;642if (s->ext.debug_cb)643s->ext.debug_cb(SSL_CONNECTION_GET_USER_SSL(s), !s->server,644thisex->type, PACKET_data(&thisex->data),645PACKET_remaining(&thisex->data),646s->ext.debug_arg);647}648}649650if (init) {651/*652* Initialise all known extensions relevant to this context,653* whether we have found them or not654*/655for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);656i++, thisexd++) {657if (thisexd->init != NULL && (thisexd->context & context) != 0658&& extension_is_relevant(s, thisexd->context, context)659&& !thisexd->init(s, context)) {660/* SSLfatal() already called */661goto err;662}663}664}665666*res = raw_extensions;667if (len != NULL)668*len = num_exts;669return 1;670671err:672OPENSSL_free(raw_extensions);673return 0;674}675676/*677* Runs the parser for a given extension with index |idx|. |exts| contains the678* list of all parsed extensions previously collected by679* tls_collect_extensions(). The parser is only run if it is applicable for the680* given |context| and the parser has not already been run. If this is for a681* Certificate message, then we also provide the parser with the relevant682* Certificate |x| and its position in the |chainidx| with 0 being the first683* Certificate. Returns 1 on success or 0 on failure. If an extension is not684* present this counted as success.685*/686int tls_parse_extension(SSL_CONNECTION *s, TLSEXT_INDEX idx, int context,687RAW_EXTENSION *exts, X509 *x, size_t chainidx)688{689RAW_EXTENSION *currext = &exts[idx];690int (*parser)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context, X509 *x,691size_t chainidx)692= NULL;693694/* Skip if the extension is not present */695if (!currext->present)696return 1;697698/* Skip if we've already parsed this extension */699if (currext->parsed)700return 1;701702currext->parsed = 1;703704if (idx < OSSL_NELEM(ext_defs)) {705/* We are handling a built-in extension */706const EXTENSION_DEFINITION *extdef = &ext_defs[idx];707708/* Check if extension is defined for our protocol. If not, skip */709if (!extension_is_relevant(s, extdef->context, context))710return 1;711712parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;713714if (parser != NULL)715return parser(s, &currext->data, context, x, chainidx);716717/*718* If the parser is NULL we fall through to the custom extension719* processing720*/721}722723/* Parse custom extensions */724return custom_ext_parse(s, context, currext->type,725PACKET_data(&currext->data),726PACKET_remaining(&currext->data),727x, chainidx);728}729730/*731* Parse all remaining extensions that have not yet been parsed. Also calls the732* finalisation for all extensions at the end if |fin| is nonzero, whether we733* collected them or not. Returns 1 for success or 0 for failure. If we are734* working on a Certificate message then we also pass the Certificate |x| and735* its position in the |chainidx|, with 0 being the first certificate.736*/737int tls_parse_all_extensions(SSL_CONNECTION *s, int context,738RAW_EXTENSION *exts, X509 *x,739size_t chainidx, int fin)740{741size_t i, numexts = OSSL_NELEM(ext_defs);742const EXTENSION_DEFINITION *thisexd;743744/* Calculate the number of extensions in the extensions list */745numexts += s->cert->custext.meths_count;746747/* Parse each extension in turn */748for (i = 0; i < numexts; i++) {749if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {750/* SSLfatal() already called */751return 0;752}753}754755if (fin) {756/*757* Finalise all known extensions relevant to this context,758* whether we have found them or not759*/760for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);761i++, thisexd++) {762if (thisexd->final != NULL && (thisexd->context & context) != 0763&& !thisexd->final(s, context, exts[i].present)) {764/* SSLfatal() already called */765return 0;766}767}768}769770return 1;771}772773int should_add_extension(SSL_CONNECTION *s, unsigned int extctx,774unsigned int thisctx, int max_version)775{776/* Skip if not relevant for our context */777if ((extctx & thisctx) == 0)778return 0;779780/* Check if this extension is defined for our protocol. If not, skip */781if (!extension_is_relevant(s, extctx, thisctx)782|| ((extctx & SSL_EXT_TLS1_3_ONLY) != 0783&& (thisctx & SSL_EXT_CLIENT_HELLO) != 0784&& (SSL_CONNECTION_IS_DTLS(s) || max_version < TLS1_3_VERSION)))785return 0;786787return 1;788}789790/*791* Construct all the extensions relevant to the current |context| and write792* them to |pkt|. If this is an extension for a Certificate in a Certificate793* message, then |x| will be set to the Certificate we are handling, and794* |chainidx| will indicate the position in the chainidx we are processing (with795* 0 being the first in the chain). Returns 1 on success or 0 on failure. On a796* failure construction stops at the first extension to fail to construct.797*/798int tls_construct_extensions(SSL_CONNECTION *s, WPACKET *pkt,799unsigned int context,800X509 *x, size_t chainidx)801{802size_t i;803int min_version, max_version = 0, reason;804const EXTENSION_DEFINITION *thisexd;805int for_comp = (context & SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION) != 0;806807if (!WPACKET_start_sub_packet_u16(pkt)808/*809* If extensions are of zero length then we don't even add the810* extensions length bytes to a ClientHello/ServerHello811* (for non-TLSv1.3).812*/813|| ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0814&& !WPACKET_set_flags(pkt,815WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {816if (!for_comp)817SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);818return 0;819}820821if ((context & SSL_EXT_CLIENT_HELLO) != 0) {822reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);823if (reason != 0) {824if (!for_comp)825SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);826return 0;827}828}829830/* Add custom extensions first */831if ((context & SSL_EXT_CLIENT_HELLO) != 0) {832/* On the server side with initialise during ClientHello parsing */833custom_ext_init(&s->cert->custext);834}835if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {836/* SSLfatal() already called */837return 0;838}839840for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {841EXT_RETURN (*construct)(SSL_CONNECTION *s, WPACKET *pkt,842unsigned int context,843X509 *x, size_t chainidx);844EXT_RETURN ret;845846/* Skip if not relevant for our context */847if (!should_add_extension(s, thisexd->context, context, max_version))848continue;849850construct = s->server ? thisexd->construct_stoc851: thisexd->construct_ctos;852853if (construct == NULL)854continue;855856ret = construct(s, pkt, context, x, chainidx);857if (ret == EXT_RETURN_FAIL) {858/* SSLfatal() already called */859return 0;860}861if (ret == EXT_RETURN_SENT862&& (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)863s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;864}865866if (!WPACKET_close(pkt)) {867if (!for_comp)868SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);869return 0;870}871872return 1;873}874875/*876* Built in extension finalisation and initialisation functions. All initialise877* or finalise the associated extension type for the given |context|. For878* finalisers |sent| is set to 1 if we saw the extension during parsing, and 0879* otherwise. These functions return 1 on success or 0 on failure.880*/881882static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent)883{884if (!s->server) {885/*886* Check if we can connect to a server that doesn't support safe887* renegotiation888*/889if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)890&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)891&& !sent) {892SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,893SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);894return 0;895}896897return 1;898}899900/* Need RI if renegotiating */901if (s->renegotiate902&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)903&& !sent) {904SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,905SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);906return 0;907}908909return 1;910}911912static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,913TSAN_QUALIFIER int *stat)914{915if (ssl_tsan_lock(ctx)) {916tsan_decr(stat);917ssl_tsan_unlock(ctx);918}919}920921static int init_server_name(SSL_CONNECTION *s, unsigned int context)922{923if (s->server) {924s->servername_done = 0;925926OPENSSL_free(s->ext.hostname);927s->ext.hostname = NULL;928}929930return 1;931}932933static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)934{935int ret = SSL_TLSEXT_ERR_NOACK;936int altmp = SSL_AD_UNRECOGNIZED_NAME;937SSL *ssl = SSL_CONNECTION_GET_SSL(s);938SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);939SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);940int was_ticket = (SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0;941942if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {943SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);944return 0;945}946947if (sctx->ext.servername_cb != NULL)948ret = sctx->ext.servername_cb(ussl, &altmp,949sctx->ext.servername_arg);950else if (s->session_ctx->ext.servername_cb != NULL)951ret = s->session_ctx->ext.servername_cb(ussl, &altmp,952s->session_ctx->ext.servername_arg);953954/*955* For servers, propagate the SNI hostname from the temporary956* storage in the SSL to the persistent SSL_SESSION, now that we957* know we accepted it.958* Clients make this copy when parsing the server's response to959* the extension, which is when they find out that the negotiation960* was successful.961*/962if (s->server) {963if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {964/* Only store the hostname in the session if we accepted it. */965OPENSSL_free(s->session->ext.hostname);966s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);967if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {968SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);969}970}971}972973/*974* If we switched contexts (whether here or in the client_hello callback),975* move the sess_accept increment from the session_ctx to the new976* context, to avoid the confusing situation of having sess_accept_good977* exceed sess_accept (zero) for the new context.978*/979if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx980&& s->hello_retry_request == SSL_HRR_NONE) {981ssl_tsan_counter(sctx, &sctx->stats.sess_accept);982ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);983}984985/*986* If we're expecting to send a ticket, and tickets were previously enabled,987* and now tickets are disabled, then turn off expected ticket.988* Also, if this is not a resumption, create a new session ID989*/990if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected991&& was_ticket && (SSL_get_options(ssl) & SSL_OP_NO_TICKET) != 0) {992s->ext.ticket_expected = 0;993if (!s->hit) {994SSL_SESSION *ss = SSL_get_session(ssl);995996if (ss != NULL) {997OPENSSL_free(ss->ext.tick);998ss->ext.tick = NULL;999ss->ext.ticklen = 0;1000ss->ext.tick_lifetime_hint = 0;1001ss->ext.tick_age_add = 0;1002if (!ssl_generate_session_id(s, ss)) {1003SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1004return 0;1005}1006} else {1007SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1008return 0;1009}1010}1011}10121013switch (ret) {1014case SSL_TLSEXT_ERR_ALERT_FATAL:1015SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);1016return 0;10171018case SSL_TLSEXT_ERR_ALERT_WARNING:1019/* TLSv1.3 doesn't have warning alerts so we suppress this */1020if (!SSL_CONNECTION_IS_TLS13(s))1021ssl3_send_alert(s, SSL3_AL_WARNING, altmp);1022s->servername_done = 0;1023return 1;10241025case SSL_TLSEXT_ERR_NOACK:1026s->servername_done = 0;1027return 1;10281029default:1030return 1;1031}1032}10331034static int final_ec_pt_formats(SSL_CONNECTION *s, unsigned int context,1035int sent)1036{1037unsigned long alg_k, alg_a;10381039if (s->server)1040return 1;10411042alg_k = s->s3.tmp.new_cipher->algorithm_mkey;1043alg_a = s->s3.tmp.new_cipher->algorithm_auth;10441045/*1046* If we are client and using an elliptic curve cryptography cipher1047* suite, then if server returns an EC point formats lists extension it1048* must contain uncompressed.1049*/1050if (s->ext.ecpointformats != NULL1051&& s->ext.ecpointformats_len > 01052&& s->ext.peer_ecpointformats != NULL1053&& s->ext.peer_ecpointformats_len > 01054&& ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {1055/* we are using an ECC cipher */1056size_t i;1057unsigned char *list = s->ext.peer_ecpointformats;10581059for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {1060if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)1061break;1062}1063if (i == s->ext.peer_ecpointformats_len) {1064SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1065SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);1066return 0;1067}1068}10691070return 1;1071}10721073static int init_session_ticket(SSL_CONNECTION *s, unsigned int context)1074{1075if (!s->server)1076s->ext.ticket_expected = 0;10771078return 1;1079}10801081#ifndef OPENSSL_NO_OCSP1082static int init_status_request(SSL_CONNECTION *s, unsigned int context)1083{1084if (s->server) {1085s->ext.status_type = TLSEXT_STATUSTYPE_nothing;1086} else {1087/*1088* Ensure we get sensible values passed to tlsext_status_cb in the event1089* that we don't receive a status message1090*/1091OPENSSL_free(s->ext.ocsp.resp);1092s->ext.ocsp.resp = NULL;1093s->ext.ocsp.resp_len = 0;1094}10951096return 1;1097}1098#endif10991100#ifndef OPENSSL_NO_NEXTPROTONEG1101static int init_npn(SSL_CONNECTION *s, unsigned int context)1102{1103s->s3.npn_seen = 0;11041105return 1;1106}1107#endif11081109static int init_alpn(SSL_CONNECTION *s, unsigned int context)1110{1111OPENSSL_free(s->s3.alpn_selected);1112s->s3.alpn_selected = NULL;1113s->s3.alpn_selected_len = 0;1114if (s->server) {1115OPENSSL_free(s->s3.alpn_proposed);1116s->s3.alpn_proposed = NULL;1117s->s3.alpn_proposed_len = 0;1118}1119return 1;1120}11211122static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent)1123{1124if (!s->server && !sent && s->session->ext.alpn_selected != NULL)1125s->ext.early_data_ok = 0;11261127if (!s->server || !SSL_CONNECTION_IS_TLS13(s))1128return 1;11291130/*1131* Call alpn_select callback if needed. Has to be done after SNI and1132* cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.31133* we also have to do this before we decide whether to accept early_data.1134* In TLSv1.3 we've already negotiated our cipher so we do this call now.1135* For < TLSv1.3 we defer it until after cipher negotiation.1136*1137* On failure SSLfatal() already called.1138*/1139return tls_handle_alpn(s);1140}11411142static int init_sig_algs(SSL_CONNECTION *s, unsigned int context)1143{1144/* Clear any signature algorithms extension received */1145OPENSSL_free(s->s3.tmp.peer_sigalgs);1146s->s3.tmp.peer_sigalgs = NULL;1147s->s3.tmp.peer_sigalgslen = 0;11481149return 1;1150}11511152static int init_sig_algs_cert(SSL_CONNECTION *s,1153ossl_unused unsigned int context)1154{1155/* Clear any signature algorithms extension received */1156OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);1157s->s3.tmp.peer_cert_sigalgs = NULL;1158s->s3.tmp.peer_cert_sigalgslen = 0;11591160return 1;1161}11621163#ifndef OPENSSL_NO_SRP1164static int init_srp(SSL_CONNECTION *s, unsigned int context)1165{1166OPENSSL_free(s->srp_ctx.login);1167s->srp_ctx.login = NULL;11681169return 1;1170}1171#endif11721173static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context)1174{1175OPENSSL_free(s->ext.peer_ecpointformats);1176s->ext.peer_ecpointformats = NULL;1177s->ext.peer_ecpointformats_len = 0;11781179return 1;1180}11811182static int init_etm(SSL_CONNECTION *s, unsigned int context)1183{1184s->ext.use_etm = 0;11851186return 1;1187}11881189static int init_ems(SSL_CONNECTION *s, unsigned int context)1190{1191if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {1192s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;1193s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;1194}11951196return 1;1197}11981199static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent)1200{1201/*1202* Check extended master secret extension is not dropped on1203* renegotiation.1204*/1205if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)1206&& (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {1207SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);1208return 0;1209}1210if (!s->server && s->hit) {1211/*1212* Check extended master secret extension is consistent with1213* original session.1214*/1215if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {1216SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);1217return 0;1218}1219}12201221return 1;1222}12231224static int init_certificate_authorities(SSL_CONNECTION *s, unsigned int context)1225{1226sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);1227s->s3.tmp.peer_ca_names = NULL;1228return 1;1229}12301231static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,1232WPACKET *pkt,1233unsigned int context,1234X509 *x,1235size_t chainidx)1236{1237const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);12381239if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)1240return EXT_RETURN_NOT_SENT;12411242if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)1243|| !WPACKET_start_sub_packet_u16(pkt)) {1244SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1245return EXT_RETURN_FAIL;1246}12471248if (!construct_ca_names(s, ca_sk, pkt)) {1249/* SSLfatal() already called */1250return EXT_RETURN_FAIL;1251}12521253if (!WPACKET_close(pkt)) {1254SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1255return EXT_RETURN_FAIL;1256}12571258return EXT_RETURN_SENT;1259}12601261static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,1262unsigned int context, X509 *x,1263size_t chainidx)1264{1265if (!parse_ca_names(s, pkt))1266return 0;1267if (PACKET_remaining(pkt) != 0) {1268SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);1269return 0;1270}1271return 1;1272}12731274#ifndef OPENSSL_NO_SRTP1275static int init_srtp(SSL_CONNECTION *s, unsigned int context)1276{1277if (s->server)1278s->srtp_profile = NULL;12791280return 1;1281}1282#endif12831284static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent)1285{1286if (!sent && SSL_CONNECTION_IS_TLS13(s) && !s->hit) {1287SSLfatal(s, TLS13_AD_MISSING_EXTENSION,1288SSL_R_MISSING_SIGALGS_EXTENSION);1289return 0;1290}12911292return 1;1293}12941295static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,1296int sent)1297{1298if (!sent && context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) {1299SSLfatal(s, TLS13_AD_MISSING_EXTENSION,1300SSL_R_MISSING_SUPPORTED_VERSIONS_EXTENSION);1301return 0;1302}13031304return 1;1305}13061307static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent)1308{1309#if !defined(OPENSSL_NO_TLS1_3)1310if (!SSL_CONNECTION_IS_TLS13(s))1311return 1;13121313/* Nothing to do for key_share in an HRR */1314if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)1315return 1;13161317/*1318* If1319* we are a client1320* AND1321* we have no key_share1322* AND1323* (we are not resuming1324* OR the kex_mode doesn't allow non key_share resumes)1325* THEN1326* fail;1327*/1328if (!s->server1329&& !sent) {1330if ((s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {1331SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_SUITABLE_KEY_SHARE);1332return 0;1333}1334if (!s->hit) {1335SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);1336return 0;1337}1338}1339/*1340* IF1341* we are a server1342* THEN1343* IF1344* we have a suitable key_share1345* THEN1346* IF1347* we are stateless AND we have no cookie1348* THEN1349* send a HelloRetryRequest1350* ELSE1351* IF1352* we didn't already send a HelloRetryRequest1353* AND1354* the client sent a key_share extension1355* AND1356* (we are not resuming1357* OR the kex_mode allows key_share resumes)1358* AND1359* a shared group exists1360* THEN1361* send a HelloRetryRequest1362* ELSE IF1363* we are not resuming1364* OR1365* the kex_mode doesn't allow non key_share resumes1366* THEN1367* fail1368* ELSE IF1369* we are stateless AND we have no cookie1370* THEN1371* send a HelloRetryRequest1372*/1373if (s->server) {1374if (s->s3.peer_tmp != NULL) {1375/* We have a suitable key_share */1376if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 01377&& !s->ext.cookieok) {1378if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {1379/*1380* If we are stateless then we wouldn't know about any1381* previously sent HRR - so how can this be anything other1382* than 0?1383*/1384SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1385return 0;1386}1387s->hello_retry_request = SSL_HRR_PENDING;1388return 1;1389}1390} else {1391/* No suitable key_share */1392if (s->hello_retry_request == SSL_HRR_NONE && sent1393&& (!s->hit1394|| (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) != 0)) {13951396/* Did we detect group overlap in tls_parse_ctos_key_share ? */1397if (s->s3.group_id_candidate != 0) {1398/* A shared group exists so send a HelloRetryRequest */1399s->s3.group_id = s->s3.group_id_candidate;1400s->hello_retry_request = SSL_HRR_PENDING;1401return 1;1402}1403}1404if (!s->hit1405|| (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {1406/* Nothing left we can do - just fail */1407SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE : SSL_AD_MISSING_EXTENSION,1408SSL_R_NO_SUITABLE_KEY_SHARE);1409return 0;1410}14111412if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 01413&& !s->ext.cookieok) {1414if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {1415/*1416* If we are stateless then we wouldn't know about any1417* previously sent HRR - so how can this be anything other1418* than 0?1419*/1420SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1421return 0;1422}1423s->hello_retry_request = SSL_HRR_PENDING;1424return 1;1425}1426}14271428/*1429* We have a key_share so don't send any more HelloRetryRequest1430* messages1431*/1432if (s->hello_retry_request == SSL_HRR_PENDING)1433s->hello_retry_request = SSL_HRR_COMPLETE;1434} else {1435/*1436* For a client side resumption with no key_share we need to generate1437* the handshake secret (otherwise this is done during key_share1438* processing).1439*/1440if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {1441SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1442return 0;1443}1444}1445#endif /* !defined(OPENSSL_NO_TLS1_3) */1446return 1;1447}14481449static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context)1450{1451s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;1452return 1;1453}14541455int tls_psk_do_binder(SSL_CONNECTION *s, const EVP_MD *md,1456const unsigned char *msgstart,1457size_t binderoffset, const unsigned char *binderin,1458unsigned char *binderout, SSL_SESSION *sess, int sign,1459int external)1460{1461EVP_PKEY *mackey = NULL;1462EVP_MD_CTX *mctx = NULL;1463unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];1464unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];1465unsigned char *early_secret;1466/* ASCII: "res binder", in hex for EBCDIC compatibility */1467static const unsigned char resumption_label[] = "\x72\x65\x73\x20\x62\x69\x6E\x64\x65\x72";1468/* ASCII: "ext binder", in hex for EBCDIC compatibility */1469static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";1470const unsigned char *label;1471size_t bindersize, labelsize, hashsize;1472int hashsizei = EVP_MD_get_size(md);1473int ret = -1;1474int usepskfored = 0;1475SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);14761477/* Ensure cast to size_t is safe */1478if (!ossl_assert(hashsizei > 0)) {1479SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1480goto err;1481}1482hashsize = (size_t)hashsizei;14831484if (external1485&& s->early_data_state == SSL_EARLY_DATA_CONNECTING1486&& s->session->ext.max_early_data == 01487&& sess->ext.max_early_data > 0)1488usepskfored = 1;14891490if (external) {1491label = external_label;1492labelsize = sizeof(external_label) - 1;1493} else {1494label = resumption_label;1495labelsize = sizeof(resumption_label) - 1;1496}14971498/*1499* Generate the early_secret. On the server side we've selected a PSK to1500* resume with (internal or external) so we always do this. On the client1501* side we do this for a non-external (i.e. resumption) PSK or external PSK1502* that will be used for early_data so that it is in place for sending early1503* data. For client side external PSK not being used for early_data we1504* generate it but store it away for later use.1505*/1506if (s->server || !external || usepskfored)1507early_secret = (unsigned char *)s->early_secret;1508else1509early_secret = (unsigned char *)sess->early_secret;15101511if (!tls13_generate_secret(s, md, NULL, sess->master_key,1512sess->master_key_length, early_secret)) {1513/* SSLfatal() already called */1514goto err;1515}15161517/*1518* Create the handshake hash for the binder key...the messages so far are1519* empty!1520*/1521mctx = EVP_MD_CTX_new();1522if (mctx == NULL1523|| EVP_DigestInit_ex(mctx, md, NULL) <= 01524|| EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {1525SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1526goto err;1527}15281529/* Generate the binder key */1530if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,1531hashsize, binderkey, hashsize, 1)) {1532/* SSLfatal() already called */1533goto err;1534}15351536/* Generate the finished key */1537if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {1538/* SSLfatal() already called */1539goto err;1540}15411542if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {1543SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1544goto err;1545}15461547/*1548* Get a hash of the ClientHello up to the start of the binders. If we are1549* following a HelloRetryRequest then this includes the hash of the first1550* ClientHello and the HelloRetryRequest itself.1551*/1552if (s->hello_retry_request == SSL_HRR_PENDING) {1553size_t hdatalen;1554long hdatalen_l;1555void *hdata;15561557hdatalen = hdatalen_l = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);1558if (hdatalen_l <= 0) {1559SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);1560goto err;1561}15621563/*1564* For servers the handshake buffer data will include the second1565* ClientHello - which we don't want - so we need to take that bit off.1566*/1567if (s->server) {1568PACKET hashprefix, msg;15691570/* Find how many bytes are left after the first two messages */1571if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)1572|| !PACKET_forward(&hashprefix, 1)1573|| !PACKET_get_length_prefixed_3(&hashprefix, &msg)1574|| !PACKET_forward(&hashprefix, 1)1575|| !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {1576SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1577goto err;1578}1579hdatalen -= PACKET_remaining(&hashprefix);1580}15811582if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {1583SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1584goto err;1585}1586}15871588if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 01589|| EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {1590SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1591goto err;1592}15931594mackey = EVP_PKEY_new_raw_private_key_ex(sctx->libctx, "HMAC",1595sctx->propq, finishedkey,1596hashsize);1597if (mackey == NULL) {1598SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1599goto err;1600}16011602if (!sign)1603binderout = tmpbinder;16041605bindersize = hashsize;1606if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), sctx->libctx,1607sctx->propq, mackey, NULL)1608<= 01609|| EVP_DigestSignUpdate(mctx, hash, hashsize) <= 01610|| EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 01611|| bindersize != hashsize) {1612SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1613goto err;1614}16151616if (sign) {1617ret = 1;1618} else {1619/* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */1620ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);1621if (!ret)1622SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BINDER_DOES_NOT_VERIFY);1623}16241625err:1626OPENSSL_cleanse(binderkey, sizeof(binderkey));1627OPENSSL_cleanse(finishedkey, sizeof(finishedkey));1628EVP_PKEY_free(mackey);1629EVP_MD_CTX_free(mctx);16301631return ret;1632}16331634static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent)1635{1636if (!sent)1637return 1;16381639if (!s->server) {1640if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS1641&& sent1642&& !s->ext.early_data_ok) {1643/*1644* If we get here then the server accepted our early_data but we1645* later realised that it shouldn't have done (e.g. inconsistent1646* ALPN)1647*/1648SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);1649return 0;1650}16511652return 1;1653}16541655if (s->max_early_data == 01656|| !s->hit1657|| s->early_data_state != SSL_EARLY_DATA_ACCEPTING1658|| !s->ext.early_data_ok1659|| s->hello_retry_request != SSL_HRR_NONE1660|| (s->allow_early_data_cb != NULL1661&& !s->allow_early_data_cb(SSL_CONNECTION_GET_USER_SSL(s),1662s->allow_early_data_cb_data))) {1663s->ext.early_data = SSL_EARLY_DATA_REJECTED;1664} else {1665s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;16661667if (!tls13_change_cipher_state(s,1668SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {1669/* SSLfatal() already called */1670return 0;1671}1672}16731674return 1;1675}16761677static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,1678int sent)1679{1680if (s->session == NULL)1681return 1;16821683/* MaxFragmentLength defaults to disabled */1684if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)1685s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;16861687if (USE_MAX_FRAGMENT_LENGTH_EXT(s->session)) {1688s->rlayer.rrlmethod->set_max_frag_len(s->rlayer.rrl,1689GET_MAX_FRAGMENT_LENGTH(s->session));1690s->rlayer.wrlmethod->set_max_frag_len(s->rlayer.wrl,1691ssl_get_max_send_fragment(s));1692}16931694return 1;1695}16961697static int init_post_handshake_auth(SSL_CONNECTION *s,1698ossl_unused unsigned int context)1699{1700s->post_handshake_auth = SSL_PHA_NONE;17011702return 1;1703}17041705/*1706* If clients offer "pre_shared_key" without a "psk_key_exchange_modes"1707* extension, servers MUST abort the handshake.1708*/1709static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent)1710{1711if (s->server && sent && s->clienthello != NULL1712&& !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {1713SSLfatal(s, TLS13_AD_MISSING_EXTENSION,1714SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);1715return 0;1716}17171718return 1;1719}17201721static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context)1722{1723memset(sc->ext.compress_certificate_from_peer, 0,1724sizeof(sc->ext.compress_certificate_from_peer));1725return 1;1726}17271728/* The order these are put into the packet imply a preference order: [brotli, zlib, zstd] */1729static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,1730unsigned int context,1731X509 *x, size_t chainidx)1732{1733#ifndef OPENSSL_NO_COMP_ALG1734int i;17351736if (!ossl_comp_has_alg(0))1737return EXT_RETURN_NOT_SENT;17381739/* Server: Don't attempt to compress a non-X509 (i.e. an RPK) */1740if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509) {1741sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;1742return EXT_RETURN_NOT_SENT;1743}17441745/* Client: If we sent a client cert-type extension, don't indicate compression */1746if (!sc->server && sc->ext.client_cert_type_ctos) {1747sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;1748return EXT_RETURN_NOT_SENT;1749}17501751/* Do not indicate we support receiving compressed certificates */1752if ((sc->options & SSL_OP_NO_RX_CERTIFICATE_COMPRESSION) != 0)1753return EXT_RETURN_NOT_SENT;17541755if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)1756return EXT_RETURN_NOT_SENT;17571758if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_compress_certificate)1759|| !WPACKET_start_sub_packet_u16(pkt)1760|| !WPACKET_start_sub_packet_u8(pkt))1761goto err;17621763for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {1764if (!WPACKET_put_bytes_u16(pkt, sc->cert_comp_prefs[i]))1765goto err;1766}1767if (!WPACKET_close(pkt) || !WPACKET_close(pkt))1768goto err;17691770sc->ext.compress_certificate_sent = 1;1771return EXT_RETURN_SENT;1772err:1773SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1774return EXT_RETURN_FAIL;1775#else1776return EXT_RETURN_NOT_SENT;1777#endif1778}17791780#ifndef OPENSSL_NO_COMP_ALG1781static int tls_comp_in_pref(SSL_CONNECTION *sc, int alg)1782{1783int i;17841785/* ossl_comp_has_alg() considers 0 as "any" */1786if (alg == 0)1787return 0;1788/* Make sure algorithm is enabled */1789if (!ossl_comp_has_alg(alg))1790return 0;1791/* If no preferences are set, it's ok */1792if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)1793return 1;1794/* Find the algorithm */1795for (i = 0; i < TLSEXT_comp_cert_limit; i++)1796if (sc->cert_comp_prefs[i] == alg)1797return 1;1798return 0;1799}1800#endif18011802int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt, unsigned int context,1803X509 *x, size_t chainidx)1804{1805#ifndef OPENSSL_NO_COMP_ALG1806PACKET supported_comp_algs;1807unsigned int comp;1808int already_set[TLSEXT_comp_cert_limit];1809int j = 0;18101811/* If no algorithms are available, ignore the extension */1812if (!ossl_comp_has_alg(0))1813return 1;18141815/* Don't attempt to compress a non-X509 (i.e. an RPK) */1816if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509)1817return 1;1818if (!sc->server && sc->ext.client_cert_type != TLSEXT_cert_type_x509)1819return 1;18201821/* Ignore the extension and don't send compressed certificates */1822if ((sc->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)1823return 1;18241825if (!PACKET_as_length_prefixed_1(pkt, &supported_comp_algs)1826|| PACKET_remaining(&supported_comp_algs) == 0) {1827SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);1828return 0;1829}18301831memset(already_set, 0, sizeof(already_set));1832/*1833* The preference array has real values, so take a look at each1834* value coming in, and make sure it's in our preference list1835* The array is 0 (i.e. "none") terminated1836* The preference list only contains supported algorithms1837*/1838while (PACKET_get_net_2(&supported_comp_algs, &comp)) {1839if (tls_comp_in_pref(sc, comp) && !already_set[comp]) {1840sc->ext.compress_certificate_from_peer[j++] = comp;1841already_set[comp] = 1;1842}1843}1844if (PACKET_remaining(&supported_comp_algs) != 0) {1845SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);1846return 0;1847}1848#endif1849return 1;1850}18511852static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context)1853{1854/* Only reset when parsing client hello */1855if (sc->server) {1856sc->ext.server_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;1857sc->ext.server_cert_type = TLSEXT_cert_type_x509;1858}1859return 1;1860}18611862static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context)1863{1864/* Only reset when parsing client hello */1865if (sc->server) {1866sc->ext.client_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;1867sc->ext.client_cert_type = TLSEXT_cert_type_x509;1868}1869return 1;1870}187118721873