Path: blob/main/crypto/openssl/ssl/statem/statem_srvr.c
48266 views
/*1* Copyright 1995-2025 The OpenSSL Project Authors. All Rights Reserved.2* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved3* Copyright 2005 Nokia. All rights reserved.4*5* Licensed under the Apache License 2.0 (the "License"). You may not use6* this file except in compliance with the License. You can obtain a copy7* in the file LICENSE in the source distribution or at8* https://www.openssl.org/source/license.html9*/1011#include "internal/e_os.h"1213#include <stdio.h>14#include "../ssl_local.h"15#include "statem_local.h"16#include "internal/constant_time.h"17#include "internal/cryptlib.h"18#include "internal/ssl_unwrap.h"19#include <openssl/buffer.h>20#include <openssl/rand.h>21#include <openssl/objects.h>22#include <openssl/evp.h>23#include <openssl/x509.h>24#include <openssl/dh.h>25#include <openssl/rsa.h>26#include <openssl/bn.h>27#include <openssl/md5.h>28#include <openssl/trace.h>29#include <openssl/core_names.h>30#include <openssl/asn1t.h>31#include <openssl/comp.h>32#include "internal/comp.h"3334#define TICKET_NONCE_SIZE 83536typedef struct {37ASN1_TYPE *kxBlob;38ASN1_TYPE *opaqueBlob;39} GOST_KX_MESSAGE;4041DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)4243ASN1_SEQUENCE(GOST_KX_MESSAGE) = {44ASN1_SIMPLE(GOST_KX_MESSAGE, kxBlob, ASN1_ANY),45ASN1_OPT(GOST_KX_MESSAGE, opaqueBlob, ASN1_ANY),46} ASN1_SEQUENCE_END(GOST_KX_MESSAGE)4748IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)4950static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,51WPACKET *pkt);5253static ossl_inline int received_client_cert(const SSL_CONNECTION *sc)54{55return sc->session->peer_rpk != NULL || sc->session->peer != NULL;56}5758/*59* ossl_statem_server13_read_transition() encapsulates the logic for the allowed60* handshake state transitions when a TLSv1.3 server is reading messages from61* the client. The message type that the client has sent is provided in |mt|.62* The current state is in |s->statem.hand_state|.63*64* Return values are 1 for success (transition allowed) and 0 on error65* (transition not allowed)66*/67static int ossl_statem_server13_read_transition(SSL_CONNECTION *s, int mt)68{69OSSL_STATEM *st = &s->statem;7071/*72* Note: There is no case for TLS_ST_BEFORE because at that stage we have73* not negotiated TLSv1.3 yet, so that case is handled by74* ossl_statem_server_read_transition()75*/76switch (st->hand_state) {77default:78break;7980case TLS_ST_EARLY_DATA:81if (s->hello_retry_request == SSL_HRR_PENDING) {82if (mt == SSL3_MT_CLIENT_HELLO) {83st->hand_state = TLS_ST_SR_CLNT_HELLO;84return 1;85}86break;87} else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED88&& !SSL_NO_EOED(s)) {89if (mt == SSL3_MT_END_OF_EARLY_DATA) {90st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;91return 1;92}93break;94}95/* Fall through */9697case TLS_ST_SR_END_OF_EARLY_DATA:98case TLS_ST_SW_FINISHED:99if (s->s3.tmp.cert_request) {100if (mt == SSL3_MT_CERTIFICATE) {101st->hand_state = TLS_ST_SR_CERT;102return 1;103}104#ifndef OPENSSL_NO_COMP_ALG105if (mt == SSL3_MT_COMPRESSED_CERTIFICATE106&& s->ext.compress_certificate_sent) {107st->hand_state = TLS_ST_SR_COMP_CERT;108return 1;109}110#endif111} else {112if (mt == SSL3_MT_FINISHED) {113st->hand_state = TLS_ST_SR_FINISHED;114return 1;115}116}117break;118119case TLS_ST_SR_COMP_CERT:120case TLS_ST_SR_CERT:121if (!received_client_cert(s)) {122if (mt == SSL3_MT_FINISHED) {123st->hand_state = TLS_ST_SR_FINISHED;124return 1;125}126} else {127if (mt == SSL3_MT_CERTIFICATE_VERIFY) {128st->hand_state = TLS_ST_SR_CERT_VRFY;129return 1;130}131}132break;133134case TLS_ST_SR_CERT_VRFY:135if (mt == SSL3_MT_FINISHED) {136st->hand_state = TLS_ST_SR_FINISHED;137return 1;138}139break;140141case TLS_ST_OK:142/*143* Its never ok to start processing handshake messages in the middle of144* early data (i.e. before we've received the end of early data alert)145*/146if (s->early_data_state == SSL_EARLY_DATA_READING)147break;148149if (s->post_handshake_auth == SSL_PHA_REQUESTED) {150if (mt == SSL3_MT_CERTIFICATE) {151st->hand_state = TLS_ST_SR_CERT;152return 1;153}154#ifndef OPENSSL_NO_COMP_ALG155if (mt == SSL3_MT_COMPRESSED_CERTIFICATE156&& s->ext.compress_certificate_sent) {157st->hand_state = TLS_ST_SR_COMP_CERT;158return 1;159}160#endif161}162163if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {164st->hand_state = TLS_ST_SR_KEY_UPDATE;165return 1;166}167break;168}169170/* No valid transition found */171return 0;172}173174/*175* ossl_statem_server_read_transition() encapsulates the logic for the allowed176* handshake state transitions when the server is reading messages from the177* client. The message type that the client has sent is provided in |mt|. The178* current state is in |s->statem.hand_state|.179*180* Return values are 1 for success (transition allowed) and 0 on error181* (transition not allowed)182*/183int ossl_statem_server_read_transition(SSL_CONNECTION *s, int mt)184{185OSSL_STATEM *st = &s->statem;186187if (SSL_CONNECTION_IS_TLS13(s)) {188if (!ossl_statem_server13_read_transition(s, mt))189goto err;190return 1;191}192193switch (st->hand_state) {194default:195break;196197case TLS_ST_BEFORE:198case TLS_ST_OK:199case DTLS_ST_SW_HELLO_VERIFY_REQUEST:200if (mt == SSL3_MT_CLIENT_HELLO) {201st->hand_state = TLS_ST_SR_CLNT_HELLO;202return 1;203}204break;205206case TLS_ST_SW_SRVR_DONE:207/*208* If we get a CKE message after a ServerDone then either209* 1) We didn't request a Certificate210* OR211* 2) If we did request one then212* a) We allow no Certificate to be returned213* AND214* b) We are running SSL3 (in TLS1.0+ the client must return a 0215* list if we requested a certificate)216*/217if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {218if (s->s3.tmp.cert_request) {219if (s->version == SSL3_VERSION) {220if ((s->verify_mode & SSL_VERIFY_PEER)221&& (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {222/*223* This isn't an unexpected message as such - we're just224* not going to accept it because we require a client225* cert.226*/227SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,228SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);229return 0;230}231st->hand_state = TLS_ST_SR_KEY_EXCH;232return 1;233}234} else {235st->hand_state = TLS_ST_SR_KEY_EXCH;236return 1;237}238} else if (s->s3.tmp.cert_request) {239if (mt == SSL3_MT_CERTIFICATE) {240st->hand_state = TLS_ST_SR_CERT;241return 1;242}243}244break;245246case TLS_ST_SR_CERT:247if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {248st->hand_state = TLS_ST_SR_KEY_EXCH;249return 1;250}251break;252253case TLS_ST_SR_KEY_EXCH:254/*255* We should only process a CertificateVerify message if we have256* received a Certificate from the client. If so then |s->session->peer|257* will be non NULL. In some instances a CertificateVerify message is258* not required even if the peer has sent a Certificate (e.g. such as in259* the case of static DH). In that case |st->no_cert_verify| should be260* set.261*/262if (!received_client_cert(s) || st->no_cert_verify) {263if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {264/*265* For the ECDH ciphersuites when the client sends its ECDH266* pub key in a certificate, the CertificateVerify message is267* not sent. Also for GOST ciphersuites when the client uses268* its key from the certificate for key exchange.269*/270st->hand_state = TLS_ST_SR_CHANGE;271return 1;272}273} else {274if (mt == SSL3_MT_CERTIFICATE_VERIFY) {275st->hand_state = TLS_ST_SR_CERT_VRFY;276return 1;277}278}279break;280281case TLS_ST_SR_CERT_VRFY:282if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {283st->hand_state = TLS_ST_SR_CHANGE;284return 1;285}286break;287288case TLS_ST_SR_CHANGE:289#ifndef OPENSSL_NO_NEXTPROTONEG290if (s->s3.npn_seen) {291if (mt == SSL3_MT_NEXT_PROTO) {292st->hand_state = TLS_ST_SR_NEXT_PROTO;293return 1;294}295} else {296#endif297if (mt == SSL3_MT_FINISHED) {298st->hand_state = TLS_ST_SR_FINISHED;299return 1;300}301#ifndef OPENSSL_NO_NEXTPROTONEG302}303#endif304break;305306#ifndef OPENSSL_NO_NEXTPROTONEG307case TLS_ST_SR_NEXT_PROTO:308if (mt == SSL3_MT_FINISHED) {309st->hand_state = TLS_ST_SR_FINISHED;310return 1;311}312break;313#endif314315case TLS_ST_SW_FINISHED:316if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {317st->hand_state = TLS_ST_SR_CHANGE;318return 1;319}320break;321}322323err:324/* No valid transition found */325if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {326BIO *rbio;327328/*329* CCS messages don't have a message sequence number so this is probably330* because of an out-of-order CCS. We'll just drop it.331*/332s->init_num = 0;333s->rwstate = SSL_READING;334rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));335BIO_clear_retry_flags(rbio);336BIO_set_retry_read(rbio);337return 0;338}339SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);340return 0;341}342343/*344* Should we send a ServerKeyExchange message?345*346* Valid return values are:347* 1: Yes348* 0: No349*/350static int send_server_key_exchange(SSL_CONNECTION *s)351{352unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;353354/*355* only send a ServerKeyExchange if DH or fortezza but we have a356* sign only certificate PSK: may send PSK identity hints For357* ECC ciphersuites, we send a serverKeyExchange message only if358* the cipher suite is either ECDH-anon or ECDHE. In other cases,359* the server certificate contains the server's public key for360* key exchange.361*/362if (alg_k & (SSL_kDHE | SSL_kECDHE)363/*364* PSK: send ServerKeyExchange if PSK identity hint if365* provided366*/367#ifndef OPENSSL_NO_PSK368/* Only send SKE if we have identity hint for plain PSK */369|| ((alg_k & (SSL_kPSK | SSL_kRSAPSK))370&& s->cert->psk_identity_hint)371/* For other PSK always send SKE */372|| (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))373#endif374#ifndef OPENSSL_NO_SRP375/* SRP: send ServerKeyExchange */376|| (alg_k & SSL_kSRP)377#endif378) {379return 1;380}381382return 0;383}384385/*386* Used to determine if we should send a CompressedCertificate message387*388* Returns the algorithm to use, TLSEXT_comp_cert_none means no compression389*/390static int get_compressed_certificate_alg(SSL_CONNECTION *sc)391{392#ifndef OPENSSL_NO_COMP_ALG393int *alg = sc->ext.compress_certificate_from_peer;394395if (sc->s3.tmp.cert == NULL)396return TLSEXT_comp_cert_none;397398for (; *alg != TLSEXT_comp_cert_none; alg++) {399if (sc->s3.tmp.cert->comp_cert[*alg] != NULL)400return *alg;401}402#endif403return TLSEXT_comp_cert_none;404}405406/*407* Should we send a CertificateRequest message?408*409* Valid return values are:410* 1: Yes411* 0: No412*/413int send_certificate_request(SSL_CONNECTION *s)414{415if (416/* don't request cert unless asked for it: */417s->verify_mode & SSL_VERIFY_PEER418/*419* don't request if post-handshake-only unless doing420* post-handshake in TLSv1.3:421*/422&& (!SSL_CONNECTION_IS_TLS13(s)423|| !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)424|| s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)425/*426* if SSL_VERIFY_CLIENT_ONCE is set, don't request cert427* a second time:428*/429&& (s->certreqs_sent < 1 ||430!(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))431/*432* never request cert in anonymous ciphersuites (see433* section "Certificate request" in SSL 3 drafts and in434* RFC 2246):435*/436&& (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)437/*438* ... except when the application insists on439* verification (against the specs, but statem_clnt.c accepts440* this for SSL 3)441*/442|| (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))443/* don't request certificate for SRP auth */444&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)445/*446* With normal PSK Certificates and Certificate Requests447* are omitted448*/449&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {450return 1;451}452453return 0;454}455456static int do_compressed_cert(SSL_CONNECTION *sc)457{458/* If we negotiated RPK, we won't attempt to compress it */459return sc->ext.server_cert_type == TLSEXT_cert_type_x509460&& get_compressed_certificate_alg(sc) != TLSEXT_comp_cert_none;461}462463/*464* ossl_statem_server13_write_transition() works out what handshake state to465* move to next when a TLSv1.3 server is writing messages to be sent to the466* client.467*/468static WRITE_TRAN ossl_statem_server13_write_transition(SSL_CONNECTION *s)469{470OSSL_STATEM *st = &s->statem;471472/*473* No case for TLS_ST_BEFORE, because at that stage we have not negotiated474* TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()475*/476477switch (st->hand_state) {478default:479/* Shouldn't happen */480SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);481return WRITE_TRAN_ERROR;482483case TLS_ST_OK:484if (s->key_update != SSL_KEY_UPDATE_NONE) {485st->hand_state = TLS_ST_SW_KEY_UPDATE;486return WRITE_TRAN_CONTINUE;487}488if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {489st->hand_state = TLS_ST_SW_CERT_REQ;490return WRITE_TRAN_CONTINUE;491}492if (s->ext.extra_tickets_expected > 0) {493st->hand_state = TLS_ST_SW_SESSION_TICKET;494return WRITE_TRAN_CONTINUE;495}496/* Try to read from the client instead */497return WRITE_TRAN_FINISHED;498499case TLS_ST_SR_CLNT_HELLO:500st->hand_state = TLS_ST_SW_SRVR_HELLO;501return WRITE_TRAN_CONTINUE;502503case TLS_ST_SW_SRVR_HELLO:504if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0505&& s->hello_retry_request != SSL_HRR_COMPLETE)506st->hand_state = TLS_ST_SW_CHANGE;507else if (s->hello_retry_request == SSL_HRR_PENDING)508st->hand_state = TLS_ST_EARLY_DATA;509else510st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;511return WRITE_TRAN_CONTINUE;512513case TLS_ST_SW_CHANGE:514if (s->hello_retry_request == SSL_HRR_PENDING)515st->hand_state = TLS_ST_EARLY_DATA;516else517st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;518return WRITE_TRAN_CONTINUE;519520case TLS_ST_SW_ENCRYPTED_EXTENSIONS:521if (s->hit)522st->hand_state = TLS_ST_SW_FINISHED;523else if (send_certificate_request(s))524st->hand_state = TLS_ST_SW_CERT_REQ;525else if (do_compressed_cert(s))526st->hand_state = TLS_ST_SW_COMP_CERT;527else528st->hand_state = TLS_ST_SW_CERT;529530return WRITE_TRAN_CONTINUE;531532case TLS_ST_SW_CERT_REQ:533if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {534s->post_handshake_auth = SSL_PHA_REQUESTED;535st->hand_state = TLS_ST_OK;536} else if (do_compressed_cert(s)) {537st->hand_state = TLS_ST_SW_COMP_CERT;538} else {539st->hand_state = TLS_ST_SW_CERT;540}541return WRITE_TRAN_CONTINUE;542543case TLS_ST_SW_COMP_CERT:544case TLS_ST_SW_CERT:545st->hand_state = TLS_ST_SW_CERT_VRFY;546return WRITE_TRAN_CONTINUE;547548case TLS_ST_SW_CERT_VRFY:549st->hand_state = TLS_ST_SW_FINISHED;550return WRITE_TRAN_CONTINUE;551552case TLS_ST_SW_FINISHED:553st->hand_state = TLS_ST_EARLY_DATA;554s->ts_msg_write = ossl_time_now();555return WRITE_TRAN_CONTINUE;556557case TLS_ST_EARLY_DATA:558return WRITE_TRAN_FINISHED;559560case TLS_ST_SR_FINISHED:561s->ts_msg_read = ossl_time_now();562/*563* Technically we have finished the handshake at this point, but we're564* going to remain "in_init" for now and write out any session tickets565* immediately.566*/567if (s->post_handshake_auth == SSL_PHA_REQUESTED) {568s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;569} else if (!s->ext.ticket_expected) {570/*571* If we're not going to renew the ticket then we just finish the572* handshake at this point.573*/574st->hand_state = TLS_ST_OK;575return WRITE_TRAN_CONTINUE;576}577if (s->num_tickets > s->sent_tickets)578st->hand_state = TLS_ST_SW_SESSION_TICKET;579else580st->hand_state = TLS_ST_OK;581return WRITE_TRAN_CONTINUE;582583case TLS_ST_SR_KEY_UPDATE:584case TLS_ST_SW_KEY_UPDATE:585st->hand_state = TLS_ST_OK;586return WRITE_TRAN_CONTINUE;587588case TLS_ST_SW_SESSION_TICKET:589/* In a resumption we only ever send a maximum of one new ticket.590* Following an initial handshake we send the number of tickets we have591* been configured for.592*/593if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {594return WRITE_TRAN_CONTINUE;595} else if (s->hit || s->num_tickets <= s->sent_tickets) {596/* We've written enough tickets out. */597st->hand_state = TLS_ST_OK;598}599return WRITE_TRAN_CONTINUE;600}601}602603/*604* ossl_statem_server_write_transition() works out what handshake state to move605* to next when the server is writing messages to be sent to the client.606*/607WRITE_TRAN ossl_statem_server_write_transition(SSL_CONNECTION *s)608{609OSSL_STATEM *st = &s->statem;610611/*612* Note that before the ClientHello we don't know what version we are going613* to negotiate yet, so we don't take this branch until later614*/615616if (SSL_CONNECTION_IS_TLS13(s))617return ossl_statem_server13_write_transition(s);618619switch (st->hand_state) {620default:621/* Shouldn't happen */622SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);623return WRITE_TRAN_ERROR;624625case TLS_ST_OK:626if (st->request_state == TLS_ST_SW_HELLO_REQ) {627/* We must be trying to renegotiate */628st->hand_state = TLS_ST_SW_HELLO_REQ;629st->request_state = TLS_ST_BEFORE;630return WRITE_TRAN_CONTINUE;631}632/* Must be an incoming ClientHello */633if (!tls_setup_handshake(s)) {634/* SSLfatal() already called */635return WRITE_TRAN_ERROR;636}637/* Fall through */638639case TLS_ST_BEFORE:640/* Just go straight to trying to read from the client */641return WRITE_TRAN_FINISHED;642643case TLS_ST_SW_HELLO_REQ:644st->hand_state = TLS_ST_OK;645return WRITE_TRAN_CONTINUE;646647case TLS_ST_SR_CLNT_HELLO:648if (SSL_CONNECTION_IS_DTLS(s) && !s->d1->cookie_verified649&& (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE)) {650st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;651} else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {652/* We must have rejected the renegotiation */653st->hand_state = TLS_ST_OK;654return WRITE_TRAN_CONTINUE;655} else {656st->hand_state = TLS_ST_SW_SRVR_HELLO;657}658return WRITE_TRAN_CONTINUE;659660case DTLS_ST_SW_HELLO_VERIFY_REQUEST:661return WRITE_TRAN_FINISHED;662663case TLS_ST_SW_SRVR_HELLO:664if (s->hit) {665if (s->ext.ticket_expected)666st->hand_state = TLS_ST_SW_SESSION_TICKET;667else668st->hand_state = TLS_ST_SW_CHANGE;669} else {670/* Check if it is anon DH or anon ECDH, */671/* normal PSK or SRP */672if (!(s->s3.tmp.new_cipher->algorithm_auth &673(SSL_aNULL | SSL_aSRP | SSL_aPSK))) {674st->hand_state = TLS_ST_SW_CERT;675} else if (send_server_key_exchange(s)) {676st->hand_state = TLS_ST_SW_KEY_EXCH;677} else if (send_certificate_request(s)) {678st->hand_state = TLS_ST_SW_CERT_REQ;679} else {680st->hand_state = TLS_ST_SW_SRVR_DONE;681}682}683return WRITE_TRAN_CONTINUE;684685case TLS_ST_SW_CERT:686if (s->ext.status_expected) {687st->hand_state = TLS_ST_SW_CERT_STATUS;688return WRITE_TRAN_CONTINUE;689}690/* Fall through */691692case TLS_ST_SW_CERT_STATUS:693if (send_server_key_exchange(s)) {694st->hand_state = TLS_ST_SW_KEY_EXCH;695return WRITE_TRAN_CONTINUE;696}697/* Fall through */698699case TLS_ST_SW_KEY_EXCH:700if (send_certificate_request(s)) {701st->hand_state = TLS_ST_SW_CERT_REQ;702return WRITE_TRAN_CONTINUE;703}704/* Fall through */705706case TLS_ST_SW_CERT_REQ:707st->hand_state = TLS_ST_SW_SRVR_DONE;708return WRITE_TRAN_CONTINUE;709710case TLS_ST_SW_SRVR_DONE:711s->ts_msg_write = ossl_time_now();712return WRITE_TRAN_FINISHED;713714case TLS_ST_SR_FINISHED:715s->ts_msg_read = ossl_time_now();716if (s->hit) {717st->hand_state = TLS_ST_OK;718return WRITE_TRAN_CONTINUE;719} else if (s->ext.ticket_expected) {720st->hand_state = TLS_ST_SW_SESSION_TICKET;721} else {722st->hand_state = TLS_ST_SW_CHANGE;723}724return WRITE_TRAN_CONTINUE;725726case TLS_ST_SW_SESSION_TICKET:727st->hand_state = TLS_ST_SW_CHANGE;728return WRITE_TRAN_CONTINUE;729730case TLS_ST_SW_CHANGE:731st->hand_state = TLS_ST_SW_FINISHED;732return WRITE_TRAN_CONTINUE;733734case TLS_ST_SW_FINISHED:735if (s->hit) {736return WRITE_TRAN_FINISHED;737}738st->hand_state = TLS_ST_OK;739return WRITE_TRAN_CONTINUE;740}741}742743/*744* Perform any pre work that needs to be done prior to sending a message from745* the server to the client.746*/747WORK_STATE ossl_statem_server_pre_work(SSL_CONNECTION *s, WORK_STATE wst)748{749OSSL_STATEM *st = &s->statem;750SSL *ssl = SSL_CONNECTION_GET_SSL(s);751752switch (st->hand_state) {753default:754/* No pre work to be done */755break;756757case TLS_ST_SW_HELLO_REQ:758s->shutdown = 0;759if (SSL_CONNECTION_IS_DTLS(s))760dtls1_clear_sent_buffer(s);761break;762763case DTLS_ST_SW_HELLO_VERIFY_REQUEST:764s->shutdown = 0;765if (SSL_CONNECTION_IS_DTLS(s)) {766dtls1_clear_sent_buffer(s);767/* We don't buffer this message so don't use the timer */768st->use_timer = 0;769}770break;771772case TLS_ST_SW_SRVR_HELLO:773if (SSL_CONNECTION_IS_DTLS(s)) {774/*775* Messages we write from now on should be buffered and776* retransmitted if necessary, so we need to use the timer now777*/778st->use_timer = 1;779}780break;781782case TLS_ST_SW_SRVR_DONE:783#ifndef OPENSSL_NO_SCTP784if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {785/* Calls SSLfatal() as required */786return dtls_wait_for_dry(s);787}788#endif789return WORK_FINISHED_CONTINUE;790791case TLS_ST_SW_SESSION_TICKET:792if (SSL_CONNECTION_IS_TLS13(s) && s->sent_tickets == 0793&& s->ext.extra_tickets_expected == 0) {794/*795* Actually this is the end of the handshake, but we're going796* straight into writing the session ticket out. So we finish off797* the handshake, but keep the various buffers active.798*799* Calls SSLfatal as required.800*/801return tls_finish_handshake(s, wst, 0, 0);802}803if (SSL_CONNECTION_IS_DTLS(s)) {804/*805* We're into the last flight. We don't retransmit the last flight806* unless we need to, so we don't use the timer807*/808st->use_timer = 0;809}810break;811812case TLS_ST_SW_CHANGE:813if (SSL_CONNECTION_IS_TLS13(s))814break;815/* Writes to s->session are only safe for initial handshakes */816if (s->session->cipher == NULL) {817s->session->cipher = s->s3.tmp.new_cipher;818} else if (s->session->cipher != s->s3.tmp.new_cipher) {819SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);820return WORK_ERROR;821}822if (!ssl->method->ssl3_enc->setup_key_block(s)) {823/* SSLfatal() already called */824return WORK_ERROR;825}826if (SSL_CONNECTION_IS_DTLS(s)) {827/*828* We're into the last flight. We don't retransmit the last flight829* unless we need to, so we don't use the timer. This might have830* already been set to 0 if we sent a NewSessionTicket message,831* but we'll set it again here in case we didn't.832*/833st->use_timer = 0;834}835return WORK_FINISHED_CONTINUE;836837case TLS_ST_EARLY_DATA:838if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING839&& (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)840return WORK_FINISHED_CONTINUE;841842/*843* In QUIC with 0-RTT we just carry on when otherwise we would stop844* to allow the server to read early data845*/846if (SSL_NO_EOED(s) && s->ext.early_data == SSL_EARLY_DATA_ACCEPTED847&& s->early_data_state != SSL_EARLY_DATA_FINISHED_READING) {848s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;849if (!ssl->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE850| SSL3_CHANGE_CIPHER_SERVER_READ)) {851SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);852return WORK_ERROR;853}854return WORK_FINISHED_SWAP;855}856/* Fall through */857858case TLS_ST_OK:859/* Calls SSLfatal() as required */860return tls_finish_handshake(s, wst, 1, 1);861}862863return WORK_FINISHED_CONTINUE;864}865866static ossl_inline int conn_is_closed(void)867{868switch (get_last_sys_error()) {869#if defined(EPIPE)870case EPIPE:871return 1;872#endif873#if defined(ECONNRESET)874case ECONNRESET:875return 1;876#endif877#if defined(WSAECONNRESET)878case WSAECONNRESET:879return 1;880#endif881default:882return 0;883}884}885886/*887* Perform any work that needs to be done after sending a message from the888* server to the client.889*/890WORK_STATE ossl_statem_server_post_work(SSL_CONNECTION *s, WORK_STATE wst)891{892OSSL_STATEM *st = &s->statem;893SSL *ssl = SSL_CONNECTION_GET_SSL(s);894895s->init_num = 0;896897switch (st->hand_state) {898default:899/* No post work to be done */900break;901902case TLS_ST_SW_HELLO_REQ:903if (statem_flush(s) != 1)904return WORK_MORE_A;905if (!ssl3_init_finished_mac(s)) {906/* SSLfatal() already called */907return WORK_ERROR;908}909break;910911case DTLS_ST_SW_HELLO_VERIFY_REQUEST:912if (statem_flush(s) != 1)913return WORK_MORE_A;914/* HelloVerifyRequest resets Finished MAC */915if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {916/* SSLfatal() already called */917return WORK_ERROR;918}919/*920* The next message should be another ClientHello which we need to921* treat like it was the first packet922*/923s->first_packet = 1;924break;925926case TLS_ST_SW_SRVR_HELLO:927if (SSL_CONNECTION_IS_TLS13(s)928&& s->hello_retry_request == SSL_HRR_PENDING) {929if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0930&& statem_flush(s) != 1)931return WORK_MORE_A;932break;933}934#ifndef OPENSSL_NO_SCTP935if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {936unsigned char sctpauthkey[64];937char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];938size_t labellen;939940/*941* Add new shared key for SCTP-Auth, will be ignored if no942* SCTP used.943*/944memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,945sizeof(DTLS1_SCTP_AUTH_LABEL));946947/* Don't include the terminating zero. */948labellen = sizeof(labelbuffer) - 1;949if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)950labellen += 1;951952if (SSL_export_keying_material(ssl, sctpauthkey,953sizeof(sctpauthkey), labelbuffer,954labellen, NULL, 0,9550) <= 0) {956SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);957return WORK_ERROR;958}959960BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,961sizeof(sctpauthkey), sctpauthkey);962}963#endif964if (!SSL_CONNECTION_IS_TLS13(s)965|| ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0966&& s->hello_retry_request != SSL_HRR_COMPLETE))967break;968/* Fall through */969970case TLS_ST_SW_CHANGE:971if (s->hello_retry_request == SSL_HRR_PENDING) {972if (!statem_flush(s))973return WORK_MORE_A;974break;975}976977if (SSL_CONNECTION_IS_TLS13(s)) {978if (!ssl->method->ssl3_enc->setup_key_block(s)979|| !tls13_store_handshake_traffic_hash(s)980|| !ssl->method->ssl3_enc->change_cipher_state(s,981SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {982/* SSLfatal() already called */983return WORK_ERROR;984}985986if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED987&& !ssl->method->ssl3_enc->change_cipher_state(s,988SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) {989/* SSLfatal() already called */990return WORK_ERROR;991}992/*993* We don't yet know whether the next record we are going to receive994* is an unencrypted alert, an encrypted alert, or an encrypted995* handshake message. We temporarily tolerate unencrypted alerts.996*/997if (s->rlayer.rrlmethod->set_plain_alerts != NULL)998s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);999break;1000}10011002#ifndef OPENSSL_NO_SCTP1003if (SSL_CONNECTION_IS_DTLS(s) && !s->hit) {1004/*1005* Change to new shared key of SCTP-Auth, will be ignored if1006* no SCTP used.1007*/1008BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,10090, NULL);1010}1011#endif1012if (!ssl->method->ssl3_enc->change_cipher_state(s,1013SSL3_CHANGE_CIPHER_SERVER_WRITE)) {1014/* SSLfatal() already called */1015return WORK_ERROR;1016}1017break;10181019case TLS_ST_SW_SRVR_DONE:1020if (statem_flush(s) != 1)1021return WORK_MORE_A;1022break;10231024case TLS_ST_SW_FINISHED:1025if (statem_flush(s) != 1)1026return WORK_MORE_A;1027#ifndef OPENSSL_NO_SCTP1028if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {1029/*1030* Change to new shared key of SCTP-Auth, will be ignored if1031* no SCTP used.1032*/1033BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,10340, NULL);1035}1036#endif1037if (SSL_CONNECTION_IS_TLS13(s)) {1038/* TLS 1.3 gets the secret size from the handshake md */1039size_t dummy;1040if (!ssl->method->ssl3_enc->generate_master_secret(s,1041s->master_secret, s->handshake_secret, 0,1042&dummy)1043|| !tls13_store_server_finished_hash(s)1044|| !ssl->method->ssl3_enc->change_cipher_state(s,1045SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))1046/* SSLfatal() already called */1047return WORK_ERROR;1048}1049break;10501051case TLS_ST_SW_CERT_REQ:1052if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {1053if (statem_flush(s) != 1)1054return WORK_MORE_A;1055} else {1056if (!SSL_CONNECTION_IS_TLS13(s)1057|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)1058s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;1059}1060break;10611062case TLS_ST_SW_ENCRYPTED_EXTENSIONS:1063if (!s->hit && !send_certificate_request(s)) {1064if (!SSL_CONNECTION_IS_TLS13(s)1065|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)1066s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;1067}1068break;10691070case TLS_ST_SW_KEY_UPDATE:1071if (statem_flush(s) != 1)1072return WORK_MORE_A;1073if (!tls13_update_key(s, 1)) {1074/* SSLfatal() already called */1075return WORK_ERROR;1076}1077break;10781079case TLS_ST_SW_SESSION_TICKET:1080clear_sys_error();1081if (SSL_CONNECTION_IS_TLS13(s) && statem_flush(s) != 1) {1082if (SSL_get_error(ssl, 0) == SSL_ERROR_SYSCALL1083&& conn_is_closed()) {1084/*1085* We ignore connection closed errors in TLSv1.3 when sending a1086* NewSessionTicket and behave as if we were successful. This is1087* so that we are still able to read data sent to us by a client1088* that closes soon after the end of the handshake without1089* waiting to read our post-handshake NewSessionTickets.1090*/1091s->rwstate = SSL_NOTHING;1092break;1093}10941095return WORK_MORE_A;1096}1097break;1098}10991100return WORK_FINISHED_CONTINUE;1101}11021103/*1104* Get the message construction function and message type for sending from the1105* server1106*1107* Valid return values are:1108* 1: Success1109* 0: Error1110*/1111int ossl_statem_server_construct_message(SSL_CONNECTION *s,1112confunc_f *confunc, int *mt)1113{1114OSSL_STATEM *st = &s->statem;11151116switch (st->hand_state) {1117default:1118/* Shouldn't happen */1119SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);1120return 0;11211122case TLS_ST_SW_CHANGE:1123if (SSL_CONNECTION_IS_DTLS(s))1124*confunc = dtls_construct_change_cipher_spec;1125else1126*confunc = tls_construct_change_cipher_spec;1127*mt = SSL3_MT_CHANGE_CIPHER_SPEC;1128break;11291130case DTLS_ST_SW_HELLO_VERIFY_REQUEST:1131*confunc = dtls_construct_hello_verify_request;1132*mt = DTLS1_MT_HELLO_VERIFY_REQUEST;1133break;11341135case TLS_ST_SW_HELLO_REQ:1136/* No construction function needed */1137*confunc = NULL;1138*mt = SSL3_MT_HELLO_REQUEST;1139break;11401141case TLS_ST_SW_SRVR_HELLO:1142*confunc = tls_construct_server_hello;1143*mt = SSL3_MT_SERVER_HELLO;1144break;11451146case TLS_ST_SW_CERT:1147*confunc = tls_construct_server_certificate;1148*mt = SSL3_MT_CERTIFICATE;1149break;11501151#ifndef OPENSSL_NO_COMP_ALG1152case TLS_ST_SW_COMP_CERT:1153*confunc = tls_construct_server_compressed_certificate;1154*mt = SSL3_MT_COMPRESSED_CERTIFICATE;1155break;1156#endif11571158case TLS_ST_SW_CERT_VRFY:1159*confunc = tls_construct_cert_verify;1160*mt = SSL3_MT_CERTIFICATE_VERIFY;1161break;116211631164case TLS_ST_SW_KEY_EXCH:1165*confunc = tls_construct_server_key_exchange;1166*mt = SSL3_MT_SERVER_KEY_EXCHANGE;1167break;11681169case TLS_ST_SW_CERT_REQ:1170*confunc = tls_construct_certificate_request;1171*mt = SSL3_MT_CERTIFICATE_REQUEST;1172break;11731174case TLS_ST_SW_SRVR_DONE:1175*confunc = tls_construct_server_done;1176*mt = SSL3_MT_SERVER_DONE;1177break;11781179case TLS_ST_SW_SESSION_TICKET:1180*confunc = tls_construct_new_session_ticket;1181*mt = SSL3_MT_NEWSESSION_TICKET;1182break;11831184case TLS_ST_SW_CERT_STATUS:1185*confunc = tls_construct_cert_status;1186*mt = SSL3_MT_CERTIFICATE_STATUS;1187break;11881189case TLS_ST_SW_FINISHED:1190*confunc = tls_construct_finished;1191*mt = SSL3_MT_FINISHED;1192break;11931194case TLS_ST_EARLY_DATA:1195*confunc = NULL;1196*mt = SSL3_MT_DUMMY;1197break;11981199case TLS_ST_SW_ENCRYPTED_EXTENSIONS:1200*confunc = tls_construct_encrypted_extensions;1201*mt = SSL3_MT_ENCRYPTED_EXTENSIONS;1202break;12031204case TLS_ST_SW_KEY_UPDATE:1205*confunc = tls_construct_key_update;1206*mt = SSL3_MT_KEY_UPDATE;1207break;1208}12091210return 1;1211}12121213/*1214* Maximum size (excluding the Handshake header) of a ClientHello message,1215* calculated as follows:1216*1217* 2 + # client_version1218* 32 + # only valid length for random1219* 1 + # length of session_id1220* 32 + # maximum size for session_id1221* 2 + # length of cipher suites1222* 2^16-2 + # maximum length of cipher suites array1223* 1 + # length of compression_methods1224* 2^8-1 + # maximum length of compression methods1225* 2 + # length of extensions1226* 2^16-1 # maximum length of extensions1227*/1228#define CLIENT_HELLO_MAX_LENGTH 13139612291230#define CLIENT_KEY_EXCH_MAX_LENGTH 20481231#define NEXT_PROTO_MAX_LENGTH 51412321233/*1234* Returns the maximum allowed length for the current message that we are1235* reading. Excludes the message header.1236*/1237size_t ossl_statem_server_max_message_size(SSL_CONNECTION *s)1238{1239OSSL_STATEM *st = &s->statem;12401241switch (st->hand_state) {1242default:1243/* Shouldn't happen */1244return 0;12451246case TLS_ST_SR_CLNT_HELLO:1247return CLIENT_HELLO_MAX_LENGTH;12481249case TLS_ST_SR_END_OF_EARLY_DATA:1250return END_OF_EARLY_DATA_MAX_LENGTH;12511252case TLS_ST_SR_COMP_CERT:1253case TLS_ST_SR_CERT:1254return s->max_cert_list;12551256case TLS_ST_SR_KEY_EXCH:1257return CLIENT_KEY_EXCH_MAX_LENGTH;12581259case TLS_ST_SR_CERT_VRFY:1260return CERTIFICATE_VERIFY_MAX_LENGTH;12611262#ifndef OPENSSL_NO_NEXTPROTONEG1263case TLS_ST_SR_NEXT_PROTO:1264return NEXT_PROTO_MAX_LENGTH;1265#endif12661267case TLS_ST_SR_CHANGE:1268return CCS_MAX_LENGTH;12691270case TLS_ST_SR_FINISHED:1271return FINISHED_MAX_LENGTH;12721273case TLS_ST_SR_KEY_UPDATE:1274return KEY_UPDATE_MAX_LENGTH;1275}1276}12771278/*1279* Process a message that the server has received from the client.1280*/1281MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL_CONNECTION *s,1282PACKET *pkt)1283{1284OSSL_STATEM *st = &s->statem;12851286switch (st->hand_state) {1287default:1288/* Shouldn't happen */1289SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1290return MSG_PROCESS_ERROR;12911292case TLS_ST_SR_CLNT_HELLO:1293return tls_process_client_hello(s, pkt);12941295case TLS_ST_SR_END_OF_EARLY_DATA:1296return tls_process_end_of_early_data(s, pkt);12971298case TLS_ST_SR_CERT:1299return tls_process_client_certificate(s, pkt);13001301#ifndef OPENSSL_NO_COMP_ALG1302case TLS_ST_SR_COMP_CERT:1303return tls_process_client_compressed_certificate(s, pkt);1304#endif13051306case TLS_ST_SR_KEY_EXCH:1307return tls_process_client_key_exchange(s, pkt);13081309case TLS_ST_SR_CERT_VRFY:1310return tls_process_cert_verify(s, pkt);13111312#ifndef OPENSSL_NO_NEXTPROTONEG1313case TLS_ST_SR_NEXT_PROTO:1314return tls_process_next_proto(s, pkt);1315#endif13161317case TLS_ST_SR_CHANGE:1318return tls_process_change_cipher_spec(s, pkt);13191320case TLS_ST_SR_FINISHED:1321return tls_process_finished(s, pkt);13221323case TLS_ST_SR_KEY_UPDATE:1324return tls_process_key_update(s, pkt);13251326}1327}13281329/*1330* Perform any further processing required following the receipt of a message1331* from the client1332*/1333WORK_STATE ossl_statem_server_post_process_message(SSL_CONNECTION *s,1334WORK_STATE wst)1335{1336OSSL_STATEM *st = &s->statem;13371338switch (st->hand_state) {1339default:1340/* Shouldn't happen */1341SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1342return WORK_ERROR;13431344case TLS_ST_SR_CLNT_HELLO:1345return tls_post_process_client_hello(s, wst);13461347case TLS_ST_SR_KEY_EXCH:1348return tls_post_process_client_key_exchange(s, wst);1349}1350}13511352#ifndef OPENSSL_NO_SRP1353/* Returns 1 on success, 0 for retryable error, -1 for fatal error */1354static int ssl_check_srp_ext_ClientHello(SSL_CONNECTION *s)1355{1356int ret;1357int al = SSL_AD_UNRECOGNIZED_NAME;13581359if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&1360(s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {1361if (s->srp_ctx.login == NULL) {1362/*1363* RFC 5054 says SHOULD reject, we do so if There is no srp1364* login name1365*/1366SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,1367SSL_R_PSK_IDENTITY_NOT_FOUND);1368return -1;1369} else {1370ret = ssl_srp_server_param_with_username_intern(s, &al);1371if (ret < 0)1372return 0;1373if (ret == SSL3_AL_FATAL) {1374SSLfatal(s, al,1375al == SSL_AD_UNKNOWN_PSK_IDENTITY1376? SSL_R_PSK_IDENTITY_NOT_FOUND1377: SSL_R_CLIENTHELLO_TLSEXT);1378return -1;1379}1380}1381}1382return 1;1383}1384#endif13851386int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,1387size_t cookie_len)1388{1389/* Always use DTLS 1.0 version: see RFC 6347 */1390if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)1391|| !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))1392return 0;13931394return 1;1395}13961397CON_FUNC_RETURN dtls_construct_hello_verify_request(SSL_CONNECTION *s,1398WPACKET *pkt)1399{1400unsigned int cookie_leni;1401SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);14021403if (sctx->app_gen_cookie_cb == NULL1404|| sctx->app_gen_cookie_cb(SSL_CONNECTION_GET_USER_SSL(s), s->d1->cookie,1405&cookie_leni) == 01406|| cookie_leni > DTLS1_COOKIE_LENGTH) {1407SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);1408return CON_FUNC_ERROR;1409}1410s->d1->cookie_len = cookie_leni;14111412if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,1413s->d1->cookie_len)) {1414SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);1415return CON_FUNC_ERROR;1416}14171418return CON_FUNC_SUCCESS;1419}14201421/*-1422* ssl_check_for_safari attempts to fingerprint Safari using OS X1423* SecureTransport using the TLS extension block in |hello|.1424* Safari, since 10.6, sends exactly these extensions, in this order:1425* SNI,1426* elliptic_curves1427* ec_point_formats1428* signature_algorithms (for TLSv1.2 only)1429*1430* We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,1431* but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.1432* Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from1433* 10.8..10.8.3 (which don't work).1434*/1435static void ssl_check_for_safari(SSL_CONNECTION *s,1436const CLIENTHELLO_MSG *hello)1437{1438static const unsigned char kSafariExtensionsBlock[] = {14390x00, 0x0a, /* elliptic_curves extension */14400x00, 0x08, /* 8 bytes */14410x00, 0x06, /* 6 bytes of curve ids */14420x00, 0x17, /* P-256 */14430x00, 0x18, /* P-384 */14440x00, 0x19, /* P-521 */144514460x00, 0x0b, /* ec_point_formats */14470x00, 0x02, /* 2 bytes */14480x01, /* 1 point format */14490x00, /* uncompressed */1450/* The following is only present in TLS 1.2 */14510x00, 0x0d, /* signature_algorithms */14520x00, 0x0c, /* 12 bytes */14530x00, 0x0a, /* 10 bytes */14540x05, 0x01, /* SHA-384/RSA */14550x04, 0x01, /* SHA-256/RSA */14560x02, 0x01, /* SHA-1/RSA */14570x04, 0x03, /* SHA-256/ECDSA */14580x02, 0x03, /* SHA-1/ECDSA */1459};1460/* Length of the common prefix (first two extensions). */1461static const size_t kSafariCommonExtensionsLength = 18;1462unsigned int type;1463PACKET sni, tmppkt;1464size_t ext_len;14651466tmppkt = hello->extensions;14671468if (!PACKET_forward(&tmppkt, 2)1469|| !PACKET_get_net_2(&tmppkt, &type)1470|| !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {1471return;1472}14731474if (type != TLSEXT_TYPE_server_name)1475return;14761477ext_len = TLS1_get_client_version(1478SSL_CONNECTION_GET_SSL(s)) >= TLS1_2_VERSION ?1479sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;14801481s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,1482ext_len);1483}14841485#define RENEG_OPTIONS_OK(options) \1486((options & SSL_OP_NO_RENEGOTIATION) == 0 \1487&& (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)14881489MSG_PROCESS_RETURN tls_process_client_hello(SSL_CONNECTION *s, PACKET *pkt)1490{1491/* |cookie| will only be initialized for DTLS. */1492PACKET session_id, compression, extensions, cookie;1493static const unsigned char null_compression = 0;1494CLIENTHELLO_MSG *clienthello = NULL;14951496/* Check if this is actually an unexpected renegotiation ClientHello */1497if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {1498if (!ossl_assert(!SSL_CONNECTION_IS_TLS13(s))) {1499SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1500goto err;1501}1502if (!RENEG_OPTIONS_OK(s->options)1503|| (!s->s3.send_connection_binding1504&& (s->options1505& SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) {1506ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);1507return MSG_PROCESS_FINISHED_READING;1508}1509s->renegotiate = 1;1510s->new_session = 1;1511}15121513clienthello = OPENSSL_zalloc(sizeof(*clienthello));1514if (clienthello == NULL) {1515SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1516goto err;1517}15181519/*1520* First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.1521*/1522clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);1523PACKET_null_init(&cookie);15241525if (clienthello->isv2) {1526unsigned int mt;15271528if (!SSL_IS_FIRST_HANDSHAKE(s)1529|| s->hello_retry_request != SSL_HRR_NONE) {1530SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);1531goto err;1532}15331534/*-1535* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv21536* header is sent directly on the wire, not wrapped as a TLS1537* record. Our record layer just processes the message length and passes1538* the rest right through. Its format is:1539* Byte Content1540* 0-1 msg_length - decoded by the record layer1541* 2 msg_type - s->init_msg points here1542* 3-4 version1543* 5-6 cipher_spec_length1544* 7-8 session_id_length1545* 9-10 challenge_length1546* ... ...1547*/15481549if (!PACKET_get_1(pkt, &mt)1550|| mt != SSL2_MT_CLIENT_HELLO) {1551/*1552* Should never happen. We should have tested this in the record1553* layer in order to have determined that this is an SSLv2 record1554* in the first place1555*/1556SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1557goto err;1558}1559}15601561if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {1562SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);1563goto err;1564}15651566/* Parse the message and load client random. */1567if (clienthello->isv2) {1568/*1569* Handle an SSLv2 backwards compatible ClientHello1570* Note, this is only for SSLv3+ using the backward compatible format.1571* Real SSLv2 is not supported, and is rejected below.1572*/1573unsigned int ciphersuite_len, session_id_len, challenge_len;1574PACKET challenge;15751576if (!PACKET_get_net_2(pkt, &ciphersuite_len)1577|| !PACKET_get_net_2(pkt, &session_id_len)1578|| !PACKET_get_net_2(pkt, &challenge_len)) {1579SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);1580goto err;1581}15821583if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {1584SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);1585goto err;1586}15871588if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,1589ciphersuite_len)1590|| !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)1591|| !PACKET_get_sub_packet(pkt, &challenge, challenge_len)1592/* No extensions. */1593|| PACKET_remaining(pkt) != 0) {1594SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);1595goto err;1596}1597clienthello->session_id_len = session_id_len;15981599/* Load the client random and compression list. We use SSL3_RANDOM_SIZE1600* here rather than sizeof(clienthello->random) because that is the limit1601* for SSLv3 and it is fixed. It won't change even if1602* sizeof(clienthello->random) does.1603*/1604challenge_len = challenge_len > SSL3_RANDOM_SIZE1605? SSL3_RANDOM_SIZE : challenge_len;1606memset(clienthello->random, 0, SSL3_RANDOM_SIZE);1607if (!PACKET_copy_bytes(&challenge,1608clienthello->random + SSL3_RANDOM_SIZE -1609challenge_len, challenge_len)1610/* Advertise only null compression. */1611|| !PACKET_buf_init(&compression, &null_compression, 1)) {1612SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1613goto err;1614}16151616PACKET_null_init(&clienthello->extensions);1617} else {1618/* Regular ClientHello. */1619if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)1620|| !PACKET_get_length_prefixed_1(pkt, &session_id)1621|| !PACKET_copy_all(&session_id, clienthello->session_id,1622SSL_MAX_SSL_SESSION_ID_LENGTH,1623&clienthello->session_id_len)) {1624SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1625goto err;1626}16271628if (SSL_CONNECTION_IS_DTLS(s)) {1629if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {1630SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1631goto err;1632}1633if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,1634DTLS1_COOKIE_LENGTH,1635&clienthello->dtls_cookie_len)) {1636SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1637goto err;1638}1639/*1640* If we require cookies and this ClientHello doesn't contain one,1641* just return since we do not want to allocate any memory yet.1642* So check cookie length...1643*/1644if (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE) {1645if (clienthello->dtls_cookie_len == 0) {1646OPENSSL_free(clienthello);1647return MSG_PROCESS_FINISHED_READING;1648}1649}1650}16511652if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {1653SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1654goto err;1655}16561657if (!PACKET_get_length_prefixed_1(pkt, &compression)) {1658SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1659goto err;1660}16611662/* Could be empty. */1663if (PACKET_remaining(pkt) == 0) {1664PACKET_null_init(&clienthello->extensions);1665} else {1666if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)1667|| PACKET_remaining(pkt) != 0) {1668SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1669goto err;1670}1671}1672}16731674if (!PACKET_copy_all(&compression, clienthello->compressions,1675MAX_COMPRESSIONS_SIZE,1676&clienthello->compressions_len)) {1677SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1678goto err;1679}16801681/* Preserve the raw extensions PACKET for later use */1682extensions = clienthello->extensions;1683if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,1684&clienthello->pre_proc_exts,1685&clienthello->pre_proc_exts_len, 1)) {1686/* SSLfatal already been called */1687goto err;1688}1689s->clienthello = clienthello;16901691return MSG_PROCESS_CONTINUE_PROCESSING;16921693err:1694if (clienthello != NULL)1695OPENSSL_free(clienthello->pre_proc_exts);1696OPENSSL_free(clienthello);16971698return MSG_PROCESS_ERROR;1699}17001701static int tls_early_post_process_client_hello(SSL_CONNECTION *s)1702{1703unsigned int j;1704int i, al = SSL_AD_INTERNAL_ERROR;1705int protverr;1706unsigned long id;1707#ifndef OPENSSL_NO_COMP1708SSL_COMP *comp = NULL;1709#endif1710const SSL_CIPHER *c;1711STACK_OF(SSL_CIPHER) *ciphers = NULL;1712STACK_OF(SSL_CIPHER) *scsvs = NULL;1713CLIENTHELLO_MSG *clienthello = s->clienthello;1714DOWNGRADE dgrd = DOWNGRADE_NONE;1715SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);1716SSL *ssl = SSL_CONNECTION_GET_SSL(s);1717SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);17181719/* Finished parsing the ClientHello, now we can start processing it */1720/* Give the ClientHello callback a crack at things */1721if (sctx->client_hello_cb != NULL) {1722/* A failure in the ClientHello callback terminates the connection. */1723switch (sctx->client_hello_cb(ussl, &al, sctx->client_hello_cb_arg)) {1724case SSL_CLIENT_HELLO_SUCCESS:1725break;1726case SSL_CLIENT_HELLO_RETRY:1727s->rwstate = SSL_CLIENT_HELLO_CB;1728return -1;1729case SSL_CLIENT_HELLO_ERROR:1730default:1731SSLfatal(s, al, SSL_R_CALLBACK_FAILED);1732goto err;1733}1734}17351736/* Set up the client_random */1737memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);17381739/* Choose the version */17401741if (clienthello->isv2) {1742if (clienthello->legacy_version == SSL2_VERSION1743|| (clienthello->legacy_version & 0xff00)1744!= (SSL3_VERSION_MAJOR << 8)) {1745/*1746* This is real SSLv2 or something completely unknown. We don't1747* support it.1748*/1749SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);1750goto err;1751}1752/* SSLv3/TLS */1753s->client_version = clienthello->legacy_version;1754}17551756/* Choose the server SSL/TLS/DTLS version. */1757protverr = ssl_choose_server_version(s, clienthello, &dgrd);17581759if (protverr) {1760if (SSL_IS_FIRST_HANDSHAKE(s)) {1761/* like ssl3_get_record, send alert using remote version number */1762s->version = s->client_version = clienthello->legacy_version;1763}1764SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);1765goto err;1766}17671768/* TLSv1.3 specifies that a ClientHello must end on a record boundary */1769if (SSL_CONNECTION_IS_TLS13(s)1770&& RECORD_LAYER_processed_read_pending(&s->rlayer)) {1771SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);1772goto err;1773}17741775if (SSL_CONNECTION_IS_DTLS(s)) {1776/* Empty cookie was already handled above by returning early. */1777if (SSL_get_options(ssl) & SSL_OP_COOKIE_EXCHANGE) {1778if (sctx->app_verify_cookie_cb != NULL) {1779if (sctx->app_verify_cookie_cb(ussl, clienthello->dtls_cookie,1780clienthello->dtls_cookie_len) == 0) {1781SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,1782SSL_R_COOKIE_MISMATCH);1783goto err;1784/* else cookie verification succeeded */1785}1786/* default verification */1787} else if (s->d1->cookie_len != clienthello->dtls_cookie_len1788|| memcmp(clienthello->dtls_cookie, s->d1->cookie,1789s->d1->cookie_len) != 0) {1790SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);1791goto err;1792}1793s->d1->cookie_verified = 1;1794}1795}17961797s->hit = 0;17981799if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,1800clienthello->isv2) ||1801!ossl_bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers,1802&scsvs, clienthello->isv2, 1)) {1803/* SSLfatal() already called */1804goto err;1805}18061807s->s3.send_connection_binding = 0;1808/* Check what signalling cipher-suite values were received. */1809if (scsvs != NULL) {1810for (i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {1811c = sk_SSL_CIPHER_value(scsvs, i);1812if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {1813if (s->renegotiate) {1814/* SCSV is fatal if renegotiating */1815SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,1816SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);1817goto err;1818}1819s->s3.send_connection_binding = 1;1820} else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&1821!ssl_check_version_downgrade(s)) {1822/*1823* This SCSV indicates that the client previously tried1824* a higher version. We should fail if the current version1825* is an unexpected downgrade, as that indicates that the first1826* connection may have been tampered with in order to trigger1827* an insecure downgrade.1828*/1829SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,1830SSL_R_INAPPROPRIATE_FALLBACK);1831goto err;1832}1833}1834}18351836/* For TLSv1.3 we must select the ciphersuite *before* session resumption */1837if (SSL_CONNECTION_IS_TLS13(s)) {1838const SSL_CIPHER *cipher =1839ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(ssl));18401841if (cipher == NULL) {1842SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);1843goto err;1844}1845if (s->hello_retry_request == SSL_HRR_PENDING1846&& (s->s3.tmp.new_cipher == NULL1847|| s->s3.tmp.new_cipher->id != cipher->id)) {1848/*1849* A previous HRR picked a different ciphersuite to the one we1850* just selected. Something must have changed.1851*/1852SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);1853goto err;1854}1855s->s3.tmp.new_cipher = cipher;1856}18571858/* We need to do this before getting the session */1859if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,1860SSL_EXT_CLIENT_HELLO,1861clienthello->pre_proc_exts, NULL, 0)) {1862/* SSLfatal() already called */1863goto err;1864}18651866/*1867* We don't allow resumption in a backwards compatible ClientHello.1868* In TLS1.1+, session_id MUST be empty.1869*1870* Versions before 0.9.7 always allow clients to resume sessions in1871* renegotiation. 0.9.7 and later allow this by default, but optionally1872* ignore resumption requests with flag1873* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather1874* than a change to default behavior so that applications relying on1875* this for security won't even compile against older library versions).1876* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to1877* request renegotiation but not a new session (s->new_session remains1878* unset): for servers, this essentially just means that the1879* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be1880* ignored.1881*/1882if (clienthello->isv2 ||1883(s->new_session &&1884(s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {1885if (!ssl_get_new_session(s, 1)) {1886/* SSLfatal() already called */1887goto err;1888}1889} else {1890i = ssl_get_prev_session(s, clienthello);1891if (i == 1) {1892/* previous session */1893s->hit = 1;1894} else if (i == -1) {1895/* SSLfatal() already called */1896goto err;1897} else {1898/* i == 0 */1899if (!ssl_get_new_session(s, 1)) {1900/* SSLfatal() already called */1901goto err;1902}1903}1904}19051906if (SSL_CONNECTION_IS_TLS13(s)) {1907memcpy(s->tmp_session_id, s->clienthello->session_id,1908s->clienthello->session_id_len);1909s->tmp_session_id_len = s->clienthello->session_id_len;1910}19111912/*1913* If it is a hit, check that the cipher is in the list. In TLSv1.3 we check1914* ciphersuite compatibility with the session as part of resumption.1915*/1916if (!SSL_CONNECTION_IS_TLS13(s) && s->hit) {1917j = 0;1918id = s->session->cipher->id;19191920OSSL_TRACE_BEGIN(TLS_CIPHER) {1921BIO_printf(trc_out, "client sent %d ciphers\n",1922sk_SSL_CIPHER_num(ciphers));1923}1924for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {1925c = sk_SSL_CIPHER_value(ciphers, i);1926if (trc_out != NULL)1927BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,1928sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));1929if (c->id == id) {1930j = 1;1931break;1932}1933}1934if (j == 0) {1935/*1936* we need to have the cipher in the cipher list if we are asked1937* to reuse it1938*/1939SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1940SSL_R_REQUIRED_CIPHER_MISSING);1941OSSL_TRACE_CANCEL(TLS_CIPHER);1942goto err;1943}1944OSSL_TRACE_END(TLS_CIPHER);1945}19461947/* At least one compression method must be preset. */1948if (clienthello->compressions_len == 0) {1949SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);1950goto err;1951}1952/* Make sure at least the null compression is supported. */1953if (memchr(clienthello->compressions, 0,1954clienthello->compressions_len) == NULL) {1955SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1956SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);1957goto err;1958}19591960if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)1961ssl_check_for_safari(s, clienthello);19621963/* TLS extensions */1964if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,1965clienthello->pre_proc_exts, NULL, 0, 1)) {1966/* SSLfatal() already called */1967goto err;1968}19691970/*1971* Check if we want to use external pre-shared secret for this handshake1972* for not reused session only. We need to generate server_random before1973* calling tls_session_secret_cb in order to allow SessionTicket1974* processing to use it in key derivation.1975*/1976{1977unsigned char *pos;1978pos = s->s3.server_random;1979if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {1980SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1981goto err;1982}1983}19841985if (!s->hit && !tls1_set_server_sigalgs(s)) {1986/* SSLfatal() already called */1987goto err;1988}19891990if (!s->hit1991&& s->version >= TLS1_VERSION1992&& !SSL_CONNECTION_IS_TLS13(s)1993&& !SSL_CONNECTION_IS_DTLS(s)1994&& s->ext.session_secret_cb != NULL) {1995const SSL_CIPHER *pref_cipher = NULL;1996/*1997* s->session->master_key_length is a size_t, but this is an int for1998* backwards compat reasons1999*/2000int master_key_length;20012002master_key_length = sizeof(s->session->master_key);2003if (s->ext.session_secret_cb(ussl, s->session->master_key,2004&master_key_length, ciphers,2005&pref_cipher,2006s->ext.session_secret_cb_arg)2007&& master_key_length > 0) {2008s->session->master_key_length = master_key_length;2009s->hit = 1;2010s->peer_ciphers = ciphers;2011s->session->verify_result = X509_V_OK;20122013ciphers = NULL;20142015/* check if some cipher was preferred by call back */2016if (pref_cipher == NULL)2017pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,2018SSL_get_ciphers(ssl));2019if (pref_cipher == NULL) {2020SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);2021goto err;2022}20232024s->session->cipher = pref_cipher;2025sk_SSL_CIPHER_free(s->cipher_list);2026s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);2027sk_SSL_CIPHER_free(s->cipher_list_by_id);2028s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);2029}2030}20312032/*2033* Worst case, we will use the NULL compression, but if we have other2034* options, we will now look for them. We have complen-1 compression2035* algorithms from the client, starting at q.2036*/2037s->s3.tmp.new_compression = NULL;2038if (SSL_CONNECTION_IS_TLS13(s)) {2039/*2040* We already checked above that the NULL compression method appears in2041* the list. Now we check there aren't any others (which is illegal in2042* a TLSv1.3 ClientHello.2043*/2044if (clienthello->compressions_len != 1) {2045SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,2046SSL_R_INVALID_COMPRESSION_ALGORITHM);2047goto err;2048}2049}2050#ifndef OPENSSL_NO_COMP2051/* This only happens if we have a cache hit */2052else if (s->session->compress_meth != 0) {2053int m, comp_id = s->session->compress_meth;2054unsigned int k;2055/* Perform sanity checks on resumed compression algorithm */2056/* Can't disable compression */2057if (!ssl_allow_compression(s)) {2058SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2059SSL_R_INCONSISTENT_COMPRESSION);2060goto err;2061}2062/* Look for resumed compression method */2063for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {2064comp = sk_SSL_COMP_value(sctx->comp_methods, m);2065if (comp_id == comp->id) {2066s->s3.tmp.new_compression = comp;2067break;2068}2069}2070if (s->s3.tmp.new_compression == NULL) {2071SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2072SSL_R_INVALID_COMPRESSION_ALGORITHM);2073goto err;2074}2075/* Look for resumed method in compression list */2076for (k = 0; k < clienthello->compressions_len; k++) {2077if (clienthello->compressions[k] == comp_id)2078break;2079}2080if (k >= clienthello->compressions_len) {2081SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,2082SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);2083goto err;2084}2085} else if (s->hit) {2086comp = NULL;2087} else if (ssl_allow_compression(s) && sctx->comp_methods) {2088/* See if we have a match */2089int m, nn, v, done = 0;2090unsigned int o;20912092nn = sk_SSL_COMP_num(sctx->comp_methods);2093for (m = 0; m < nn; m++) {2094comp = sk_SSL_COMP_value(sctx->comp_methods, m);2095v = comp->id;2096for (o = 0; o < clienthello->compressions_len; o++) {2097if (v == clienthello->compressions[o]) {2098done = 1;2099break;2100}2101}2102if (done)2103break;2104}2105if (done)2106s->s3.tmp.new_compression = comp;2107else2108comp = NULL;2109}2110#else2111/*2112* If compression is disabled we'd better not try to resume a session2113* using compression.2114*/2115if (s->session->compress_meth != 0) {2116SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);2117goto err;2118}2119#endif21202121/*2122* Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher2123*/21242125if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {2126sk_SSL_CIPHER_free(s->peer_ciphers);2127s->peer_ciphers = ciphers;2128if (ciphers == NULL) {2129SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2130goto err;2131}2132ciphers = NULL;2133}21342135if (!s->hit) {2136#ifdef OPENSSL_NO_COMP2137s->session->compress_meth = 0;2138#else2139s->session->compress_meth = (comp == NULL) ? 0 : comp->id;2140#endif2141}21422143sk_SSL_CIPHER_free(ciphers);2144sk_SSL_CIPHER_free(scsvs);2145OPENSSL_free(clienthello->pre_proc_exts);2146OPENSSL_free(s->clienthello);2147s->clienthello = NULL;2148return 1;2149err:2150sk_SSL_CIPHER_free(ciphers);2151sk_SSL_CIPHER_free(scsvs);2152OPENSSL_free(clienthello->pre_proc_exts);2153OPENSSL_free(s->clienthello);2154s->clienthello = NULL;21552156return 0;2157}21582159/*2160* Call the status request callback if needed. Upon success, returns 1.2161* Upon failure, returns 0.2162*/2163static int tls_handle_status_request(SSL_CONNECTION *s)2164{2165SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);21662167s->ext.status_expected = 0;21682169/*2170* If status request then ask callback what to do. Note: this must be2171* called after servername callbacks in case the certificate has changed,2172* and must be called after the cipher has been chosen because this may2173* influence which certificate is sent2174*/2175if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL2176&& sctx->ext.status_cb != NULL) {2177int ret;21782179/* If no certificate can't return certificate status */2180if (s->s3.tmp.cert != NULL) {2181/*2182* Set current certificate to one we will use so SSL_get_certificate2183* et al can pick it up.2184*/2185s->cert->key = s->s3.tmp.cert;2186ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),2187sctx->ext.status_arg);2188switch (ret) {2189/* We don't want to send a status request response */2190case SSL_TLSEXT_ERR_NOACK:2191s->ext.status_expected = 0;2192break;2193/* status request response should be sent */2194case SSL_TLSEXT_ERR_OK:2195if (s->ext.ocsp.resp)2196s->ext.status_expected = 1;2197break;2198/* something bad happened */2199case SSL_TLSEXT_ERR_ALERT_FATAL:2200default:2201SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);2202return 0;2203}2204}2205}22062207return 1;2208}22092210/*2211* Call the alpn_select callback if needed. Upon success, returns 1.2212* Upon failure, returns 0.2213*/2214int tls_handle_alpn(SSL_CONNECTION *s)2215{2216const unsigned char *selected = NULL;2217unsigned char selected_len = 0;2218SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);22192220if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {2221int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),2222&selected, &selected_len,2223s->s3.alpn_proposed,2224(unsigned int)s->s3.alpn_proposed_len,2225sctx->ext.alpn_select_cb_arg);22262227if (r == SSL_TLSEXT_ERR_OK) {2228OPENSSL_free(s->s3.alpn_selected);2229s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);2230if (s->s3.alpn_selected == NULL) {2231s->s3.alpn_selected_len = 0;2232SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2233return 0;2234}2235s->s3.alpn_selected_len = selected_len;2236#ifndef OPENSSL_NO_NEXTPROTONEG2237/* ALPN takes precedence over NPN. */2238s->s3.npn_seen = 0;2239#endif22402241/* Check ALPN is consistent with session */2242if (s->session->ext.alpn_selected == NULL2243|| selected_len != s->session->ext.alpn_selected_len2244|| memcmp(selected, s->session->ext.alpn_selected,2245selected_len) != 0) {2246/* Not consistent so can't be used for early_data */2247s->ext.early_data_ok = 0;22482249if (!s->hit) {2250/*2251* This is a new session and so alpn_selected should have2252* been initialised to NULL. We should update it with the2253* selected ALPN.2254*/2255if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {2256SSLfatal(s, SSL_AD_INTERNAL_ERROR,2257ERR_R_INTERNAL_ERROR);2258return 0;2259}2260s->session->ext.alpn_selected = OPENSSL_memdup(selected,2261selected_len);2262if (s->session->ext.alpn_selected == NULL) {2263SSLfatal(s, SSL_AD_INTERNAL_ERROR,2264ERR_R_INTERNAL_ERROR);2265return 0;2266}2267s->session->ext.alpn_selected_len = selected_len;2268}2269}22702271return 1;2272} else if (r != SSL_TLSEXT_ERR_NOACK) {2273SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,2274SSL_R_NO_APPLICATION_PROTOCOL);2275return 0;2276}2277/*2278* If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was2279* present.2280*/2281}22822283/* Check ALPN is consistent with session */2284if (s->session->ext.alpn_selected != NULL) {2285/* Not consistent so can't be used for early_data */2286s->ext.early_data_ok = 0;2287}22882289return 1;2290}22912292WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)2293{2294const SSL_CIPHER *cipher;2295SSL *ssl = SSL_CONNECTION_GET_SSL(s);2296SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);22972298if (wst == WORK_MORE_A) {2299int rv = tls_early_post_process_client_hello(s);2300if (rv == 0) {2301/* SSLfatal() was already called */2302goto err;2303}2304if (rv < 0)2305return WORK_MORE_A;2306wst = WORK_MORE_B;2307}2308if (wst == WORK_MORE_B) {2309if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {2310/* Let cert callback update server certificates if required */2311if (!s->hit && s->cert->cert_cb != NULL) {2312int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);23132314if (rv == 0) {2315SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);2316goto err;2317}2318if (rv < 0) {2319s->rwstate = SSL_X509_LOOKUP;2320return WORK_MORE_B;2321}2322s->rwstate = SSL_NOTHING;2323}23242325/* In TLSv1.3 we selected the ciphersuite before resumption */2326if (!SSL_CONNECTION_IS_TLS13(s)) {2327cipher =2328ssl3_choose_cipher(s, s->peer_ciphers,2329SSL_get_ciphers(ssl));23302331if (cipher == NULL) {2332SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2333SSL_R_NO_SHARED_CIPHER);2334goto err;2335}2336s->s3.tmp.new_cipher = cipher;2337}2338if (!s->hit) {2339if (!tls_choose_sigalg(s, 1)) {2340/* SSLfatal already called */2341goto err;2342}2343/* check whether we should disable session resumption */2344if (s->not_resumable_session_cb != NULL)2345s->session->not_resumable =2346s->not_resumable_session_cb(ussl,2347((s->s3.tmp.new_cipher->algorithm_mkey2348& (SSL_kDHE | SSL_kECDHE)) != 0));2349if (s->session->not_resumable)2350/* do not send a session ticket */2351s->ext.ticket_expected = 0;2352}2353} else {2354/* Session-id reuse */2355s->s3.tmp.new_cipher = s->session->cipher;2356}23572358/*-2359* we now have the following setup.2360* client_random2361* cipher_list - our preferred list of ciphers2362* ciphers - the client's preferred list of ciphers2363* compression - basically ignored right now2364* ssl version is set - sslv32365* s->session - The ssl session has been setup.2366* s->hit - session reuse flag2367* s->s3.tmp.new_cipher - the new cipher to use.2368*/23692370/*2371* Call status_request callback if needed. Has to be done after the2372* certificate callbacks etc above.2373*/2374if (!tls_handle_status_request(s)) {2375/* SSLfatal() already called */2376goto err;2377}2378/*2379* Call alpn_select callback if needed. Has to be done after SNI and2380* cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.32381* we already did this because cipher negotiation happens earlier, and2382* we must handle ALPN before we decide whether to accept early_data.2383*/2384if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {2385/* SSLfatal() already called */2386goto err;2387}23882389wst = WORK_MORE_C;2390}2391#ifndef OPENSSL_NO_SRP2392if (wst == WORK_MORE_C) {2393int ret;2394if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {2395/*2396* callback indicates further work to be done2397*/2398s->rwstate = SSL_X509_LOOKUP;2399return WORK_MORE_C;2400}2401if (ret < 0) {2402/* SSLfatal() already called */2403goto err;2404}2405}2406#endif24072408return WORK_FINISHED_STOP;2409err:2410return WORK_ERROR;2411}24122413CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)2414{2415int compm;2416size_t sl, len;2417int version;2418unsigned char *session_id;2419int usetls13 = SSL_CONNECTION_IS_TLS13(s)2420|| s->hello_retry_request == SSL_HRR_PENDING;24212422version = usetls13 ? TLS1_2_VERSION : s->version;2423if (!WPACKET_put_bytes_u16(pkt, version)2424/*2425* Random stuff. Filling of the server_random takes place in2426* tls_process_client_hello()2427*/2428|| !WPACKET_memcpy(pkt,2429s->hello_retry_request == SSL_HRR_PENDING2430? hrrrandom : s->s3.server_random,2431SSL3_RANDOM_SIZE)) {2432SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2433return CON_FUNC_ERROR;2434}24352436/*-2437* There are several cases for the session ID to send2438* back in the server hello:2439* - For session reuse from the session cache,2440* we send back the old session ID.2441* - If stateless session reuse (using a session ticket)2442* is successful, we send back the client's "session ID"2443* (which doesn't actually identify the session).2444* - If it is a new session, we send back the new2445* session ID.2446* - However, if we want the new session to be single-use,2447* we send back a 0-length session ID.2448* - In TLSv1.3 we echo back the session id sent to us by the client2449* regardless2450* s->hit is non-zero in either case of session reuse,2451* so the following won't overwrite an ID that we're supposed2452* to send back.2453*/2454if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)2455&& !s->hit)2456s->session->session_id_length = 0;24572458if (usetls13) {2459sl = s->tmp_session_id_len;2460session_id = s->tmp_session_id;2461} else {2462sl = s->session->session_id_length;2463session_id = s->session->session_id;2464}24652466if (sl > sizeof(s->session->session_id)) {2467SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2468return CON_FUNC_ERROR;2469}24702471/* set up the compression method */2472#ifdef OPENSSL_NO_COMP2473compm = 0;2474#else2475if (usetls13 || s->s3.tmp.new_compression == NULL)2476compm = 0;2477else2478compm = s->s3.tmp.new_compression->id;2479#endif24802481if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)2482|| !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,2483pkt, &len)2484|| !WPACKET_put_bytes_u8(pkt, compm)) {2485SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2486return CON_FUNC_ERROR;2487}24882489if (!tls_construct_extensions(s, pkt,2490s->hello_retry_request == SSL_HRR_PENDING2491? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST2492: (SSL_CONNECTION_IS_TLS13(s)2493? SSL_EXT_TLS1_3_SERVER_HELLO2494: SSL_EXT_TLS1_2_SERVER_HELLO),2495NULL, 0)) {2496/* SSLfatal() already called */2497return CON_FUNC_ERROR;2498}24992500if (s->hello_retry_request == SSL_HRR_PENDING) {2501/* Ditch the session. We'll create a new one next time around */2502SSL_SESSION_free(s->session);2503s->session = NULL;2504s->hit = 0;25052506/*2507* Re-initialise the Transcript Hash. We're going to prepopulate it with2508* a synthetic message_hash in place of ClientHello1.2509*/2510if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {2511/* SSLfatal() already called */2512return CON_FUNC_ERROR;2513}2514} else if (!(s->verify_mode & SSL_VERIFY_PEER)2515&& !ssl3_digest_cached_records(s, 0)) {2516/* SSLfatal() already called */;2517return CON_FUNC_ERROR;2518}25192520return CON_FUNC_SUCCESS;2521}25222523CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)2524{2525if (!s->s3.tmp.cert_request) {2526if (!ssl3_digest_cached_records(s, 0)) {2527/* SSLfatal() already called */2528return CON_FUNC_ERROR;2529}2530}2531return CON_FUNC_SUCCESS;2532}25332534CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,2535WPACKET *pkt)2536{2537EVP_PKEY *pkdh = NULL;2538unsigned char *encodedPoint = NULL;2539size_t encodedlen = 0;2540int curve_id = 0;2541const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;2542int i;2543unsigned long type;2544BIGNUM *r[4];2545EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();2546EVP_PKEY_CTX *pctx = NULL;2547size_t paramlen, paramoffset;2548int freer = 0;2549CON_FUNC_RETURN ret = CON_FUNC_ERROR;2550SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);25512552if (!WPACKET_get_total_written(pkt, ¶moffset)) {2553SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2554goto err;2555}25562557if (md_ctx == NULL) {2558SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2559goto err;2560}25612562type = s->s3.tmp.new_cipher->algorithm_mkey;25632564r[0] = r[1] = r[2] = r[3] = NULL;2565#ifndef OPENSSL_NO_PSK2566/* Plain PSK or RSAPSK nothing to do */2567if (type & (SSL_kPSK | SSL_kRSAPSK)) {2568} else2569#endif /* !OPENSSL_NO_PSK */2570if (type & (SSL_kDHE | SSL_kDHEPSK)) {2571CERT *cert = s->cert;2572EVP_PKEY *pkdhp = NULL;25732574if (s->cert->dh_tmp_auto) {2575pkdh = ssl_get_auto_dh(s);2576if (pkdh == NULL) {2577SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2578goto err;2579}2580pkdhp = pkdh;2581} else {2582pkdhp = cert->dh_tmp;2583}2584#if !defined(OPENSSL_NO_DEPRECATED_3_0)2585if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {2586pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s),25870, 1024));2588if (pkdh == NULL) {2589SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2590goto err;2591}2592pkdhp = pkdh;2593}2594#endif2595if (pkdhp == NULL) {2596SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);2597goto err;2598}2599if (!ssl_security(s, SSL_SECOP_TMP_DH,2600EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {2601SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);2602goto err;2603}2604if (s->s3.tmp.pkey != NULL) {2605SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2606goto err;2607}26082609s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);2610if (s->s3.tmp.pkey == NULL) {2611SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2612goto err;2613}26142615EVP_PKEY_free(pkdh);2616pkdh = NULL;26172618/* These BIGNUMs need to be freed when we're finished */2619freer = 1;2620if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,2621&r[0])2622|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,2623&r[1])2624|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,2625OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {2626SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2627goto err;2628}2629} else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {26302631if (s->s3.tmp.pkey != NULL) {2632SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2633goto err;2634}26352636/* Get NID of appropriate shared curve */2637curve_id = tls1_shared_group(s, -2);2638if (curve_id == 0) {2639SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2640SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);2641goto err;2642}2643/* Cache the group used in the SSL_SESSION */2644s->session->kex_group = curve_id;2645/* Generate a new key for this curve */2646s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);2647if (s->s3.tmp.pkey == NULL) {2648/* SSLfatal() already called */2649goto err;2650}26512652/* Encode the public key. */2653encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,2654&encodedPoint);2655if (encodedlen == 0) {2656SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);2657goto err;2658}26592660/*2661* We'll generate the serverKeyExchange message explicitly so we2662* can set these to NULLs2663*/2664r[0] = NULL;2665r[1] = NULL;2666r[2] = NULL;2667r[3] = NULL;2668} else2669#ifndef OPENSSL_NO_SRP2670if (type & SSL_kSRP) {2671if ((s->srp_ctx.N == NULL) ||2672(s->srp_ctx.g == NULL) ||2673(s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {2674SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);2675goto err;2676}2677r[0] = s->srp_ctx.N;2678r[1] = s->srp_ctx.g;2679r[2] = s->srp_ctx.s;2680r[3] = s->srp_ctx.B;2681} else2682#endif2683{2684SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);2685goto err;2686}26872688if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)2689|| ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {2690lu = NULL;2691} else if (lu == NULL) {2692SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);2693goto err;2694}26952696#ifndef OPENSSL_NO_PSK2697if (type & SSL_PSK) {2698size_t len = (s->cert->psk_identity_hint == NULL)2699? 0 : strlen(s->cert->psk_identity_hint);27002701/*2702* It should not happen that len > PSK_MAX_IDENTITY_LEN - we already2703* checked this when we set the identity hint - but just in case2704*/2705if (len > PSK_MAX_IDENTITY_LEN2706|| !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,2707len)) {2708SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2709goto err;2710}2711}2712#endif27132714for (i = 0; i < 4 && r[i] != NULL; i++) {2715unsigned char *binval;2716int res;27172718#ifndef OPENSSL_NO_SRP2719if ((i == 2) && (type & SSL_kSRP)) {2720res = WPACKET_start_sub_packet_u8(pkt);2721} else2722#endif2723res = WPACKET_start_sub_packet_u16(pkt);27242725if (!res) {2726SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2727goto err;2728}27292730/*-2731* for interoperability with some versions of the Microsoft TLS2732* stack, we need to zero pad the DHE pub key to the same length2733* as the prime2734*/2735if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {2736size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);27372738if (len > 0) {2739if (!WPACKET_allocate_bytes(pkt, len, &binval)) {2740SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2741goto err;2742}2743memset(binval, 0, len);2744}2745}27462747if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)2748|| !WPACKET_close(pkt)) {2749SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2750goto err;2751}27522753BN_bn2bin(r[i], binval);2754}27552756if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {2757/*2758* We only support named (not generic) curves. In this situation, the2759* ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]2760* [1 byte length of encoded point], followed by the actual encoded2761* point itself2762*/2763if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)2764|| !WPACKET_put_bytes_u8(pkt, 0)2765|| !WPACKET_put_bytes_u8(pkt, curve_id)2766|| !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {2767SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2768goto err;2769}2770OPENSSL_free(encodedPoint);2771encodedPoint = NULL;2772}27732774/* not anonymous */2775if (lu != NULL) {2776EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;2777const EVP_MD *md;2778unsigned char *sigbytes1, *sigbytes2, *tbs;2779size_t siglen = 0, tbslen;27802781if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {2782/* Should never happen */2783SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2784goto err;2785}2786/* Get length of the parameters we have written above */2787if (!WPACKET_get_length(pkt, ¶mlen)) {2788SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2789goto err;2790}2791/* send signature algorithm */2792if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {2793SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2794goto err;2795}27962797if (EVP_DigestSignInit_ex(md_ctx, &pctx,2798md == NULL ? NULL : EVP_MD_get0_name(md),2799sctx->libctx, sctx->propq, pkey,2800NULL) <= 0) {2801SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2802goto err;2803}2804if (lu->sig == EVP_PKEY_RSA_PSS) {2805if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 02806|| EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {2807SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2808goto err;2809}2810}2811tbslen = construct_key_exchange_tbs(s, &tbs,2812s->init_buf->data + paramoffset,2813paramlen);2814if (tbslen == 0) {2815/* SSLfatal() already called */2816goto err;2817}28182819if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <=02820|| !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)2821|| EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 02822|| !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)2823|| sigbytes1 != sigbytes2) {2824OPENSSL_free(tbs);2825SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2826goto err;2827}2828OPENSSL_free(tbs);2829}28302831ret = CON_FUNC_SUCCESS;2832err:2833EVP_PKEY_free(pkdh);2834OPENSSL_free(encodedPoint);2835EVP_MD_CTX_free(md_ctx);2836if (freer) {2837BN_free(r[0]);2838BN_free(r[1]);2839BN_free(r[2]);2840BN_free(r[3]);2841}2842return ret;2843}28442845CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,2846WPACKET *pkt)2847{2848if (SSL_CONNECTION_IS_TLS13(s)) {2849/* Send random context when doing post-handshake auth */2850if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {2851OPENSSL_free(s->pha_context);2852s->pha_context_len = 32;2853if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {2854s->pha_context_len = 0;2855SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2856return CON_FUNC_ERROR;2857}2858if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,2859s->pha_context, s->pha_context_len, 0) <= 02860|| !WPACKET_sub_memcpy_u8(pkt, s->pha_context,2861s->pha_context_len)) {2862SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2863return CON_FUNC_ERROR;2864}2865/* reset the handshake hash back to just after the ClientFinished */2866if (!tls13_restore_handshake_digest_for_pha(s)) {2867/* SSLfatal() already called */2868return CON_FUNC_ERROR;2869}2870} else {2871if (!WPACKET_put_bytes_u8(pkt, 0)) {2872SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2873return CON_FUNC_ERROR;2874}2875}28762877if (!tls_construct_extensions(s, pkt,2878SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,28790)) {2880/* SSLfatal() already called */2881return CON_FUNC_ERROR;2882}2883goto done;2884}28852886/* get the list of acceptable cert types */2887if (!WPACKET_start_sub_packet_u8(pkt)2888|| !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {2889SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2890return CON_FUNC_ERROR;2891}28922893if (SSL_USE_SIGALGS(s)) {2894const uint16_t *psigs;2895size_t nl = tls12_get_psigalgs(s, 1, &psigs);28962897if (!WPACKET_start_sub_packet_u16(pkt)2898|| !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)2899|| !tls12_copy_sigalgs(s, pkt, psigs, nl)2900|| !WPACKET_close(pkt)) {2901SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2902return CON_FUNC_ERROR;2903}2904}29052906if (!construct_ca_names(s, get_ca_names(s), pkt)) {2907/* SSLfatal() already called */2908return CON_FUNC_ERROR;2909}29102911done:2912s->certreqs_sent++;2913s->s3.tmp.cert_request = 1;2914return CON_FUNC_SUCCESS;2915}29162917static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)2918{2919#ifndef OPENSSL_NO_PSK2920unsigned char psk[PSK_MAX_PSK_LEN];2921size_t psklen;2922PACKET psk_identity;29232924if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {2925SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2926return 0;2927}2928if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {2929SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);2930return 0;2931}2932if (s->psk_server_callback == NULL) {2933SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);2934return 0;2935}29362937if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {2938SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2939return 0;2940}29412942psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),2943s->session->psk_identity,2944psk, sizeof(psk));29452946if (psklen > PSK_MAX_PSK_LEN) {2947SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2948return 0;2949} else if (psklen == 0) {2950/*2951* PSK related to the given identity not found2952*/2953SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);2954return 0;2955}29562957OPENSSL_free(s->s3.tmp.psk);2958s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);2959OPENSSL_cleanse(psk, psklen);29602961if (s->s3.tmp.psk == NULL) {2962s->s3.tmp.psklen = 0;2963SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2964return 0;2965}29662967s->s3.tmp.psklen = psklen;29682969return 1;2970#else2971/* Should never happen */2972SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2973return 0;2974#endif2975}29762977static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)2978{2979size_t outlen;2980PACKET enc_premaster;2981EVP_PKEY *rsa = NULL;2982unsigned char *rsa_decrypt = NULL;2983int ret = 0;2984EVP_PKEY_CTX *ctx = NULL;2985OSSL_PARAM params[3], *p = params;2986SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);29872988rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;2989if (rsa == NULL) {2990SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);2991return 0;2992}29932994/* SSLv3 and pre-standard DTLS omit the length bytes. */2995if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {2996enc_premaster = *pkt;2997} else {2998if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)2999|| PACKET_remaining(pkt) != 0) {3000SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3001return 0;3002}3003}30043005outlen = SSL_MAX_MASTER_KEY_LENGTH;3006rsa_decrypt = OPENSSL_malloc(outlen);3007if (rsa_decrypt == NULL) {3008SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3009return 0;3010}30113012ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);3013if (ctx == NULL) {3014SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3015goto err;3016}30173018/*3019* We must not leak whether a decryption failure occurs because of3020* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,3021* section 7.4.7.1). We use the special padding type3022* RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the3023* RSA, check the padding and check that the client version is as expected3024* in the premaster secret. If any of that fails then the function appears3025* to return successfully but with a random result. The call below could3026* still fail if the input is publicly invalid.3027* See https://tools.ietf.org/html/rfc5246#section-7.4.7.13028*/3029if (EVP_PKEY_decrypt_init(ctx) <= 03030|| EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {3031SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3032goto err;3033}30343035*p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,3036(unsigned int *)&s->client_version);3037if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)3038*p++ = OSSL_PARAM_construct_uint(3039OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,3040(unsigned int *)&s->version);3041*p++ = OSSL_PARAM_construct_end();30423043if (!EVP_PKEY_CTX_set_params(ctx, params)3044|| EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,3045PACKET_data(&enc_premaster),3046PACKET_remaining(&enc_premaster)) <= 0) {3047SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3048goto err;3049}30503051/*3052* This test should never fail (otherwise we should have failed above) but3053* we double check anyway.3054*/3055if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {3056OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);3057SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3058goto err;3059}30603061/* Also cleanses rsa_decrypt (on success or failure) */3062if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {3063/* SSLfatal() already called */3064goto err;3065}30663067ret = 1;3068err:3069OPENSSL_free(rsa_decrypt);3070EVP_PKEY_CTX_free(ctx);3071return ret;3072}30733074static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)3075{3076EVP_PKEY *skey = NULL;3077unsigned int i;3078const unsigned char *data;3079EVP_PKEY *ckey = NULL;3080int ret = 0;30813082if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {3083SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);3084goto err;3085}3086skey = s->s3.tmp.pkey;3087if (skey == NULL) {3088SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);3089goto err;3090}30913092if (PACKET_remaining(pkt) == 0L) {3093SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);3094goto err;3095}3096if (!PACKET_get_bytes(pkt, &data, i)) {3097/* We already checked we have enough data */3098SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3099goto err;3100}3101ckey = EVP_PKEY_new();3102if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {3103SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);3104goto err;3105}31063107if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {3108SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);3109goto err;3110}31113112if (ssl_derive(s, skey, ckey, 1) == 0) {3113/* SSLfatal() already called */3114goto err;3115}31163117ret = 1;3118EVP_PKEY_free(s->s3.tmp.pkey);3119s->s3.tmp.pkey = NULL;3120err:3121EVP_PKEY_free(ckey);3122return ret;3123}31243125static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)3126{3127EVP_PKEY *skey = s->s3.tmp.pkey;3128EVP_PKEY *ckey = NULL;3129int ret = 0;31303131if (PACKET_remaining(pkt) == 0L) {3132/* We don't support ECDH client auth */3133SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);3134goto err;3135} else {3136unsigned int i;3137const unsigned char *data;31383139/*3140* Get client's public key from encoded point in the3141* ClientKeyExchange message.3142*/31433144/* Get encoded point length */3145if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)3146|| PACKET_remaining(pkt) != 0) {3147SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3148goto err;3149}3150if (skey == NULL) {3151SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);3152goto err;3153}31543155ckey = EVP_PKEY_new();3156if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {3157SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);3158goto err;3159}31603161if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {3162SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);3163goto err;3164}3165}31663167if (ssl_derive(s, skey, ckey, 1) == 0) {3168/* SSLfatal() already called */3169goto err;3170}31713172ret = 1;3173EVP_PKEY_free(s->s3.tmp.pkey);3174s->s3.tmp.pkey = NULL;3175err:3176EVP_PKEY_free(ckey);31773178return ret;3179}31803181static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)3182{3183#ifndef OPENSSL_NO_SRP3184unsigned int i;3185const unsigned char *data;31863187if (!PACKET_get_net_2(pkt, &i)3188|| !PACKET_get_bytes(pkt, &data, i)) {3189SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);3190return 0;3191}3192if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {3193SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);3194return 0;3195}3196if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {3197SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);3198return 0;3199}3200OPENSSL_free(s->session->srp_username);3201s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);3202if (s->session->srp_username == NULL) {3203SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3204return 0;3205}32063207if (!srp_generate_server_master_secret(s)) {3208/* SSLfatal() already called */3209return 0;3210}32113212return 1;3213#else3214/* Should never happen */3215SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3216return 0;3217#endif3218}32193220static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)3221{3222#ifndef OPENSSL_NO_GOST3223EVP_PKEY_CTX *pkey_ctx;3224EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;3225unsigned char premaster_secret[32];3226const unsigned char *start;3227size_t outlen = sizeof(premaster_secret), inlen;3228unsigned long alg_a;3229GOST_KX_MESSAGE *pKX = NULL;3230const unsigned char *ptr;3231int ret = 0;3232SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);32333234/* Get our certificate private key */3235alg_a = s->s3.tmp.new_cipher->algorithm_auth;3236if (alg_a & SSL_aGOST12) {3237/*3238* New GOST ciphersuites have SSL_aGOST01 bit too3239*/3240pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;3241if (pk == NULL) {3242pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;3243}3244if (pk == NULL) {3245pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;3246}3247} else if (alg_a & SSL_aGOST01) {3248pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;3249}32503251pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);3252if (pkey_ctx == NULL) {3253SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3254return 0;3255}3256if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {3257SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3258goto err;3259}3260/*3261* If client certificate is present and is of the same type, maybe3262* use it for key exchange. Don't mind errors from3263* EVP_PKEY_derive_set_peer, because it is completely valid to use a3264* client certificate for authorization only.3265*/3266client_pub_pkey = tls_get_peer_pkey(s);3267if (client_pub_pkey) {3268if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)3269ERR_clear_error();3270}32713272ptr = PACKET_data(pkt);3273/* Some implementations provide extra data in the opaqueBlob3274* We have nothing to do with this blob so we just skip it */3275pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));3276if (pKX == NULL3277|| pKX->kxBlob == NULL3278|| ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {3279SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3280goto err;3281}32823283if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {3284SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);3285goto err;3286}32873288if (PACKET_remaining(pkt) != 0) {3289SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);3290goto err;3291}32923293inlen = pKX->kxBlob->value.sequence->length;3294start = pKX->kxBlob->value.sequence->data;32953296if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,3297inlen) <= 0) {3298SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3299goto err;3300}3301/* Generate master secret */3302if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {3303/* SSLfatal() already called */3304goto err;3305}3306/* Check if pubkey from client certificate was used */3307if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,3308NULL) > 0)3309s->statem.no_cert_verify = 1;33103311ret = 1;3312err:3313EVP_PKEY_CTX_free(pkey_ctx);3314GOST_KX_MESSAGE_free(pKX);3315return ret;3316#else3317/* Should never happen */3318SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3319return 0;3320#endif3321}33223323static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)3324{3325#ifndef OPENSSL_NO_GOST3326unsigned char rnd_dgst[32];3327EVP_PKEY_CTX *pkey_ctx = NULL;3328EVP_PKEY *pk = NULL;3329unsigned char premaster_secret[32];3330const unsigned char *start = NULL;3331size_t outlen = sizeof(premaster_secret), inlen = 0;3332int ret = 0;3333int cipher_nid = ossl_gost18_cke_cipher_nid(s);3334SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);33353336if (cipher_nid == NID_undef) {3337SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3338return 0;3339}33403341if (ossl_gost_ukm(s, rnd_dgst) <= 0) {3342SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3343goto err;3344}33453346/* Get our certificate private key */3347pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ?3348s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey :3349s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;3350if (pk == NULL) {3351SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);3352goto err;3353}33543355pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);3356if (pkey_ctx == NULL) {3357SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3358goto err;3359}3360if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {3361SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3362goto err;3363}33643365/* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */3366if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,3367EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) <= 0) {3368SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3369goto err;3370}33713372if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,3373EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) <= 0) {3374SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3375goto err;3376}3377inlen = PACKET_remaining(pkt);3378start = PACKET_data(pkt);33793380if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {3381SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3382goto err;3383}3384/* Generate master secret */3385if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {3386/* SSLfatal() already called */3387goto err;3388}3389ret = 1;33903391err:3392EVP_PKEY_CTX_free(pkey_ctx);3393return ret;3394#else3395/* Should never happen */3396SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3397return 0;3398#endif3399}34003401MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,3402PACKET *pkt)3403{3404unsigned long alg_k;34053406alg_k = s->s3.tmp.new_cipher->algorithm_mkey;34073408/* For PSK parse and retrieve identity, obtain PSK key */3409if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {3410/* SSLfatal() already called */3411goto err;3412}34133414if (alg_k & SSL_kPSK) {3415/* Identity extracted earlier: should be nothing left */3416if (PACKET_remaining(pkt) != 0) {3417SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3418goto err;3419}3420/* PSK handled by ssl_generate_master_secret */3421if (!ssl_generate_master_secret(s, NULL, 0, 0)) {3422/* SSLfatal() already called */3423goto err;3424}3425} else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {3426if (!tls_process_cke_rsa(s, pkt)) {3427/* SSLfatal() already called */3428goto err;3429}3430} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {3431if (!tls_process_cke_dhe(s, pkt)) {3432/* SSLfatal() already called */3433goto err;3434}3435} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {3436if (!tls_process_cke_ecdhe(s, pkt)) {3437/* SSLfatal() already called */3438goto err;3439}3440} else if (alg_k & SSL_kSRP) {3441if (!tls_process_cke_srp(s, pkt)) {3442/* SSLfatal() already called */3443goto err;3444}3445} else if (alg_k & SSL_kGOST) {3446if (!tls_process_cke_gost(s, pkt)) {3447/* SSLfatal() already called */3448goto err;3449}3450} else if (alg_k & SSL_kGOST18) {3451if (!tls_process_cke_gost18(s, pkt)) {3452/* SSLfatal() already called */3453goto err;3454}3455} else {3456SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);3457goto err;3458}34593460return MSG_PROCESS_CONTINUE_PROCESSING;3461err:3462#ifndef OPENSSL_NO_PSK3463OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);3464s->s3.tmp.psk = NULL;3465s->s3.tmp.psklen = 0;3466#endif3467return MSG_PROCESS_ERROR;3468}34693470WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,3471WORK_STATE wst)3472{3473#ifndef OPENSSL_NO_SCTP3474if (wst == WORK_MORE_A) {3475if (SSL_CONNECTION_IS_DTLS(s)) {3476unsigned char sctpauthkey[64];3477char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];3478size_t labellen;3479/*3480* Add new shared key for SCTP-Auth, will be ignored if no SCTP3481* used.3482*/3483memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,3484sizeof(DTLS1_SCTP_AUTH_LABEL));34853486/* Don't include the terminating zero. */3487labellen = sizeof(labelbuffer) - 1;3488if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)3489labellen += 1;34903491if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),3492sctpauthkey,3493sizeof(sctpauthkey), labelbuffer,3494labellen, NULL, 0,34950) <= 0) {3496SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3497return WORK_ERROR;3498}34993500BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,3501sizeof(sctpauthkey), sctpauthkey);3502}3503}3504#endif35053506if (s->statem.no_cert_verify || !received_client_cert(s)) {3507/*3508* No certificate verify or no peer certificate so we no longer need3509* the handshake_buffer3510*/3511if (!ssl3_digest_cached_records(s, 0)) {3512/* SSLfatal() already called */3513return WORK_ERROR;3514}3515return WORK_FINISHED_CONTINUE;3516} else {3517if (!s->s3.handshake_buffer) {3518SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3519return WORK_ERROR;3520}3521/*3522* For sigalgs freeze the handshake buffer. If we support3523* extms we've done this already so this is a no-op3524*/3525if (!ssl3_digest_cached_records(s, 1)) {3526/* SSLfatal() already called */3527return WORK_ERROR;3528}3529}35303531return WORK_FINISHED_CONTINUE;3532}35333534MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)3535{3536MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3537SSL_SESSION *new_sess = NULL;3538EVP_PKEY *peer_rpk = NULL;35393540if (!tls_process_rpk(sc, pkt, &peer_rpk)) {3541/* SSLfatal already called */3542goto err;3543}35443545if (peer_rpk == NULL) {3546if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)3547&& (sc->verify_mode & SSL_VERIFY_PEER)) {3548SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,3549SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);3550goto err;3551}3552} else {3553if (ssl_verify_rpk(sc, peer_rpk) <= 0) {3554SSLfatal(sc, ssl_x509err2alert(sc->verify_result),3555SSL_R_CERTIFICATE_VERIFY_FAILED);3556goto err;3557}3558}35593560/*3561* Sessions must be immutable once they go into the session cache. Otherwise3562* we can get multi-thread problems. Therefore we don't "update" sessions,3563* we replace them with a duplicate. Here, we need to do this every time3564* a new RPK (or certificate) is received via post-handshake authentication,3565* as the session may have already gone into the session cache.3566*/35673568if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {3569if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {3570SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);3571goto err;3572}35733574SSL_SESSION_free(sc->session);3575sc->session = new_sess;3576}35773578/* Ensure there is no peer/peer_chain */3579X509_free(sc->session->peer);3580sc->session->peer = NULL;3581sk_X509_pop_free(sc->session->peer_chain, X509_free);3582sc->session->peer_chain = NULL;3583/* Save RPK */3584EVP_PKEY_free(sc->session->peer_rpk);3585sc->session->peer_rpk = peer_rpk;3586peer_rpk = NULL;35873588sc->session->verify_result = sc->verify_result;35893590/*3591* Freeze the handshake buffer. For <TLS1.3 we do this after the CKE3592* message3593*/3594if (SSL_CONNECTION_IS_TLS13(sc)) {3595if (!ssl3_digest_cached_records(sc, 1)) {3596/* SSLfatal() already called */3597goto err;3598}35993600/* Save the current hash state for when we receive the CertificateVerify */3601if (!ssl_handshake_hash(sc, sc->cert_verify_hash,3602sizeof(sc->cert_verify_hash),3603&sc->cert_verify_hash_len)) {3604/* SSLfatal() already called */;3605goto err;3606}36073608/* resend session tickets */3609sc->sent_tickets = 0;3610}36113612ret = MSG_PROCESS_CONTINUE_READING;36133614err:3615EVP_PKEY_free(peer_rpk);3616return ret;3617}36183619MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,3620PACKET *pkt)3621{3622int i;3623MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3624X509 *x = NULL;3625unsigned long l;3626const unsigned char *certstart, *certbytes;3627STACK_OF(X509) *sk = NULL;3628PACKET spkt, context;3629size_t chainidx;3630SSL_SESSION *new_sess = NULL;3631SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);36323633/*3634* To get this far we must have read encrypted data from the client. We no3635* longer tolerate unencrypted alerts. This is ignored if less than TLSv1.33636*/3637if (s->rlayer.rrlmethod->set_plain_alerts != NULL)3638s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);36393640if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)3641return tls_process_client_rpk(s, pkt);36423643if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {3644SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,3645SSL_R_UNKNOWN_CERTIFICATE_TYPE);3646goto err;3647}36483649if ((sk = sk_X509_new_null()) == NULL) {3650SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3651goto err;3652}36533654if (SSL_CONNECTION_IS_TLS13(s)3655&& (!PACKET_get_length_prefixed_1(pkt, &context)3656|| (s->pha_context == NULL && PACKET_remaining(&context) != 0)3657|| (s->pha_context != NULL3658&& !PACKET_equal(&context, s->pha_context,3659s->pha_context_len)))) {3660SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);3661goto err;3662}36633664if (!PACKET_get_length_prefixed_3(pkt, &spkt)3665|| PACKET_remaining(pkt) != 0) {3666SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3667goto err;3668}36693670for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {3671if (!PACKET_get_net_3(&spkt, &l)3672|| !PACKET_get_bytes(&spkt, &certbytes, l)) {3673SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);3674goto err;3675}36763677certstart = certbytes;3678x = X509_new_ex(sctx->libctx, sctx->propq);3679if (x == NULL) {3680SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);3681goto err;3682}3683if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {3684SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);3685goto err;3686}36873688if (certbytes != (certstart + l)) {3689SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);3690goto err;3691}36923693if (SSL_CONNECTION_IS_TLS13(s)) {3694RAW_EXTENSION *rawexts = NULL;3695PACKET extensions;36963697if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {3698SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);3699goto err;3700}3701if (!tls_collect_extensions(s, &extensions,3702SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,3703NULL, chainidx == 0)3704|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,3705rawexts, x, chainidx,3706PACKET_remaining(&spkt) == 0)) {3707OPENSSL_free(rawexts);3708goto err;3709}3710OPENSSL_free(rawexts);3711}37123713if (!sk_X509_push(sk, x)) {3714SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3715goto err;3716}3717x = NULL;3718}37193720if (sk_X509_num(sk) <= 0) {3721/* TLS does not mind 0 certs returned */3722if (s->version == SSL3_VERSION) {3723SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3724SSL_R_NO_CERTIFICATES_RETURNED);3725goto err;3726}3727/* Fail for TLS only if we required a certificate */3728else if ((s->verify_mode & SSL_VERIFY_PEER) &&3729(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {3730SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,3731SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);3732goto err;3733}3734/* No client certificate so digest cached records */3735if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {3736/* SSLfatal() already called */3737goto err;3738}3739} else {3740EVP_PKEY *pkey;3741i = ssl_verify_cert_chain(s, sk);3742if (i <= 0) {3743SSLfatal(s, ssl_x509err2alert(s->verify_result),3744SSL_R_CERTIFICATE_VERIFY_FAILED);3745goto err;3746}3747pkey = X509_get0_pubkey(sk_X509_value(sk, 0));3748if (pkey == NULL) {3749SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3750SSL_R_UNKNOWN_CERTIFICATE_TYPE);3751goto err;3752}3753}37543755/*3756* Sessions must be immutable once they go into the session cache. Otherwise3757* we can get multi-thread problems. Therefore we don't "update" sessions,3758* we replace them with a duplicate. Here, we need to do this every time3759* a new certificate is received via post-handshake authentication, as the3760* session may have already gone into the session cache.3761*/37623763if (s->post_handshake_auth == SSL_PHA_REQUESTED) {3764if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {3765SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);3766goto err;3767}37683769SSL_SESSION_free(s->session);3770s->session = new_sess;3771}37723773X509_free(s->session->peer);3774s->session->peer = sk_X509_shift(sk);3775s->session->verify_result = s->verify_result;37763777OSSL_STACK_OF_X509_free(s->session->peer_chain);3778s->session->peer_chain = sk;3779sk = NULL;3780/* Ensure there is no RPK */3781EVP_PKEY_free(s->session->peer_rpk);3782s->session->peer_rpk = NULL;37833784/*3785* Freeze the handshake buffer. For <TLS1.3 we do this after the CKE3786* message3787*/3788if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {3789/* SSLfatal() already called */3790goto err;3791}37923793/*3794* Inconsistency alert: cert_chain does *not* include the peer's own3795* certificate, while we do include it in statem_clnt.c3796*/37973798/* Save the current hash state for when we receive the CertificateVerify */3799if (SSL_CONNECTION_IS_TLS13(s)) {3800if (!ssl_handshake_hash(s, s->cert_verify_hash,3801sizeof(s->cert_verify_hash),3802&s->cert_verify_hash_len)) {3803/* SSLfatal() already called */3804goto err;3805}38063807/* Resend session tickets */3808s->sent_tickets = 0;3809}38103811ret = MSG_PROCESS_CONTINUE_READING;38123813err:3814X509_free(x);3815OSSL_STACK_OF_X509_free(sk);3816return ret;3817}38183819#ifndef OPENSSL_NO_COMP_ALG3820MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)3821{3822MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3823PACKET tmppkt;3824BUF_MEM *buf = BUF_MEM_new();38253826if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)3827ret = tls_process_client_certificate(sc, &tmppkt);38283829BUF_MEM_free(buf);3830return ret;3831}3832#endif38333834CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)3835{3836CERT_PKEY *cpk = s->s3.tmp.cert;38373838if (cpk == NULL) {3839SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3840return CON_FUNC_ERROR;3841}38423843/*3844* In TLSv1.3 the certificate chain is always preceded by a 0 length context3845* for the server Certificate message3846*/3847if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {3848SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3849return CON_FUNC_ERROR;3850}3851switch (s->ext.server_cert_type) {3852case TLSEXT_cert_type_rpk:3853if (!tls_output_rpk(s, pkt, cpk)) {3854/* SSLfatal() already called */3855return 0;3856}3857break;3858case TLSEXT_cert_type_x509:3859if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {3860/* SSLfatal() already called */3861return 0;3862}3863break;3864default:3865SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3866return 0;3867}38683869return CON_FUNC_SUCCESS;3870}38713872#ifndef OPENSSL_NO_COMP_ALG3873CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)3874{3875int alg = get_compressed_certificate_alg(sc);3876OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];38773878if (!ossl_assert(cc != NULL)) {3879SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3880return 0;3881}3882/*3883* Server can't compress on-demand3884* Use pre-compressed certificate3885*/3886if (!WPACKET_put_bytes_u16(pkt, alg)3887|| !WPACKET_put_bytes_u24(pkt, cc->orig_len)3888|| !WPACKET_start_sub_packet_u24(pkt)3889|| !WPACKET_memcpy(pkt, cc->data, cc->len)3890|| !WPACKET_close(pkt))3891return 0;38923893sc->s3.tmp.cert->cert_comp_used++;3894return 1;3895}3896#endif38973898static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,3899uint32_t age_add, unsigned char *tick_nonce)3900{3901uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);39023903/*3904* Ticket lifetime hint:3905* In TLSv1.3 we reset the "time" field above, and always specify the3906* timeout, limited to a 1 week period per RFC8446.3907* For TLSv1.2 this is advisory only and we leave this unspecified for3908* resumed session (for simplicity).3909*/3910#define ONE_WEEK_SEC (7 * 24 * 60 * 60)39113912if (SSL_CONNECTION_IS_TLS13(s)) {3913if (ossl_time_compare(s->session->timeout,3914ossl_seconds2time(ONE_WEEK_SEC)) > 0)3915timeout = ONE_WEEK_SEC;3916} else if (s->hit)3917timeout = 0;39183919if (!WPACKET_put_bytes_u32(pkt, timeout)) {3920SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3921return 0;3922}39233924if (SSL_CONNECTION_IS_TLS13(s)) {3925if (!WPACKET_put_bytes_u32(pkt, age_add)3926|| !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {3927SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3928return 0;3929}3930}39313932/* Start the sub-packet for the actual ticket data */3933if (!WPACKET_start_sub_packet_u16(pkt)) {3934SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3935return 0;3936}39373938return 1;3939}39403941static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,3942WPACKET *pkt,3943uint32_t age_add,3944unsigned char *tick_nonce)3945{3946unsigned char *senc = NULL;3947EVP_CIPHER_CTX *ctx = NULL;3948SSL_HMAC *hctx = NULL;3949unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;3950const unsigned char *const_p;3951int len, slen_full, slen, lenfinal;3952SSL_SESSION *sess;3953size_t hlen;3954SSL_CTX *tctx = s->session_ctx;3955unsigned char iv[EVP_MAX_IV_LENGTH];3956unsigned char key_name[TLSEXT_KEYNAME_LENGTH];3957int iv_len;3958CON_FUNC_RETURN ok = CON_FUNC_ERROR;3959size_t macoffset, macendoffset;3960SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);3961SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);39623963/* get session encoding length */3964slen_full = i2d_SSL_SESSION(s->session, NULL);3965/*3966* Some length values are 16 bits, so forget it if session is too3967* long3968*/3969if (slen_full == 0 || slen_full > 0xFF00) {3970SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3971goto err;3972}3973senc = OPENSSL_malloc(slen_full);3974if (senc == NULL) {3975SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3976goto err;3977}39783979ctx = EVP_CIPHER_CTX_new();3980if (ctx == NULL) {3981SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3982goto err;3983}3984hctx = ssl_hmac_new(tctx);3985if (hctx == NULL) {3986SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);3987goto err;3988}39893990p = senc;3991if (!i2d_SSL_SESSION(s->session, &p)) {3992SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3993goto err;3994}39953996/*3997* create a fresh copy (not shared with other threads) to clean up3998*/3999const_p = senc;4000sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,4001sctx->propq);4002if (sess == NULL) {4003SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4004goto err;4005}40064007slen = i2d_SSL_SESSION(sess, NULL);4008if (slen == 0 || slen > slen_full) {4009/* shouldn't ever happen */4010SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4011SSL_SESSION_free(sess);4012goto err;4013}4014p = senc;4015if (!i2d_SSL_SESSION(sess, &p)) {4016SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4017SSL_SESSION_free(sess);4018goto err;4019}4020SSL_SESSION_free(sess);40214022/*4023* Initialize HMAC and cipher contexts. If callback present it does4024* all the work otherwise use generated values from parent ctx.4025*/4026#ifndef OPENSSL_NO_DEPRECATED_3_04027if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)4028#else4029if (tctx->ext.ticket_key_evp_cb != NULL)4030#endif4031{4032int ret = 0;40334034if (tctx->ext.ticket_key_evp_cb != NULL)4035ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,4036ssl_hmac_get0_EVP_MAC_CTX(hctx),40371);4038#ifndef OPENSSL_NO_DEPRECATED_3_04039else if (tctx->ext.ticket_key_cb != NULL)4040/* if 0 is returned, write an empty ticket */4041ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,4042ssl_hmac_get0_HMAC_CTX(hctx), 1);4043#endif40444045if (ret == 0) {4046/*4047* In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 04048* length ticket is not allowed so we abort construction of the4049* ticket4050*/4051if (SSL_CONNECTION_IS_TLS13(s)) {4052ok = CON_FUNC_DONT_SEND;4053goto err;4054}4055/* Put timeout and length */4056if (!WPACKET_put_bytes_u32(pkt, 0)4057|| !WPACKET_put_bytes_u16(pkt, 0)) {4058SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4059goto err;4060}4061OPENSSL_free(senc);4062EVP_CIPHER_CTX_free(ctx);4063ssl_hmac_free(hctx);4064return CON_FUNC_SUCCESS;4065}4066if (ret < 0) {4067SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);4068goto err;4069}4070iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);4071if (iv_len < 0) {4072SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4073goto err;4074}4075} else {4076EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",4077sctx->propq);40784079if (cipher == NULL) {4080/* Error is already recorded */4081SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);4082goto err;4083}40844085iv_len = EVP_CIPHER_get_iv_length(cipher);4086if (iv_len < 04087|| RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 04088|| !EVP_EncryptInit_ex(ctx, cipher, NULL,4089tctx->ext.secure->tick_aes_key, iv)4090|| !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,4091sizeof(tctx->ext.secure->tick_hmac_key),4092"SHA256")) {4093EVP_CIPHER_free(cipher);4094SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4095goto err;4096}4097EVP_CIPHER_free(cipher);4098memcpy(key_name, tctx->ext.tick_key_name,4099sizeof(tctx->ext.tick_key_name));4100}41014102if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {4103/* SSLfatal() already called */4104goto err;4105}41064107if (!WPACKET_get_total_written(pkt, &macoffset)4108/* Output key name */4109|| !WPACKET_memcpy(pkt, key_name, sizeof(key_name))4110/* output IV */4111|| !WPACKET_memcpy(pkt, iv, iv_len)4112|| !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,4113&encdata1)4114/* Encrypt session data */4115|| !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)4116|| !WPACKET_allocate_bytes(pkt, len, &encdata2)4117|| encdata1 != encdata24118|| !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)4119|| !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)4120|| encdata1 + len != encdata24121|| len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH4122|| !WPACKET_get_total_written(pkt, &macendoffset)4123|| !ssl_hmac_update(hctx,4124(unsigned char *)s->init_buf->data + macoffset,4125macendoffset - macoffset)4126|| !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)4127|| !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)4128|| hlen > EVP_MAX_MD_SIZE4129|| !WPACKET_allocate_bytes(pkt, hlen, &macdata2)4130|| macdata1 != macdata2) {4131SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4132goto err;4133}41344135/* Close the sub-packet created by create_ticket_prequel() */4136if (!WPACKET_close(pkt)) {4137SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4138goto err;4139}41404141ok = CON_FUNC_SUCCESS;4142err:4143OPENSSL_free(senc);4144EVP_CIPHER_CTX_free(ctx);4145ssl_hmac_free(hctx);4146return ok;4147}41484149static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,4150uint32_t age_add,4151unsigned char *tick_nonce)4152{4153if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {4154/* SSLfatal() already called */4155return 0;4156}41574158if (!WPACKET_memcpy(pkt, s->session->session_id,4159s->session->session_id_length)4160|| !WPACKET_close(pkt)) {4161SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4162return 0;4163}41644165return 1;4166}41674168static void tls_update_ticket_counts(SSL_CONNECTION *s)4169{4170/*4171* Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|4172* gets reset to 0 if we send more tickets following a post-handshake4173* auth, but |next_ticket_nonce| does not. If we're sending extra4174* tickets, decrement the count of pending extra tickets.4175*/4176s->sent_tickets++;4177s->next_ticket_nonce++;4178if (s->ext.extra_tickets_expected > 0)4179s->ext.extra_tickets_expected--;4180}41814182CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)4183{4184SSL_CTX *tctx = s->session_ctx;4185unsigned char tick_nonce[TICKET_NONCE_SIZE];4186union {4187unsigned char age_add_c[sizeof(uint32_t)];4188uint32_t age_add;4189} age_add_u;4190CON_FUNC_RETURN ret = CON_FUNC_ERROR;41914192age_add_u.age_add = 0;41934194if (SSL_CONNECTION_IS_TLS13(s)) {4195size_t i, hashlen;4196uint64_t nonce;4197static const unsigned char nonce_label[] = "resumption";4198const EVP_MD *md = ssl_handshake_md(s);4199int hashleni = EVP_MD_get_size(md);42004201/* Ensure cast to size_t is safe */4202if (!ossl_assert(hashleni > 0)) {4203SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4204goto err;4205}4206hashlen = (size_t)hashleni;42074208/*4209* If we already sent one NewSessionTicket, or we resumed then4210* s->session may already be in a cache and so we must not modify it.4211* Instead we need to take a copy of it and modify that.4212*/4213if (s->sent_tickets != 0 || s->hit) {4214SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);42154216if (new_sess == NULL) {4217/* SSLfatal already called */4218goto err;4219}42204221SSL_SESSION_free(s->session);4222s->session = new_sess;4223}42244225if (!ssl_generate_session_id(s, s->session)) {4226/* SSLfatal() already called */4227goto err;4228}4229if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,4230age_add_u.age_add_c, sizeof(age_add_u), 0) <= 0) {4231SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4232goto err;4233}4234s->session->ext.tick_age_add = age_add_u.age_add;42354236nonce = s->next_ticket_nonce;4237for (i = TICKET_NONCE_SIZE; i > 0; i--) {4238tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);4239nonce >>= 8;4240}42414242if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,4243nonce_label,4244sizeof(nonce_label) - 1,4245tick_nonce,4246TICKET_NONCE_SIZE,4247s->session->master_key,4248hashlen, 1)) {4249/* SSLfatal() already called */4250goto err;4251}4252s->session->master_key_length = hashlen;42534254s->session->time = ossl_time_now();4255ssl_session_calculate_timeout(s->session);4256if (s->s3.alpn_selected != NULL) {4257OPENSSL_free(s->session->ext.alpn_selected);4258s->session->ext.alpn_selected =4259OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);4260if (s->session->ext.alpn_selected == NULL) {4261s->session->ext.alpn_selected_len = 0;4262SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);4263goto err;4264}4265s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;4266}4267s->session->ext.max_early_data = s->max_early_data;4268}42694270if (tctx->generate_ticket_cb != NULL &&4271tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s),4272tctx->ticket_cb_data) == 0) {4273SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4274goto err;4275}4276/*4277* If we are using anti-replay protection then we behave as if4278* SSL_OP_NO_TICKET is set - we are caching tickets anyway so there4279* is no point in using full stateless tickets.4280*/4281if (SSL_CONNECTION_IS_TLS13(s)4282&& ((s->options & SSL_OP_NO_TICKET) != 04283|| (s->max_early_data > 04284&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {4285if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {4286/* SSLfatal() already called */4287goto err;4288}4289} else {4290CON_FUNC_RETURN tmpret;42914292tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,4293tick_nonce);4294if (tmpret != CON_FUNC_SUCCESS) {4295if (tmpret == CON_FUNC_DONT_SEND) {4296/* Non-fatal. Abort construction but continue */4297ret = CON_FUNC_DONT_SEND;4298/* We count this as a success so update the counts anwyay */4299tls_update_ticket_counts(s);4300}4301/* else SSLfatal() already called */4302goto err;4303}4304}43054306if (SSL_CONNECTION_IS_TLS13(s)) {4307if (!tls_construct_extensions(s, pkt,4308SSL_EXT_TLS1_3_NEW_SESSION_TICKET,4309NULL, 0)) {4310/* SSLfatal() already called */4311goto err;4312}4313tls_update_ticket_counts(s);4314ssl_update_cache(s, SSL_SESS_CACHE_SERVER);4315}43164317ret = CON_FUNC_SUCCESS;4318err:4319return ret;4320}43214322/*4323* In TLSv1.3 this is called from the extensions code, otherwise it is used to4324* create a separate message. Returns 1 on success or 0 on failure.4325*/4326int tls_construct_cert_status_body(SSL_CONNECTION *s, WPACKET *pkt)4327{4328if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)4329|| !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,4330s->ext.ocsp.resp_len)) {4331SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4332return 0;4333}43344335return 1;4336}43374338CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)4339{4340if (!tls_construct_cert_status_body(s, pkt)) {4341/* SSLfatal() already called */4342return CON_FUNC_ERROR;4343}43444345return CON_FUNC_SUCCESS;4346}43474348#ifndef OPENSSL_NO_NEXTPROTONEG4349/*4350* tls_process_next_proto reads a Next Protocol Negotiation handshake message.4351* It sets the next_proto member in s if found4352*/4353MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)4354{4355PACKET next_proto, padding;4356size_t next_proto_len;43574358/*-4359* The payload looks like:4360* uint8 proto_len;4361* uint8 proto[proto_len];4362* uint8 padding_len;4363* uint8 padding[padding_len];4364*/4365if (!PACKET_get_length_prefixed_1(pkt, &next_proto)4366|| !PACKET_get_length_prefixed_1(pkt, &padding)4367|| PACKET_remaining(pkt) > 0) {4368SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4369return MSG_PROCESS_ERROR;4370}43714372if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {4373s->ext.npn_len = 0;4374SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4375return MSG_PROCESS_ERROR;4376}43774378s->ext.npn_len = (unsigned char)next_proto_len;43794380return MSG_PROCESS_CONTINUE_READING;4381}4382#endif43834384static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,4385WPACKET *pkt)4386{4387if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,4388NULL, 0)) {4389/* SSLfatal() already called */4390return CON_FUNC_ERROR;4391}43924393return CON_FUNC_SUCCESS;4394}43954396MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)4397{4398if (PACKET_remaining(pkt) != 0) {4399SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4400return MSG_PROCESS_ERROR;4401}44024403if (s->early_data_state != SSL_EARLY_DATA_READING4404&& s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {4405SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4406return MSG_PROCESS_ERROR;4407}44084409/*4410* EndOfEarlyData signals a key change so the end of the message must be on4411* a record boundary.4412*/4413if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {4414SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);4415return MSG_PROCESS_ERROR;4416}44174418s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;4419if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,4420SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {4421/* SSLfatal() already called */4422return MSG_PROCESS_ERROR;4423}44244425return MSG_PROCESS_CONTINUE_READING;4426}442744284429