Path: blob/main/crypto/openssl/ssl/statem/statem_srvr.c
105379 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 || !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))430/*431* never request cert in anonymous ciphersuites (see432* section "Certificate request" in SSL 3 drafts and in433* RFC 2246):434*/435&& (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)436/*437* ... except when the application insists on438* verification (against the specs, but statem_clnt.c accepts439* this for SSL 3)440*/441|| (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))442/* don't request certificate for SRP auth */443&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)444/*445* With normal PSK Certificates and Certificate Requests446* are omitted447*/448&& !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {449return 1;450}451452return 0;453}454455static int do_compressed_cert(SSL_CONNECTION *sc)456{457/* If we negotiated RPK, we won't attempt to compress it */458return sc->ext.server_cert_type == TLSEXT_cert_type_x509459&& get_compressed_certificate_alg(sc) != TLSEXT_comp_cert_none;460}461462/*463* ossl_statem_server13_write_transition() works out what handshake state to464* move to next when a TLSv1.3 server is writing messages to be sent to the465* client.466*/467static WRITE_TRAN ossl_statem_server13_write_transition(SSL_CONNECTION *s)468{469OSSL_STATEM *st = &s->statem;470471/*472* No case for TLS_ST_BEFORE, because at that stage we have not negotiated473* TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()474*/475476switch (st->hand_state) {477default:478/* Shouldn't happen */479SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);480return WRITE_TRAN_ERROR;481482case TLS_ST_OK:483if (s->key_update != SSL_KEY_UPDATE_NONE) {484st->hand_state = TLS_ST_SW_KEY_UPDATE;485return WRITE_TRAN_CONTINUE;486}487if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {488st->hand_state = TLS_ST_SW_CERT_REQ;489return WRITE_TRAN_CONTINUE;490}491if (s->ext.extra_tickets_expected > 0) {492st->hand_state = TLS_ST_SW_SESSION_TICKET;493return WRITE_TRAN_CONTINUE;494}495/* Try to read from the client instead */496return WRITE_TRAN_FINISHED;497498case TLS_ST_SR_CLNT_HELLO:499st->hand_state = TLS_ST_SW_SRVR_HELLO;500return WRITE_TRAN_CONTINUE;501502case TLS_ST_SW_SRVR_HELLO:503if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0504&& s->hello_retry_request != SSL_HRR_COMPLETE)505st->hand_state = TLS_ST_SW_CHANGE;506else if (s->hello_retry_request == SSL_HRR_PENDING)507st->hand_state = TLS_ST_EARLY_DATA;508else509st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;510return WRITE_TRAN_CONTINUE;511512case TLS_ST_SW_CHANGE:513if (s->hello_retry_request == SSL_HRR_PENDING)514st->hand_state = TLS_ST_EARLY_DATA;515else516st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;517return WRITE_TRAN_CONTINUE;518519case TLS_ST_SW_ENCRYPTED_EXTENSIONS:520if (s->hit)521st->hand_state = TLS_ST_SW_FINISHED;522else if (send_certificate_request(s))523st->hand_state = TLS_ST_SW_CERT_REQ;524else if (do_compressed_cert(s))525st->hand_state = TLS_ST_SW_COMP_CERT;526else527st->hand_state = TLS_ST_SW_CERT;528529return WRITE_TRAN_CONTINUE;530531case TLS_ST_SW_CERT_REQ:532if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {533s->post_handshake_auth = SSL_PHA_REQUESTED;534st->hand_state = TLS_ST_OK;535} else if (do_compressed_cert(s)) {536st->hand_state = TLS_ST_SW_COMP_CERT;537} else {538st->hand_state = TLS_ST_SW_CERT;539}540return WRITE_TRAN_CONTINUE;541542case TLS_ST_SW_COMP_CERT:543case TLS_ST_SW_CERT:544st->hand_state = TLS_ST_SW_CERT_VRFY;545return WRITE_TRAN_CONTINUE;546547case TLS_ST_SW_CERT_VRFY:548st->hand_state = TLS_ST_SW_FINISHED;549return WRITE_TRAN_CONTINUE;550551case TLS_ST_SW_FINISHED:552st->hand_state = TLS_ST_EARLY_DATA;553s->ts_msg_write = ossl_time_now();554return WRITE_TRAN_CONTINUE;555556case TLS_ST_EARLY_DATA:557return WRITE_TRAN_FINISHED;558559case TLS_ST_SR_FINISHED:560s->ts_msg_read = ossl_time_now();561/*562* Technically we have finished the handshake at this point, but we're563* going to remain "in_init" for now and write out any session tickets564* immediately.565*/566if (s->post_handshake_auth == SSL_PHA_REQUESTED) {567s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;568} else if (!s->ext.ticket_expected) {569/*570* If we're not going to renew the ticket then we just finish the571* handshake at this point.572*/573st->hand_state = TLS_ST_OK;574return WRITE_TRAN_CONTINUE;575}576if (s->num_tickets > s->sent_tickets)577st->hand_state = TLS_ST_SW_SESSION_TICKET;578else579st->hand_state = TLS_ST_OK;580return WRITE_TRAN_CONTINUE;581582case TLS_ST_SR_KEY_UPDATE:583case TLS_ST_SW_KEY_UPDATE:584st->hand_state = TLS_ST_OK;585return WRITE_TRAN_CONTINUE;586587case TLS_ST_SW_SESSION_TICKET:588/* In a resumption we only ever send a maximum of one new ticket.589* Following an initial handshake we send the number of tickets we have590* been configured for.591*/592if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {593return WRITE_TRAN_CONTINUE;594} else if (s->hit || s->num_tickets <= s->sent_tickets) {595/* We've written enough tickets out. */596st->hand_state = TLS_ST_OK;597}598return WRITE_TRAN_CONTINUE;599}600}601602/*603* ossl_statem_server_write_transition() works out what handshake state to move604* to next when the server is writing messages to be sent to the client.605*/606WRITE_TRAN ossl_statem_server_write_transition(SSL_CONNECTION *s)607{608OSSL_STATEM *st = &s->statem;609610/*611* Note that before the ClientHello we don't know what version we are going612* to negotiate yet, so we don't take this branch until later613*/614615if (SSL_CONNECTION_IS_TLS13(s))616return ossl_statem_server13_write_transition(s);617618switch (st->hand_state) {619default:620/* Shouldn't happen */621SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);622return WRITE_TRAN_ERROR;623624case TLS_ST_OK:625if (st->request_state == TLS_ST_SW_HELLO_REQ) {626/* We must be trying to renegotiate */627st->hand_state = TLS_ST_SW_HELLO_REQ;628st->request_state = TLS_ST_BEFORE;629return WRITE_TRAN_CONTINUE;630}631/* Must be an incoming ClientHello */632if (!tls_setup_handshake(s)) {633/* SSLfatal() already called */634return WRITE_TRAN_ERROR;635}636/* Fall through */637638case TLS_ST_BEFORE:639/* Just go straight to trying to read from the client */640return WRITE_TRAN_FINISHED;641642case TLS_ST_SW_HELLO_REQ:643st->hand_state = TLS_ST_OK;644return WRITE_TRAN_CONTINUE;645646case TLS_ST_SR_CLNT_HELLO:647if (SSL_CONNECTION_IS_DTLS(s) && !s->d1->cookie_verified648&& (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE)) {649st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;650} else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {651/* We must have rejected the renegotiation */652st->hand_state = TLS_ST_OK;653return WRITE_TRAN_CONTINUE;654} else {655st->hand_state = TLS_ST_SW_SRVR_HELLO;656}657return WRITE_TRAN_CONTINUE;658659case DTLS_ST_SW_HELLO_VERIFY_REQUEST:660return WRITE_TRAN_FINISHED;661662case TLS_ST_SW_SRVR_HELLO:663if (s->hit) {664if (s->ext.ticket_expected)665st->hand_state = TLS_ST_SW_SESSION_TICKET;666else667st->hand_state = TLS_ST_SW_CHANGE;668} else {669/* Check if it is anon DH or anon ECDH, */670/* normal PSK or SRP */671if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {672st->hand_state = TLS_ST_SW_CERT;673} else if (send_server_key_exchange(s)) {674st->hand_state = TLS_ST_SW_KEY_EXCH;675} else if (send_certificate_request(s)) {676st->hand_state = TLS_ST_SW_CERT_REQ;677} else {678st->hand_state = TLS_ST_SW_SRVR_DONE;679}680}681return WRITE_TRAN_CONTINUE;682683case TLS_ST_SW_CERT:684if (s->ext.status_expected) {685st->hand_state = TLS_ST_SW_CERT_STATUS;686return WRITE_TRAN_CONTINUE;687}688/* Fall through */689690case TLS_ST_SW_CERT_STATUS:691if (send_server_key_exchange(s)) {692st->hand_state = TLS_ST_SW_KEY_EXCH;693return WRITE_TRAN_CONTINUE;694}695/* Fall through */696697case TLS_ST_SW_KEY_EXCH:698if (send_certificate_request(s)) {699st->hand_state = TLS_ST_SW_CERT_REQ;700return WRITE_TRAN_CONTINUE;701}702/* Fall through */703704case TLS_ST_SW_CERT_REQ:705st->hand_state = TLS_ST_SW_SRVR_DONE;706return WRITE_TRAN_CONTINUE;707708case TLS_ST_SW_SRVR_DONE:709s->ts_msg_write = ossl_time_now();710return WRITE_TRAN_FINISHED;711712case TLS_ST_SR_FINISHED:713s->ts_msg_read = ossl_time_now();714if (s->hit) {715st->hand_state = TLS_ST_OK;716return WRITE_TRAN_CONTINUE;717} else if (s->ext.ticket_expected) {718st->hand_state = TLS_ST_SW_SESSION_TICKET;719} else {720st->hand_state = TLS_ST_SW_CHANGE;721}722return WRITE_TRAN_CONTINUE;723724case TLS_ST_SW_SESSION_TICKET:725st->hand_state = TLS_ST_SW_CHANGE;726return WRITE_TRAN_CONTINUE;727728case TLS_ST_SW_CHANGE:729st->hand_state = TLS_ST_SW_FINISHED;730return WRITE_TRAN_CONTINUE;731732case TLS_ST_SW_FINISHED:733if (s->hit) {734return WRITE_TRAN_FINISHED;735}736st->hand_state = TLS_ST_OK;737return WRITE_TRAN_CONTINUE;738}739}740741/*742* Perform any pre work that needs to be done prior to sending a message from743* the server to the client.744*/745WORK_STATE ossl_statem_server_pre_work(SSL_CONNECTION *s, WORK_STATE wst)746{747OSSL_STATEM *st = &s->statem;748SSL *ssl = SSL_CONNECTION_GET_SSL(s);749750switch (st->hand_state) {751default:752/* No pre work to be done */753break;754755case TLS_ST_SW_HELLO_REQ:756s->shutdown = 0;757if (SSL_CONNECTION_IS_DTLS(s))758dtls1_clear_sent_buffer(s);759break;760761case DTLS_ST_SW_HELLO_VERIFY_REQUEST:762s->shutdown = 0;763if (SSL_CONNECTION_IS_DTLS(s)) {764dtls1_clear_sent_buffer(s);765/* We don't buffer this message so don't use the timer */766st->use_timer = 0;767}768break;769770case TLS_ST_SW_SRVR_HELLO:771if (SSL_CONNECTION_IS_DTLS(s)) {772/*773* Messages we write from now on should be buffered and774* retransmitted if necessary, so we need to use the timer now775*/776st->use_timer = 1;777}778break;779780case TLS_ST_SW_SRVR_DONE:781#ifndef OPENSSL_NO_SCTP782if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {783/* Calls SSLfatal() as required */784return dtls_wait_for_dry(s);785}786#endif787return WORK_FINISHED_CONTINUE;788789case TLS_ST_SW_SESSION_TICKET:790if (SSL_CONNECTION_IS_TLS13(s) && s->sent_tickets == 0791&& s->ext.extra_tickets_expected == 0) {792/*793* Actually this is the end of the handshake, but we're going794* straight into writing the session ticket out. So we finish off795* the handshake, but keep the various buffers active.796*797* Calls SSLfatal as required.798*/799return tls_finish_handshake(s, wst, 0, 0);800}801if (SSL_CONNECTION_IS_DTLS(s)) {802/*803* We're into the last flight. We don't retransmit the last flight804* unless we need to, so we don't use the timer805*/806st->use_timer = 0;807}808break;809810case TLS_ST_SW_CHANGE:811if (SSL_CONNECTION_IS_TLS13(s))812break;813/* Writes to s->session are only safe for initial handshakes */814if (s->session->cipher == NULL) {815s->session->cipher = s->s3.tmp.new_cipher;816} else if (s->session->cipher != s->s3.tmp.new_cipher) {817SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);818return WORK_ERROR;819}820if (!ssl->method->ssl3_enc->setup_key_block(s)) {821/* SSLfatal() already called */822return WORK_ERROR;823}824if (SSL_CONNECTION_IS_DTLS(s)) {825/*826* We're into the last flight. We don't retransmit the last flight827* unless we need to, so we don't use the timer. This might have828* already been set to 0 if we sent a NewSessionTicket message,829* but we'll set it again here in case we didn't.830*/831st->use_timer = 0;832}833return WORK_FINISHED_CONTINUE;834835case TLS_ST_EARLY_DATA:836if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING837&& (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)838return WORK_FINISHED_CONTINUE;839840/*841* In QUIC with 0-RTT we just carry on when otherwise we would stop842* to allow the server to read early data843*/844if (SSL_NO_EOED(s) && s->ext.early_data == SSL_EARLY_DATA_ACCEPTED845&& s->early_data_state != SSL_EARLY_DATA_FINISHED_READING) {846s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;847if (!ssl->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {848SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);849return WORK_ERROR;850}851return WORK_FINISHED_SWAP;852}853/* Fall through */854855case TLS_ST_OK:856/* Calls SSLfatal() as required */857return tls_finish_handshake(s, wst, 1, 1);858}859860return WORK_FINISHED_CONTINUE;861}862863static ossl_inline int conn_is_closed(void)864{865switch (get_last_sys_error()) {866#if defined(EPIPE)867case EPIPE:868return 1;869#endif870#if defined(ECONNRESET)871case ECONNRESET:872return 1;873#endif874#if defined(WSAECONNRESET)875case WSAECONNRESET:876return 1;877#endif878default:879return 0;880}881}882883/*884* Perform any work that needs to be done after sending a message from the885* server to the client.886*/887WORK_STATE ossl_statem_server_post_work(SSL_CONNECTION *s, WORK_STATE wst)888{889OSSL_STATEM *st = &s->statem;890SSL *ssl = SSL_CONNECTION_GET_SSL(s);891892s->init_num = 0;893894switch (st->hand_state) {895default:896/* No post work to be done */897break;898899case TLS_ST_SW_HELLO_REQ:900if (statem_flush(s) != 1)901return WORK_MORE_A;902if (!ssl3_init_finished_mac(s)) {903/* SSLfatal() already called */904return WORK_ERROR;905}906break;907908case DTLS_ST_SW_HELLO_VERIFY_REQUEST:909if (statem_flush(s) != 1)910return WORK_MORE_A;911/* HelloVerifyRequest resets Finished MAC */912if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {913/* SSLfatal() already called */914return WORK_ERROR;915}916/*917* The next message should be another ClientHello which we need to918* treat like it was the first packet919*/920s->first_packet = 1;921break;922923case TLS_ST_SW_SRVR_HELLO:924if (SSL_CONNECTION_IS_TLS13(s)925&& s->hello_retry_request == SSL_HRR_PENDING) {926if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0927&& statem_flush(s) != 1)928return WORK_MORE_A;929break;930}931#ifndef OPENSSL_NO_SCTP932if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {933unsigned char sctpauthkey[64];934char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];935size_t labellen;936937/*938* Add new shared key for SCTP-Auth, will be ignored if no939* SCTP used.940*/941memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,942sizeof(DTLS1_SCTP_AUTH_LABEL));943944/* Don't include the terminating zero. */945labellen = sizeof(labelbuffer) - 1;946if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)947labellen += 1;948949if (SSL_export_keying_material(ssl, sctpauthkey,950sizeof(sctpauthkey), labelbuffer,951labellen, NULL, 0,9520)953<= 0) {954SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);955return WORK_ERROR;956}957958BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,959sizeof(sctpauthkey), sctpauthkey);960}961#endif962if (!SSL_CONNECTION_IS_TLS13(s)963|| ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0964&& s->hello_retry_request != SSL_HRR_COMPLETE))965break;966/* Fall through */967968case TLS_ST_SW_CHANGE:969if (s->hello_retry_request == SSL_HRR_PENDING) {970if (!statem_flush(s))971return WORK_MORE_A;972break;973}974975if (SSL_CONNECTION_IS_TLS13(s)) {976if (!ssl->method->ssl3_enc->setup_key_block(s)977|| !tls13_store_handshake_traffic_hash(s)978|| !ssl->method->ssl3_enc->change_cipher_state(s,979SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {980/* SSLfatal() already called */981return WORK_ERROR;982}983984if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED985&& !ssl->method->ssl3_enc->change_cipher_state(s,986SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {987/* SSLfatal() already called */988return WORK_ERROR;989}990/*991* We don't yet know whether the next record we are going to receive992* is an unencrypted alert, an encrypted alert, or an encrypted993* handshake message. We temporarily tolerate unencrypted alerts.994*/995if (s->rlayer.rrlmethod->set_plain_alerts != NULL)996s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);997break;998}9991000#ifndef OPENSSL_NO_SCTP1001if (SSL_CONNECTION_IS_DTLS(s) && !s->hit) {1002/*1003* Change to new shared key of SCTP-Auth, will be ignored if1004* no SCTP used.1005*/1006BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,10070, NULL);1008}1009#endif1010if (!ssl->method->ssl3_enc->change_cipher_state(s,1011SSL3_CHANGE_CIPHER_SERVER_WRITE)) {1012/* SSLfatal() already called */1013return WORK_ERROR;1014}1015break;10161017case TLS_ST_SW_SRVR_DONE:1018if (statem_flush(s) != 1)1019return WORK_MORE_A;1020break;10211022case TLS_ST_SW_FINISHED:1023if (statem_flush(s) != 1)1024return WORK_MORE_A;1025#ifndef OPENSSL_NO_SCTP1026if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {1027/*1028* Change to new shared key of SCTP-Auth, will be ignored if1029* no SCTP used.1030*/1031BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,10320, NULL);1033}1034#endif1035if (SSL_CONNECTION_IS_TLS13(s)) {1036/* TLS 1.3 gets the secret size from the handshake md */1037size_t dummy;1038if (!ssl->method->ssl3_enc->generate_master_secret(s,1039s->master_secret, s->handshake_secret, 0,1040&dummy)1041|| !tls13_store_server_finished_hash(s)1042|| !ssl->method->ssl3_enc->change_cipher_state(s,1043SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))1044/* SSLfatal() already called */1045return WORK_ERROR;1046}1047break;10481049case TLS_ST_SW_CERT_REQ:1050if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {1051if (statem_flush(s) != 1)1052return WORK_MORE_A;1053} else {1054if (!SSL_CONNECTION_IS_TLS13(s)1055|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)1056s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;1057}1058break;10591060case TLS_ST_SW_ENCRYPTED_EXTENSIONS:1061if (!s->hit && !send_certificate_request(s)) {1062if (!SSL_CONNECTION_IS_TLS13(s)1063|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)1064s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;1065}1066break;10671068case TLS_ST_SW_KEY_UPDATE:1069if (statem_flush(s) != 1)1070return WORK_MORE_A;1071if (!tls13_update_key(s, 1)) {1072/* SSLfatal() already called */1073return WORK_ERROR;1074}1075break;10761077case TLS_ST_SW_SESSION_TICKET:1078clear_sys_error();1079if (SSL_CONNECTION_IS_TLS13(s) && statem_flush(s) != 1) {1080if (SSL_get_error(ssl, 0) == SSL_ERROR_SYSCALL1081&& conn_is_closed()) {1082/*1083* We ignore connection closed errors in TLSv1.3 when sending a1084* NewSessionTicket and behave as if we were successful. This is1085* so that we are still able to read data sent to us by a client1086* that closes soon after the end of the handshake without1087* waiting to read our post-handshake NewSessionTickets.1088*/1089s->rwstate = SSL_NOTHING;1090break;1091}10921093return WORK_MORE_A;1094}1095break;1096}10971098return WORK_FINISHED_CONTINUE;1099}11001101/*1102* Get the message construction function and message type for sending from the1103* server1104*1105* Valid return values are:1106* 1: Success1107* 0: Error1108*/1109int ossl_statem_server_construct_message(SSL_CONNECTION *s,1110confunc_f *confunc, int *mt)1111{1112OSSL_STATEM *st = &s->statem;11131114switch (st->hand_state) {1115default:1116/* Shouldn't happen */1117SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);1118return 0;11191120case TLS_ST_SW_CHANGE:1121if (SSL_CONNECTION_IS_DTLS(s))1122*confunc = dtls_construct_change_cipher_spec;1123else1124*confunc = tls_construct_change_cipher_spec;1125*mt = SSL3_MT_CHANGE_CIPHER_SPEC;1126break;11271128case DTLS_ST_SW_HELLO_VERIFY_REQUEST:1129*confunc = dtls_construct_hello_verify_request;1130*mt = DTLS1_MT_HELLO_VERIFY_REQUEST;1131break;11321133case TLS_ST_SW_HELLO_REQ:1134/* No construction function needed */1135*confunc = NULL;1136*mt = SSL3_MT_HELLO_REQUEST;1137break;11381139case TLS_ST_SW_SRVR_HELLO:1140*confunc = tls_construct_server_hello;1141*mt = SSL3_MT_SERVER_HELLO;1142break;11431144case TLS_ST_SW_CERT:1145*confunc = tls_construct_server_certificate;1146*mt = SSL3_MT_CERTIFICATE;1147break;11481149#ifndef OPENSSL_NO_COMP_ALG1150case TLS_ST_SW_COMP_CERT:1151*confunc = tls_construct_server_compressed_certificate;1152*mt = SSL3_MT_COMPRESSED_CERTIFICATE;1153break;1154#endif11551156case TLS_ST_SW_CERT_VRFY:1157*confunc = tls_construct_cert_verify;1158*mt = SSL3_MT_CERTIFICATE_VERIFY;1159break;11601161case TLS_ST_SW_KEY_EXCH:1162*confunc = tls_construct_server_key_exchange;1163*mt = SSL3_MT_SERVER_KEY_EXCHANGE;1164break;11651166case TLS_ST_SW_CERT_REQ:1167*confunc = tls_construct_certificate_request;1168*mt = SSL3_MT_CERTIFICATE_REQUEST;1169break;11701171case TLS_ST_SW_SRVR_DONE:1172*confunc = tls_construct_server_done;1173*mt = SSL3_MT_SERVER_DONE;1174break;11751176case TLS_ST_SW_SESSION_TICKET:1177*confunc = tls_construct_new_session_ticket;1178*mt = SSL3_MT_NEWSESSION_TICKET;1179break;11801181case TLS_ST_SW_CERT_STATUS:1182*confunc = tls_construct_cert_status;1183*mt = SSL3_MT_CERTIFICATE_STATUS;1184break;11851186case TLS_ST_SW_FINISHED:1187*confunc = tls_construct_finished;1188*mt = SSL3_MT_FINISHED;1189break;11901191case TLS_ST_EARLY_DATA:1192*confunc = NULL;1193*mt = SSL3_MT_DUMMY;1194break;11951196case TLS_ST_SW_ENCRYPTED_EXTENSIONS:1197*confunc = tls_construct_encrypted_extensions;1198*mt = SSL3_MT_ENCRYPTED_EXTENSIONS;1199break;12001201case TLS_ST_SW_KEY_UPDATE:1202*confunc = tls_construct_key_update;1203*mt = SSL3_MT_KEY_UPDATE;1204break;1205}12061207return 1;1208}12091210/*1211* Maximum size (excluding the Handshake header) of a ClientHello message,1212* calculated as follows:1213*1214* 2 + # client_version1215* 32 + # only valid length for random1216* 1 + # length of session_id1217* 32 + # maximum size for session_id1218* 2 + # length of cipher suites1219* 2^16-2 + # maximum length of cipher suites array1220* 1 + # length of compression_methods1221* 2^8-1 + # maximum length of compression methods1222* 2 + # length of extensions1223* 2^16-1 # maximum length of extensions1224*/1225#define CLIENT_HELLO_MAX_LENGTH 13139612261227#define CLIENT_KEY_EXCH_MAX_LENGTH 20481228#define NEXT_PROTO_MAX_LENGTH 51412291230/*1231* Returns the maximum allowed length for the current message that we are1232* reading. Excludes the message header.1233*/1234size_t ossl_statem_server_max_message_size(SSL_CONNECTION *s)1235{1236OSSL_STATEM *st = &s->statem;12371238switch (st->hand_state) {1239default:1240/* Shouldn't happen */1241return 0;12421243case TLS_ST_SR_CLNT_HELLO:1244return CLIENT_HELLO_MAX_LENGTH;12451246case TLS_ST_SR_END_OF_EARLY_DATA:1247return END_OF_EARLY_DATA_MAX_LENGTH;12481249case TLS_ST_SR_COMP_CERT:1250case TLS_ST_SR_CERT:1251return s->max_cert_list;12521253case TLS_ST_SR_KEY_EXCH:1254return CLIENT_KEY_EXCH_MAX_LENGTH;12551256case TLS_ST_SR_CERT_VRFY:1257return CERTIFICATE_VERIFY_MAX_LENGTH;12581259#ifndef OPENSSL_NO_NEXTPROTONEG1260case TLS_ST_SR_NEXT_PROTO:1261return NEXT_PROTO_MAX_LENGTH;1262#endif12631264case TLS_ST_SR_CHANGE:1265return CCS_MAX_LENGTH;12661267case TLS_ST_SR_FINISHED:1268return FINISHED_MAX_LENGTH;12691270case TLS_ST_SR_KEY_UPDATE:1271return KEY_UPDATE_MAX_LENGTH;1272}1273}12741275/*1276* Process a message that the server has received from the client.1277*/1278MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL_CONNECTION *s,1279PACKET *pkt)1280{1281OSSL_STATEM *st = &s->statem;12821283switch (st->hand_state) {1284default:1285/* Shouldn't happen */1286SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1287return MSG_PROCESS_ERROR;12881289case TLS_ST_SR_CLNT_HELLO:1290return tls_process_client_hello(s, pkt);12911292case TLS_ST_SR_END_OF_EARLY_DATA:1293return tls_process_end_of_early_data(s, pkt);12941295case TLS_ST_SR_CERT:1296return tls_process_client_certificate(s, pkt);12971298#ifndef OPENSSL_NO_COMP_ALG1299case TLS_ST_SR_COMP_CERT:1300return tls_process_client_compressed_certificate(s, pkt);1301#endif13021303case TLS_ST_SR_KEY_EXCH:1304return tls_process_client_key_exchange(s, pkt);13051306case TLS_ST_SR_CERT_VRFY:1307return tls_process_cert_verify(s, pkt);13081309#ifndef OPENSSL_NO_NEXTPROTONEG1310case TLS_ST_SR_NEXT_PROTO:1311return tls_process_next_proto(s, pkt);1312#endif13131314case TLS_ST_SR_CHANGE:1315return tls_process_change_cipher_spec(s, pkt);13161317case TLS_ST_SR_FINISHED:1318return tls_process_finished(s, pkt);13191320case TLS_ST_SR_KEY_UPDATE:1321return tls_process_key_update(s, pkt);1322}1323}13241325/*1326* Perform any further processing required following the receipt of a message1327* from the client1328*/1329WORK_STATE ossl_statem_server_post_process_message(SSL_CONNECTION *s,1330WORK_STATE wst)1331{1332OSSL_STATEM *st = &s->statem;13331334switch (st->hand_state) {1335default:1336/* Shouldn't happen */1337SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1338return WORK_ERROR;13391340case TLS_ST_SR_CLNT_HELLO:1341return tls_post_process_client_hello(s, wst);13421343case TLS_ST_SR_KEY_EXCH:1344return tls_post_process_client_key_exchange(s, wst);1345}1346}13471348#ifndef OPENSSL_NO_SRP1349/* Returns 1 on success, 0 for retryable error, -1 for fatal error */1350static int ssl_check_srp_ext_ClientHello(SSL_CONNECTION *s)1351{1352int ret;1353int al = SSL_AD_UNRECOGNIZED_NAME;13541355if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {1356if (s->srp_ctx.login == NULL) {1357/*1358* RFC 5054 says SHOULD reject, we do so if There is no srp1359* login name1360*/1361SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,1362SSL_R_PSK_IDENTITY_NOT_FOUND);1363return -1;1364} else {1365ret = ssl_srp_server_param_with_username_intern(s, &al);1366if (ret < 0)1367return 0;1368if (ret == SSL3_AL_FATAL) {1369SSLfatal(s, al,1370al == SSL_AD_UNKNOWN_PSK_IDENTITY1371? SSL_R_PSK_IDENTITY_NOT_FOUND1372: SSL_R_CLIENTHELLO_TLSEXT);1373return -1;1374}1375}1376}1377return 1;1378}1379#endif13801381int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,1382size_t cookie_len)1383{1384/* Always use DTLS 1.0 version: see RFC 6347 */1385if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)1386|| !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))1387return 0;13881389return 1;1390}13911392CON_FUNC_RETURN dtls_construct_hello_verify_request(SSL_CONNECTION *s,1393WPACKET *pkt)1394{1395unsigned int cookie_leni;1396SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);13971398if (sctx->app_gen_cookie_cb == NULL1399|| sctx->app_gen_cookie_cb(SSL_CONNECTION_GET_USER_SSL(s), s->d1->cookie,1400&cookie_leni)1401== 01402|| cookie_leni > DTLS1_COOKIE_LENGTH) {1403SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);1404return CON_FUNC_ERROR;1405}1406s->d1->cookie_len = cookie_leni;14071408if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,1409s->d1->cookie_len)) {1410SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);1411return CON_FUNC_ERROR;1412}14131414return CON_FUNC_SUCCESS;1415}14161417/*-1418* ssl_check_for_safari attempts to fingerprint Safari using OS X1419* SecureTransport using the TLS extension block in |hello|.1420* Safari, since 10.6, sends exactly these extensions, in this order:1421* SNI,1422* elliptic_curves1423* ec_point_formats1424* signature_algorithms (for TLSv1.2 only)1425*1426* We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,1427* but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.1428* Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from1429* 10.8..10.8.3 (which don't work).1430*/1431static void ssl_check_for_safari(SSL_CONNECTION *s,1432const CLIENTHELLO_MSG *hello)1433{1434static const unsigned char kSafariExtensionsBlock[] = {14350x00,14360x0a, /* elliptic_curves extension */14370x00,14380x08, /* 8 bytes */14390x00,14400x06, /* 6 bytes of curve ids */14410x00,14420x17, /* P-256 */14430x00,14440x18, /* P-384 */14450x00,14460x19, /* P-521 */144714480x00,14490x0b, /* ec_point_formats */14500x00,14510x02, /* 2 bytes */14520x01, /* 1 point format */14530x00, /* uncompressed */1454/* The following is only present in TLS 1.2 */14550x00,14560x0d, /* signature_algorithms */14570x00,14580x0c, /* 12 bytes */14590x00,14600x0a, /* 10 bytes */14610x05,14620x01, /* SHA-384/RSA */14630x04,14640x01, /* SHA-256/RSA */14650x02,14660x01, /* SHA-1/RSA */14670x04,14680x03, /* SHA-256/ECDSA */14690x02,14700x03, /* SHA-1/ECDSA */1471};1472/* Length of the common prefix (first two extensions). */1473static const size_t kSafariCommonExtensionsLength = 18;1474unsigned int type;1475PACKET sni, tmppkt;1476size_t ext_len;14771478tmppkt = hello->extensions;14791480if (!PACKET_forward(&tmppkt, 2)1481|| !PACKET_get_net_2(&tmppkt, &type)1482|| !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {1483return;1484}14851486if (type != TLSEXT_TYPE_server_name)1487return;14881489ext_len = TLS1_get_client_version(1490SSL_CONNECTION_GET_SSL(s))1491>= TLS1_2_VERSION1492? sizeof(kSafariExtensionsBlock)1493: kSafariCommonExtensionsLength;14941495s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,1496ext_len);1497}14981499#define RENEG_OPTIONS_OK(options) \1500((options & SSL_OP_NO_RENEGOTIATION) == 0 \1501&& (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)15021503MSG_PROCESS_RETURN tls_process_client_hello(SSL_CONNECTION *s, PACKET *pkt)1504{1505/* |cookie| will only be initialized for DTLS. */1506PACKET session_id, compression, extensions, cookie;1507static const unsigned char null_compression = 0;1508CLIENTHELLO_MSG *clienthello = NULL;15091510/* Check if this is actually an unexpected renegotiation ClientHello */1511if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {1512if (!ossl_assert(!SSL_CONNECTION_IS_TLS13(s))) {1513SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1514goto err;1515}1516if (!RENEG_OPTIONS_OK(s->options)1517|| (!s->s3.send_connection_binding1518&& (s->options1519& SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)1520== 0)) {1521ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);1522return MSG_PROCESS_FINISHED_READING;1523}1524s->renegotiate = 1;1525s->new_session = 1;1526}15271528clienthello = OPENSSL_zalloc(sizeof(*clienthello));1529if (clienthello == NULL) {1530SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1531goto err;1532}15331534/*1535* First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.1536*/1537clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);1538PACKET_null_init(&cookie);15391540if (clienthello->isv2) {1541unsigned int mt;15421543if (!SSL_IS_FIRST_HANDSHAKE(s)1544|| s->hello_retry_request != SSL_HRR_NONE) {1545SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);1546goto err;1547}15481549/*-1550* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv21551* header is sent directly on the wire, not wrapped as a TLS1552* record. Our record layer just processes the message length and passes1553* the rest right through. Its format is:1554* Byte Content1555* 0-1 msg_length - decoded by the record layer1556* 2 msg_type - s->init_msg points here1557* 3-4 version1558* 5-6 cipher_spec_length1559* 7-8 session_id_length1560* 9-10 challenge_length1561* ... ...1562*/15631564if (!PACKET_get_1(pkt, &mt)1565|| mt != SSL2_MT_CLIENT_HELLO) {1566/*1567* Should never happen. We should have tested this in the record1568* layer in order to have determined that this is an SSLv2 record1569* in the first place1570*/1571SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1572goto err;1573}1574}15751576if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {1577SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);1578goto err;1579}15801581/* Parse the message and load client random. */1582if (clienthello->isv2) {1583/*1584* Handle an SSLv2 backwards compatible ClientHello1585* Note, this is only for SSLv3+ using the backward compatible format.1586* Real SSLv2 is not supported, and is rejected below.1587*/1588unsigned int ciphersuite_len, session_id_len, challenge_len;1589PACKET challenge;15901591if (!PACKET_get_net_2(pkt, &ciphersuite_len)1592|| !PACKET_get_net_2(pkt, &session_id_len)1593|| !PACKET_get_net_2(pkt, &challenge_len)) {1594SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);1595goto err;1596}15971598if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {1599SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);1600goto err;1601}16021603if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,1604ciphersuite_len)1605|| !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)1606|| !PACKET_get_sub_packet(pkt, &challenge, challenge_len)1607/* No extensions. */1608|| PACKET_remaining(pkt) != 0) {1609SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);1610goto err;1611}1612clienthello->session_id_len = session_id_len;16131614/* Load the client random and compression list. We use SSL3_RANDOM_SIZE1615* here rather than sizeof(clienthello->random) because that is the limit1616* for SSLv3 and it is fixed. It won't change even if1617* sizeof(clienthello->random) does.1618*/1619challenge_len = challenge_len > SSL3_RANDOM_SIZE1620? SSL3_RANDOM_SIZE1621: challenge_len;1622memset(clienthello->random, 0, SSL3_RANDOM_SIZE);1623if (!PACKET_copy_bytes(&challenge,1624clienthello->random + SSL3_RANDOM_SIZE - challenge_len, challenge_len)1625/* Advertise only null compression. */1626|| !PACKET_buf_init(&compression, &null_compression, 1)) {1627SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1628goto err;1629}16301631PACKET_null_init(&clienthello->extensions);1632} else {1633/* Regular ClientHello. */1634if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)1635|| !PACKET_get_length_prefixed_1(pkt, &session_id)1636|| !PACKET_copy_all(&session_id, clienthello->session_id,1637SSL_MAX_SSL_SESSION_ID_LENGTH,1638&clienthello->session_id_len)) {1639SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1640goto err;1641}16421643if (SSL_CONNECTION_IS_DTLS(s)) {1644if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {1645SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1646goto err;1647}1648if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,1649DTLS1_COOKIE_LENGTH,1650&clienthello->dtls_cookie_len)) {1651SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1652goto err;1653}1654/*1655* If we require cookies and this ClientHello doesn't contain one,1656* just return since we do not want to allocate any memory yet.1657* So check cookie length...1658*/1659if (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE) {1660if (clienthello->dtls_cookie_len == 0) {1661OPENSSL_free(clienthello);1662return MSG_PROCESS_FINISHED_READING;1663}1664}1665}16661667if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {1668SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1669goto err;1670}16711672if (!PACKET_get_length_prefixed_1(pkt, &compression)) {1673SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1674goto err;1675}16761677/* Could be empty. */1678if (PACKET_remaining(pkt) == 0) {1679PACKET_null_init(&clienthello->extensions);1680} else {1681if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)1682|| PACKET_remaining(pkt) != 0) {1683SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1684goto err;1685}1686}1687}16881689if (!PACKET_copy_all(&compression, clienthello->compressions,1690MAX_COMPRESSIONS_SIZE,1691&clienthello->compressions_len)) {1692SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1693goto err;1694}16951696/* Preserve the raw extensions PACKET for later use */1697extensions = clienthello->extensions;1698if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,1699&clienthello->pre_proc_exts,1700&clienthello->pre_proc_exts_len, 1)) {1701/* SSLfatal already been called */1702goto err;1703}1704s->clienthello = clienthello;17051706return MSG_PROCESS_CONTINUE_PROCESSING;17071708err:1709if (clienthello != NULL)1710OPENSSL_free(clienthello->pre_proc_exts);1711OPENSSL_free(clienthello);17121713return MSG_PROCESS_ERROR;1714}17151716static int tls_early_post_process_client_hello(SSL_CONNECTION *s)1717{1718unsigned int j;1719int i, al = SSL_AD_INTERNAL_ERROR;1720int protverr;1721unsigned long id;1722#ifndef OPENSSL_NO_COMP1723SSL_COMP *comp = NULL;1724#endif1725const SSL_CIPHER *c;1726STACK_OF(SSL_CIPHER) *ciphers = NULL;1727STACK_OF(SSL_CIPHER) *scsvs = NULL;1728CLIENTHELLO_MSG *clienthello = s->clienthello;1729DOWNGRADE dgrd = DOWNGRADE_NONE;1730SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);1731SSL *ssl = SSL_CONNECTION_GET_SSL(s);1732SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);17331734/* Finished parsing the ClientHello, now we can start processing it */1735/* Give the ClientHello callback a crack at things */1736if (sctx->client_hello_cb != NULL) {1737/* A failure in the ClientHello callback terminates the connection. */1738switch (sctx->client_hello_cb(ussl, &al, sctx->client_hello_cb_arg)) {1739case SSL_CLIENT_HELLO_SUCCESS:1740break;1741case SSL_CLIENT_HELLO_RETRY:1742s->rwstate = SSL_CLIENT_HELLO_CB;1743return -1;1744case SSL_CLIENT_HELLO_ERROR:1745default:1746SSLfatal(s, al, SSL_R_CALLBACK_FAILED);1747goto err;1748}1749}17501751/* Set up the client_random */1752memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);17531754/* Choose the version */17551756if (clienthello->isv2) {1757if (clienthello->legacy_version == SSL2_VERSION1758|| (clienthello->legacy_version & 0xff00)1759!= (SSL3_VERSION_MAJOR << 8)) {1760/*1761* This is real SSLv2 or something completely unknown. We don't1762* support it.1763*/1764SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);1765goto err;1766}1767/* SSLv3/TLS */1768s->client_version = clienthello->legacy_version;1769}17701771/* Choose the server SSL/TLS/DTLS version. */1772protverr = ssl_choose_server_version(s, clienthello, &dgrd);17731774if (protverr) {1775if (SSL_IS_FIRST_HANDSHAKE(s)) {1776/* like ssl3_get_record, send alert using remote version number */1777s->version = s->client_version = clienthello->legacy_version;1778}1779SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);1780goto err;1781}17821783/* TLSv1.3 specifies that a ClientHello must end on a record boundary */1784if (SSL_CONNECTION_IS_TLS13(s)1785&& RECORD_LAYER_processed_read_pending(&s->rlayer)) {1786SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);1787goto err;1788}17891790if (SSL_CONNECTION_IS_DTLS(s)) {1791/* Empty cookie was already handled above by returning early. */1792if (SSL_get_options(ssl) & SSL_OP_COOKIE_EXCHANGE) {1793if (sctx->app_verify_cookie_cb != NULL) {1794if (sctx->app_verify_cookie_cb(ussl, clienthello->dtls_cookie,1795clienthello->dtls_cookie_len)1796== 0) {1797SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,1798SSL_R_COOKIE_MISMATCH);1799goto err;1800/* else cookie verification succeeded */1801}1802/* default verification */1803} else if (s->d1->cookie_len != clienthello->dtls_cookie_len1804|| memcmp(clienthello->dtls_cookie, s->d1->cookie,1805s->d1->cookie_len)1806!= 0) {1807SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);1808goto err;1809}1810s->d1->cookie_verified = 1;1811}1812}18131814s->hit = 0;18151816if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,1817clienthello->isv2)1818|| !ossl_bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers,1819&scsvs, clienthello->isv2, 1)) {1820/* SSLfatal() already called */1821goto err;1822}18231824s->s3.send_connection_binding = 0;1825/* Check what signalling cipher-suite values were received. */1826if (scsvs != NULL) {1827for (i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {1828c = sk_SSL_CIPHER_value(scsvs, i);1829if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {1830if (s->renegotiate) {1831/* SCSV is fatal if renegotiating */1832SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,1833SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);1834goto err;1835}1836s->s3.send_connection_binding = 1;1837} else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV && !ssl_check_version_downgrade(s)) {1838/*1839* This SCSV indicates that the client previously tried1840* a higher version. We should fail if the current version1841* is an unexpected downgrade, as that indicates that the first1842* connection may have been tampered with in order to trigger1843* an insecure downgrade.1844*/1845SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,1846SSL_R_INAPPROPRIATE_FALLBACK);1847goto err;1848}1849}1850}18511852/* For TLSv1.3 we must select the ciphersuite *before* session resumption */1853if (SSL_CONNECTION_IS_TLS13(s)) {1854const SSL_CIPHER *cipher = ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(ssl));18551856if (cipher == NULL) {1857SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);1858goto err;1859}1860if (s->hello_retry_request == SSL_HRR_PENDING1861&& (s->s3.tmp.new_cipher == NULL1862|| s->s3.tmp.new_cipher->id != cipher->id)) {1863/*1864* A previous HRR picked a different ciphersuite to the one we1865* just selected. Something must have changed.1866*/1867SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);1868goto err;1869}1870s->s3.tmp.new_cipher = cipher;1871}18721873/* We need to do this before getting the session */1874if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,1875SSL_EXT_CLIENT_HELLO,1876clienthello->pre_proc_exts, NULL, 0)) {1877/* SSLfatal() already called */1878goto err;1879}18801881/*1882* We don't allow resumption in a backwards compatible ClientHello.1883* In TLS1.1+, session_id MUST be empty.1884*1885* Versions before 0.9.7 always allow clients to resume sessions in1886* renegotiation. 0.9.7 and later allow this by default, but optionally1887* ignore resumption requests with flag1888* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather1889* than a change to default behavior so that applications relying on1890* this for security won't even compile against older library versions).1891* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to1892* request renegotiation but not a new session (s->new_session remains1893* unset): for servers, this essentially just means that the1894* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be1895* ignored.1896*/1897if (clienthello->isv2 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {1898if (!ssl_get_new_session(s, 1)) {1899/* SSLfatal() already called */1900goto err;1901}1902} else {1903i = ssl_get_prev_session(s, clienthello);1904if (i == 1) {1905/* previous session */1906s->hit = 1;1907} else if (i == -1) {1908/* SSLfatal() already called */1909goto err;1910} else {1911/* i == 0 */1912if (!ssl_get_new_session(s, 1)) {1913/* SSLfatal() already called */1914goto err;1915}1916}1917}19181919if (SSL_CONNECTION_IS_TLS13(s)) {1920memcpy(s->tmp_session_id, s->clienthello->session_id,1921s->clienthello->session_id_len);1922s->tmp_session_id_len = s->clienthello->session_id_len;1923}19241925/*1926* If it is a hit, check that the cipher is in the list. In TLSv1.3 we check1927* ciphersuite compatibility with the session as part of resumption.1928*/1929if (!SSL_CONNECTION_IS_TLS13(s) && s->hit) {1930j = 0;1931id = s->session->cipher->id;19321933OSSL_TRACE_BEGIN(TLS_CIPHER)1934{1935BIO_printf(trc_out, "client sent %d ciphers\n",1936sk_SSL_CIPHER_num(ciphers));1937}1938for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {1939c = sk_SSL_CIPHER_value(ciphers, i);1940if (trc_out != NULL)1941BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,1942sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));1943if (c->id == id) {1944j = 1;1945break;1946}1947}1948if (j == 0) {1949/*1950* we need to have the cipher in the cipher list if we are asked1951* to reuse it1952*/1953SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1954SSL_R_REQUIRED_CIPHER_MISSING);1955OSSL_TRACE_CANCEL(TLS_CIPHER);1956goto err;1957}1958OSSL_TRACE_END(TLS_CIPHER);1959}19601961/* At least one compression method must be preset. */1962if (clienthello->compressions_len == 0) {1963SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);1964goto err;1965}1966/* Make sure at least the null compression is supported. */1967if (memchr(clienthello->compressions, 0,1968clienthello->compressions_len)1969== NULL) {1970SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1971SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);1972goto err;1973}19741975if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)1976ssl_check_for_safari(s, clienthello);19771978/* TLS extensions */1979if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,1980clienthello->pre_proc_exts, NULL, 0, 1)) {1981/* SSLfatal() already called */1982goto err;1983}19841985/*1986* Check if we want to use external pre-shared secret for this handshake1987* for not reused session only. We need to generate server_random before1988* calling tls_session_secret_cb in order to allow SessionTicket1989* processing to use it in key derivation.1990*/1991{1992unsigned char *pos;1993pos = s->s3.server_random;1994if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {1995SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1996goto err;1997}1998}19992000if (!s->hit && !tls1_set_server_sigalgs(s)) {2001/* SSLfatal() already called */2002goto err;2003}20042005if (!s->hit2006&& s->version >= TLS1_VERSION2007&& !SSL_CONNECTION_IS_TLS13(s)2008&& !SSL_CONNECTION_IS_DTLS(s)2009&& s->ext.session_secret_cb != NULL) {2010const SSL_CIPHER *pref_cipher = NULL;2011/*2012* s->session->master_key_length is a size_t, but this is an int for2013* backwards compat reasons2014*/2015int master_key_length;20162017master_key_length = sizeof(s->session->master_key);2018if (s->ext.session_secret_cb(ussl, s->session->master_key,2019&master_key_length, ciphers,2020&pref_cipher,2021s->ext.session_secret_cb_arg)2022&& master_key_length > 0) {2023s->session->master_key_length = master_key_length;2024s->hit = 1;2025s->peer_ciphers = ciphers;2026s->session->verify_result = X509_V_OK;20272028ciphers = NULL;20292030/* check if some cipher was preferred by call back */2031if (pref_cipher == NULL)2032pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,2033SSL_get_ciphers(ssl));2034if (pref_cipher == NULL) {2035SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);2036goto err;2037}20382039s->session->cipher = pref_cipher;2040sk_SSL_CIPHER_free(s->cipher_list);2041s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);2042sk_SSL_CIPHER_free(s->cipher_list_by_id);2043s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);2044}2045}20462047/*2048* Worst case, we will use the NULL compression, but if we have other2049* options, we will now look for them. We have complen-1 compression2050* algorithms from the client, starting at q.2051*/2052s->s3.tmp.new_compression = NULL;2053if (SSL_CONNECTION_IS_TLS13(s)) {2054/*2055* We already checked above that the NULL compression method appears in2056* the list. Now we check there aren't any others (which is illegal in2057* a TLSv1.3 ClientHello.2058*/2059if (clienthello->compressions_len != 1) {2060SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,2061SSL_R_INVALID_COMPRESSION_ALGORITHM);2062goto err;2063}2064}2065#ifndef OPENSSL_NO_COMP2066/* This only happens if we have a cache hit */2067else if (s->session->compress_meth != 0) {2068int m, comp_id = s->session->compress_meth;2069unsigned int k;2070/* Perform sanity checks on resumed compression algorithm */2071/* Can't disable compression */2072if (!ssl_allow_compression(s)) {2073SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2074SSL_R_INCONSISTENT_COMPRESSION);2075goto err;2076}2077/* Look for resumed compression method */2078for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {2079comp = sk_SSL_COMP_value(sctx->comp_methods, m);2080if (comp_id == comp->id) {2081s->s3.tmp.new_compression = comp;2082break;2083}2084}2085if (s->s3.tmp.new_compression == NULL) {2086SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2087SSL_R_INVALID_COMPRESSION_ALGORITHM);2088goto err;2089}2090/* Look for resumed method in compression list */2091for (k = 0; k < clienthello->compressions_len; k++) {2092if (clienthello->compressions[k] == comp_id)2093break;2094}2095if (k >= clienthello->compressions_len) {2096SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,2097SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);2098goto err;2099}2100} else if (s->hit) {2101comp = NULL;2102} else if (ssl_allow_compression(s) && sctx->comp_methods) {2103/* See if we have a match */2104int m, nn, v, done = 0;2105unsigned int o;21062107nn = sk_SSL_COMP_num(sctx->comp_methods);2108for (m = 0; m < nn; m++) {2109comp = sk_SSL_COMP_value(sctx->comp_methods, m);2110v = comp->id;2111for (o = 0; o < clienthello->compressions_len; o++) {2112if (v == clienthello->compressions[o]) {2113done = 1;2114break;2115}2116}2117if (done)2118break;2119}2120if (done)2121s->s3.tmp.new_compression = comp;2122else2123comp = NULL;2124}2125#else2126/*2127* If compression is disabled we'd better not try to resume a session2128* using compression.2129*/2130if (s->session->compress_meth != 0) {2131SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);2132goto err;2133}2134#endif21352136/*2137* Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher2138*/21392140if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {2141sk_SSL_CIPHER_free(s->peer_ciphers);2142s->peer_ciphers = ciphers;2143if (ciphers == NULL) {2144SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2145goto err;2146}2147ciphers = NULL;2148}21492150if (!s->hit) {2151#ifdef OPENSSL_NO_COMP2152s->session->compress_meth = 0;2153#else2154s->session->compress_meth = (comp == NULL) ? 0 : comp->id;2155#endif2156}21572158sk_SSL_CIPHER_free(ciphers);2159sk_SSL_CIPHER_free(scsvs);2160OPENSSL_free(clienthello->pre_proc_exts);2161OPENSSL_free(s->clienthello);2162s->clienthello = NULL;2163return 1;2164err:2165sk_SSL_CIPHER_free(ciphers);2166sk_SSL_CIPHER_free(scsvs);2167OPENSSL_free(clienthello->pre_proc_exts);2168OPENSSL_free(s->clienthello);2169s->clienthello = NULL;21702171return 0;2172}21732174/*2175* Call the status request callback if needed. Upon success, returns 1.2176* Upon failure, returns 0.2177*/2178static int tls_handle_status_request(SSL_CONNECTION *s)2179{2180SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);21812182s->ext.status_expected = 0;21832184/*2185* If status request then ask callback what to do. Note: this must be2186* called after servername callbacks in case the certificate has changed,2187* and must be called after the cipher has been chosen because this may2188* influence which certificate is sent2189*/2190if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL2191&& sctx->ext.status_cb != NULL) {2192int ret;21932194/* If no certificate can't return certificate status */2195if (s->s3.tmp.cert != NULL) {2196/*2197* Set current certificate to one we will use so SSL_get_certificate2198* et al can pick it up.2199*/2200s->cert->key = s->s3.tmp.cert;2201ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),2202sctx->ext.status_arg);2203switch (ret) {2204/* We don't want to send a status request response */2205case SSL_TLSEXT_ERR_NOACK:2206s->ext.status_expected = 0;2207break;2208/* status request response should be sent */2209case SSL_TLSEXT_ERR_OK:2210if (s->ext.ocsp.resp)2211s->ext.status_expected = 1;2212break;2213/* something bad happened */2214case SSL_TLSEXT_ERR_ALERT_FATAL:2215default:2216SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);2217return 0;2218}2219}2220}22212222return 1;2223}22242225/*2226* Call the alpn_select callback if needed. Upon success, returns 1.2227* Upon failure, returns 0.2228*/2229int tls_handle_alpn(SSL_CONNECTION *s)2230{2231const unsigned char *selected = NULL;2232unsigned char selected_len = 0;2233SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);22342235if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {2236int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),2237&selected, &selected_len,2238s->s3.alpn_proposed,2239(unsigned int)s->s3.alpn_proposed_len,2240sctx->ext.alpn_select_cb_arg);22412242if (r == SSL_TLSEXT_ERR_OK) {2243OPENSSL_free(s->s3.alpn_selected);2244s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);2245if (s->s3.alpn_selected == NULL) {2246s->s3.alpn_selected_len = 0;2247SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2248return 0;2249}2250s->s3.alpn_selected_len = selected_len;2251#ifndef OPENSSL_NO_NEXTPROTONEG2252/* ALPN takes precedence over NPN. */2253s->s3.npn_seen = 0;2254#endif22552256/* Check ALPN is consistent with session */2257if (s->session->ext.alpn_selected == NULL2258|| selected_len != s->session->ext.alpn_selected_len2259|| memcmp(selected, s->session->ext.alpn_selected,2260selected_len)2261!= 0) {2262/* Not consistent so can't be used for early_data */2263s->ext.early_data_ok = 0;22642265if (!s->hit) {2266/*2267* This is a new session and so alpn_selected should have2268* been initialised to NULL. We should update it with the2269* selected ALPN.2270*/2271if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {2272SSLfatal(s, SSL_AD_INTERNAL_ERROR,2273ERR_R_INTERNAL_ERROR);2274return 0;2275}2276s->session->ext.alpn_selected = OPENSSL_memdup(selected,2277selected_len);2278if (s->session->ext.alpn_selected == NULL) {2279SSLfatal(s, SSL_AD_INTERNAL_ERROR,2280ERR_R_INTERNAL_ERROR);2281return 0;2282}2283s->session->ext.alpn_selected_len = selected_len;2284}2285}22862287return 1;2288} else if (r != SSL_TLSEXT_ERR_NOACK) {2289SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,2290SSL_R_NO_APPLICATION_PROTOCOL);2291return 0;2292}2293/*2294* If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was2295* present.2296*/2297}22982299/* Check ALPN is consistent with session */2300if (s->session->ext.alpn_selected != NULL) {2301/* Not consistent so can't be used for early_data */2302s->ext.early_data_ok = 0;2303}23042305return 1;2306}23072308WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)2309{2310const SSL_CIPHER *cipher;2311SSL *ssl = SSL_CONNECTION_GET_SSL(s);2312SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);23132314if (wst == WORK_MORE_A) {2315int rv = tls_early_post_process_client_hello(s);2316if (rv == 0) {2317/* SSLfatal() was already called */2318goto err;2319}2320if (rv < 0)2321return WORK_MORE_A;2322wst = WORK_MORE_B;2323}2324if (wst == WORK_MORE_B) {2325if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {2326/* Let cert callback update server certificates if required */2327if (!s->hit && s->cert->cert_cb != NULL) {2328int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);23292330if (rv == 0) {2331SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);2332goto err;2333}2334if (rv < 0) {2335s->rwstate = SSL_X509_LOOKUP;2336return WORK_MORE_B;2337}2338s->rwstate = SSL_NOTHING;2339}23402341/* In TLSv1.3 we selected the ciphersuite before resumption */2342if (!SSL_CONNECTION_IS_TLS13(s)) {2343cipher = ssl3_choose_cipher(s, s->peer_ciphers,2344SSL_get_ciphers(ssl));23452346if (cipher == NULL) {2347SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2348SSL_R_NO_SHARED_CIPHER);2349goto err;2350}2351s->s3.tmp.new_cipher = cipher;2352}2353if (!s->hit) {2354if (!tls_choose_sigalg(s, 1)) {2355/* SSLfatal already called */2356goto err;2357}2358/* check whether we should disable session resumption */2359if (s->not_resumable_session_cb != NULL)2360s->session->not_resumable = s->not_resumable_session_cb(ussl,2361((s->s3.tmp.new_cipher->algorithm_mkey2362& (SSL_kDHE | SSL_kECDHE))2363!= 0));2364if (s->session->not_resumable)2365/* do not send a session ticket */2366s->ext.ticket_expected = 0;2367}2368} else {2369/* Session-id reuse */2370s->s3.tmp.new_cipher = s->session->cipher;2371}23722373/*-2374* we now have the following setup.2375* client_random2376* cipher_list - our preferred list of ciphers2377* ciphers - the client's preferred list of ciphers2378* compression - basically ignored right now2379* ssl version is set - sslv32380* s->session - The ssl session has been setup.2381* s->hit - session reuse flag2382* s->s3.tmp.new_cipher - the new cipher to use.2383*/23842385/*2386* Call status_request callback if needed. Has to be done after the2387* certificate callbacks etc above.2388*/2389if (!tls_handle_status_request(s)) {2390/* SSLfatal() already called */2391goto err;2392}2393/*2394* Call alpn_select callback if needed. Has to be done after SNI and2395* cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.32396* we already did this because cipher negotiation happens earlier, and2397* we must handle ALPN before we decide whether to accept early_data.2398*/2399if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {2400/* SSLfatal() already called */2401goto err;2402}24032404wst = WORK_MORE_C;2405}2406#ifndef OPENSSL_NO_SRP2407if (wst == WORK_MORE_C) {2408int ret;2409if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {2410/*2411* callback indicates further work to be done2412*/2413s->rwstate = SSL_X509_LOOKUP;2414return WORK_MORE_C;2415}2416if (ret < 0) {2417/* SSLfatal() already called */2418goto err;2419}2420}2421#endif24222423return WORK_FINISHED_STOP;2424err:2425return WORK_ERROR;2426}24272428CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)2429{2430int compm;2431size_t sl, len;2432int version;2433unsigned char *session_id;2434int usetls13 = SSL_CONNECTION_IS_TLS13(s)2435|| s->hello_retry_request == SSL_HRR_PENDING;24362437version = usetls13 ? TLS1_2_VERSION : s->version;2438if (!WPACKET_put_bytes_u16(pkt, version)2439/*2440* Random stuff. Filling of the server_random takes place in2441* tls_process_client_hello()2442*/2443|| !WPACKET_memcpy(pkt,2444s->hello_retry_request == SSL_HRR_PENDING2445? hrrrandom2446: s->s3.server_random,2447SSL3_RANDOM_SIZE)) {2448SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2449return CON_FUNC_ERROR;2450}24512452/*-2453* There are several cases for the session ID to send2454* back in the server hello:2455* - For session reuse from the session cache,2456* we send back the old session ID.2457* - If stateless session reuse (using a session ticket)2458* is successful, we send back the client's "session ID"2459* (which doesn't actually identify the session).2460* - If it is a new session, we send back the new2461* session ID.2462* - However, if we want the new session to be single-use,2463* we send back a 0-length session ID.2464* - In TLSv1.3 we echo back the session id sent to us by the client2465* regardless2466* s->hit is non-zero in either case of session reuse,2467* so the following won't overwrite an ID that we're supposed2468* to send back.2469*/2470if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)2471&& !s->hit)2472s->session->session_id_length = 0;24732474if (usetls13) {2475sl = s->tmp_session_id_len;2476session_id = s->tmp_session_id;2477} else {2478sl = s->session->session_id_length;2479session_id = s->session->session_id;2480}24812482if (sl > sizeof(s->session->session_id)) {2483SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2484return CON_FUNC_ERROR;2485}24862487/* set up the compression method */2488#ifdef OPENSSL_NO_COMP2489compm = 0;2490#else2491if (usetls13 || s->s3.tmp.new_compression == NULL)2492compm = 0;2493else2494compm = s->s3.tmp.new_compression->id;2495#endif24962497if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)2498|| !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,2499pkt, &len)2500|| !WPACKET_put_bytes_u8(pkt, compm)) {2501SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2502return CON_FUNC_ERROR;2503}25042505if (!tls_construct_extensions(s, pkt,2506s->hello_retry_request == SSL_HRR_PENDING2507? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST2508: (SSL_CONNECTION_IS_TLS13(s)2509? SSL_EXT_TLS1_3_SERVER_HELLO2510: SSL_EXT_TLS1_2_SERVER_HELLO),2511NULL, 0)) {2512/* SSLfatal() already called */2513return CON_FUNC_ERROR;2514}25152516if (s->hello_retry_request == SSL_HRR_PENDING) {2517/* Ditch the session. We'll create a new one next time around */2518SSL_SESSION_free(s->session);2519s->session = NULL;2520s->hit = 0;25212522/*2523* Re-initialise the Transcript Hash. We're going to prepopulate it with2524* a synthetic message_hash in place of ClientHello1.2525*/2526if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {2527/* SSLfatal() already called */2528return CON_FUNC_ERROR;2529}2530} else if (!(s->verify_mode & SSL_VERIFY_PEER)2531&& !ssl3_digest_cached_records(s, 0)) {2532/* SSLfatal() already called */;2533return CON_FUNC_ERROR;2534}25352536return CON_FUNC_SUCCESS;2537}25382539CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)2540{2541if (!s->s3.tmp.cert_request) {2542if (!ssl3_digest_cached_records(s, 0)) {2543/* SSLfatal() already called */2544return CON_FUNC_ERROR;2545}2546}2547return CON_FUNC_SUCCESS;2548}25492550CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,2551WPACKET *pkt)2552{2553EVP_PKEY *pkdh = NULL;2554unsigned char *encodedPoint = NULL;2555size_t encodedlen = 0;2556int curve_id = 0;2557const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;2558int i;2559unsigned long type;2560BIGNUM *r[4];2561EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();2562EVP_PKEY_CTX *pctx = NULL;2563size_t paramlen, paramoffset;2564int freer = 0;2565CON_FUNC_RETURN ret = CON_FUNC_ERROR;2566SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);25672568if (!WPACKET_get_total_written(pkt, ¶moffset)) {2569SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2570goto err;2571}25722573if (md_ctx == NULL) {2574SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2575goto err;2576}25772578type = s->s3.tmp.new_cipher->algorithm_mkey;25792580r[0] = r[1] = r[2] = r[3] = NULL;2581#ifndef OPENSSL_NO_PSK2582/* Plain PSK or RSAPSK nothing to do */2583if (type & (SSL_kPSK | SSL_kRSAPSK)) {2584} else2585#endif /* !OPENSSL_NO_PSK */2586if (type & (SSL_kDHE | SSL_kDHEPSK)) {2587CERT *cert = s->cert;2588EVP_PKEY *pkdhp = NULL;25892590if (s->cert->dh_tmp_auto) {2591pkdh = ssl_get_auto_dh(s);2592if (pkdh == NULL) {2593SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2594goto err;2595}2596pkdhp = pkdh;2597} else {2598pkdhp = cert->dh_tmp;2599}2600#if !defined(OPENSSL_NO_DEPRECATED_3_0)2601if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {2602pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s),26030, 1024));2604if (pkdh == NULL) {2605SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2606goto err;2607}2608pkdhp = pkdh;2609}2610#endif2611if (pkdhp == NULL) {2612SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);2613goto err;2614}2615if (!ssl_security(s, SSL_SECOP_TMP_DH,2616EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {2617SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);2618goto err;2619}2620if (s->s3.tmp.pkey != NULL) {2621SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2622goto err;2623}26242625s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);2626if (s->s3.tmp.pkey == NULL) {2627SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2628goto err;2629}26302631EVP_PKEY_free(pkdh);2632pkdh = NULL;26332634/* These BIGNUMs need to be freed when we're finished */2635freer = 1;2636if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,2637&r[0])2638|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,2639&r[1])2640|| !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,2641OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {2642SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2643goto err;2644}2645} else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {26462647if (s->s3.tmp.pkey != NULL) {2648SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2649goto err;2650}26512652/* Get NID of appropriate shared curve */2653curve_id = tls1_shared_group(s, -2);2654if (curve_id == 0) {2655SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,2656SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);2657goto err;2658}2659/* Cache the group used in the SSL_SESSION */2660s->session->kex_group = curve_id;2661/* Generate a new key for this curve */2662s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);2663if (s->s3.tmp.pkey == NULL) {2664/* SSLfatal() already called */2665goto err;2666}26672668/* Encode the public key. */2669encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,2670&encodedPoint);2671if (encodedlen == 0) {2672SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);2673goto err;2674}26752676/*2677* We'll generate the serverKeyExchange message explicitly so we2678* can set these to NULLs2679*/2680r[0] = NULL;2681r[1] = NULL;2682r[2] = NULL;2683r[3] = NULL;2684} else2685#ifndef OPENSSL_NO_SRP2686if (type & SSL_kSRP) {2687if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {2688SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);2689goto err;2690}2691r[0] = s->srp_ctx.N;2692r[1] = s->srp_ctx.g;2693r[2] = s->srp_ctx.s;2694r[3] = s->srp_ctx.B;2695} else2696#endif2697{2698SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);2699goto err;2700}27012702if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)2703|| ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {2704lu = NULL;2705} else if (lu == NULL) {2706SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);2707goto err;2708}27092710#ifndef OPENSSL_NO_PSK2711if (type & SSL_PSK) {2712size_t len = (s->cert->psk_identity_hint == NULL)2713? 02714: strlen(s->cert->psk_identity_hint);27152716/*2717* It should not happen that len > PSK_MAX_IDENTITY_LEN - we already2718* checked this when we set the identity hint - but just in case2719*/2720if (len > PSK_MAX_IDENTITY_LEN2721|| !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,2722len)) {2723SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2724goto err;2725}2726}2727#endif27282729for (i = 0; i < 4 && r[i] != NULL; i++) {2730unsigned char *binval;2731int res;27322733#ifndef OPENSSL_NO_SRP2734if ((i == 2) && (type & SSL_kSRP)) {2735res = WPACKET_start_sub_packet_u8(pkt);2736} else2737#endif2738res = WPACKET_start_sub_packet_u16(pkt);27392740if (!res) {2741SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2742goto err;2743}27442745/*-2746* for interoperability with some versions of the Microsoft TLS2747* stack, we need to zero pad the DHE pub key to the same length2748* as the prime2749*/2750if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {2751size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);27522753if (len > 0) {2754if (!WPACKET_allocate_bytes(pkt, len, &binval)) {2755SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2756goto err;2757}2758memset(binval, 0, len);2759}2760}27612762if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)2763|| !WPACKET_close(pkt)) {2764SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2765goto err;2766}27672768BN_bn2bin(r[i], binval);2769}27702771if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {2772/*2773* We only support named (not generic) curves. In this situation, the2774* ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]2775* [1 byte length of encoded point], followed by the actual encoded2776* point itself2777*/2778if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)2779|| !WPACKET_put_bytes_u8(pkt, 0)2780|| !WPACKET_put_bytes_u8(pkt, curve_id)2781|| !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {2782SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2783goto err;2784}2785OPENSSL_free(encodedPoint);2786encodedPoint = NULL;2787}27882789/* not anonymous */2790if (lu != NULL) {2791EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;2792const EVP_MD *md;2793unsigned char *sigbytes1, *sigbytes2, *tbs;2794size_t siglen = 0, tbslen;27952796if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {2797/* Should never happen */2798SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2799goto err;2800}2801/* Get length of the parameters we have written above */2802if (!WPACKET_get_length(pkt, ¶mlen)) {2803SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2804goto err;2805}2806/* send signature algorithm */2807if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {2808SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2809goto err;2810}28112812if (EVP_DigestSignInit_ex(md_ctx, &pctx,2813md == NULL ? NULL : EVP_MD_get0_name(md),2814sctx->libctx, sctx->propq, pkey,2815NULL)2816<= 0) {2817SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2818goto err;2819}2820if (lu->sig == EVP_PKEY_RSA_PSS) {2821if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 02822|| EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {2823SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2824goto err;2825}2826}2827tbslen = construct_key_exchange_tbs(s, &tbs,2828s->init_buf->data + paramoffset,2829paramlen);2830if (tbslen == 0) {2831/* SSLfatal() already called */2832goto err;2833}28342835if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <= 02836|| !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)2837|| EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 02838|| !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)2839|| sigbytes1 != sigbytes2) {2840OPENSSL_free(tbs);2841SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2842goto err;2843}2844OPENSSL_free(tbs);2845}28462847ret = CON_FUNC_SUCCESS;2848err:2849EVP_PKEY_free(pkdh);2850OPENSSL_free(encodedPoint);2851EVP_MD_CTX_free(md_ctx);2852if (freer) {2853BN_free(r[0]);2854BN_free(r[1]);2855BN_free(r[2]);2856BN_free(r[3]);2857}2858return ret;2859}28602861CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,2862WPACKET *pkt)2863{2864if (SSL_CONNECTION_IS_TLS13(s)) {2865/* Send random context when doing post-handshake auth */2866if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {2867OPENSSL_free(s->pha_context);2868s->pha_context_len = 32;2869if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {2870s->pha_context_len = 0;2871SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2872return CON_FUNC_ERROR;2873}2874if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,2875s->pha_context, s->pha_context_len, 0)2876<= 02877|| !WPACKET_sub_memcpy_u8(pkt, s->pha_context,2878s->pha_context_len)) {2879SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2880return CON_FUNC_ERROR;2881}2882/* reset the handshake hash back to just after the ClientFinished */2883if (!tls13_restore_handshake_digest_for_pha(s)) {2884/* SSLfatal() already called */2885return CON_FUNC_ERROR;2886}2887} else {2888if (!WPACKET_put_bytes_u8(pkt, 0)) {2889SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2890return CON_FUNC_ERROR;2891}2892}28932894if (!tls_construct_extensions(s, pkt,2895SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,28960)) {2897/* SSLfatal() already called */2898return CON_FUNC_ERROR;2899}2900goto done;2901}29022903/* get the list of acceptable cert types */2904if (!WPACKET_start_sub_packet_u8(pkt)2905|| !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {2906SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2907return CON_FUNC_ERROR;2908}29092910if (SSL_USE_SIGALGS(s)) {2911const uint16_t *psigs;2912size_t nl = tls12_get_psigalgs(s, 1, &psigs);29132914if (!WPACKET_start_sub_packet_u16(pkt)2915|| !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)2916|| !tls12_copy_sigalgs(s, pkt, psigs, nl)2917|| !WPACKET_close(pkt)) {2918SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2919return CON_FUNC_ERROR;2920}2921}29222923if (!construct_ca_names(s, get_ca_names(s), pkt)) {2924/* SSLfatal() already called */2925return CON_FUNC_ERROR;2926}29272928done:2929s->certreqs_sent++;2930s->s3.tmp.cert_request = 1;2931return CON_FUNC_SUCCESS;2932}29332934static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)2935{2936#ifndef OPENSSL_NO_PSK2937unsigned char psk[PSK_MAX_PSK_LEN];2938size_t psklen;2939PACKET psk_identity;29402941if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {2942SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2943return 0;2944}2945if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {2946SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);2947return 0;2948}2949if (s->psk_server_callback == NULL) {2950SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);2951return 0;2952}29532954if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {2955SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2956return 0;2957}29582959psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),2960s->session->psk_identity,2961psk, sizeof(psk));29622963if (psklen > PSK_MAX_PSK_LEN) {2964SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2965return 0;2966} else if (psklen == 0) {2967/*2968* PSK related to the given identity not found2969*/2970SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);2971return 0;2972}29732974OPENSSL_free(s->s3.tmp.psk);2975s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);2976OPENSSL_cleanse(psk, psklen);29772978if (s->s3.tmp.psk == NULL) {2979s->s3.tmp.psklen = 0;2980SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2981return 0;2982}29832984s->s3.tmp.psklen = psklen;29852986return 1;2987#else2988/* Should never happen */2989SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2990return 0;2991#endif2992}29932994static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)2995{2996size_t outlen;2997PACKET enc_premaster;2998EVP_PKEY *rsa = NULL;2999unsigned char *rsa_decrypt = NULL;3000int ret = 0;3001EVP_PKEY_CTX *ctx = NULL;3002OSSL_PARAM params[3], *p = params;3003SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);30043005rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;3006if (rsa == NULL) {3007SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);3008return 0;3009}30103011/* SSLv3 and pre-standard DTLS omit the length bytes. */3012if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {3013enc_premaster = *pkt;3014} else {3015if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)3016|| PACKET_remaining(pkt) != 0) {3017SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3018return 0;3019}3020}30213022outlen = SSL_MAX_MASTER_KEY_LENGTH;3023rsa_decrypt = OPENSSL_malloc(outlen);3024if (rsa_decrypt == NULL) {3025SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3026return 0;3027}30283029ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);3030if (ctx == NULL) {3031SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3032goto err;3033}30343035/*3036* We must not leak whether a decryption failure occurs because of3037* Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,3038* section 7.4.7.1). We use the special padding type3039* RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the3040* RSA, check the padding and check that the client version is as expected3041* in the premaster secret. If any of that fails then the function appears3042* to return successfully but with a random result. The call below could3043* still fail if the input is publicly invalid.3044* See https://tools.ietf.org/html/rfc5246#section-7.4.7.13045*/3046if (EVP_PKEY_decrypt_init(ctx) <= 03047|| EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {3048SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3049goto err;3050}30513052*p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,3053(unsigned int *)&s->client_version);3054if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)3055*p++ = OSSL_PARAM_construct_uint(3056OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,3057(unsigned int *)&s->version);3058*p++ = OSSL_PARAM_construct_end();30593060if (!EVP_PKEY_CTX_set_params(ctx, params)3061|| EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,3062PACKET_data(&enc_premaster),3063PACKET_remaining(&enc_premaster))3064<= 0) {3065SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3066goto err;3067}30683069/*3070* This test should never fail (otherwise we should have failed above) but3071* we double check anyway.3072*/3073if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {3074OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);3075SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);3076goto err;3077}30783079/* Also cleanses rsa_decrypt (on success or failure) */3080if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {3081/* SSLfatal() already called */3082goto err;3083}30843085ret = 1;3086err:3087OPENSSL_free(rsa_decrypt);3088EVP_PKEY_CTX_free(ctx);3089return ret;3090}30913092static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)3093{3094EVP_PKEY *skey = NULL;3095unsigned int i;3096const unsigned char *data;3097EVP_PKEY *ckey = NULL;3098int ret = 0;30993100if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {3101SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);3102goto err;3103}3104skey = s->s3.tmp.pkey;3105if (skey == NULL) {3106SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);3107goto err;3108}31093110if (PACKET_remaining(pkt) == 0L) {3111SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);3112goto err;3113}3114if (!PACKET_get_bytes(pkt, &data, i)) {3115/* We already checked we have enough data */3116SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3117goto err;3118}3119ckey = EVP_PKEY_new();3120if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {3121SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);3122goto err;3123}31243125if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {3126SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);3127goto err;3128}31293130if (ssl_derive(s, skey, ckey, 1) == 0) {3131/* SSLfatal() already called */3132goto err;3133}31343135ret = 1;3136EVP_PKEY_free(s->s3.tmp.pkey);3137s->s3.tmp.pkey = NULL;3138err:3139EVP_PKEY_free(ckey);3140return ret;3141}31423143static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)3144{3145EVP_PKEY *skey = s->s3.tmp.pkey;3146EVP_PKEY *ckey = NULL;3147int ret = 0;31483149if (PACKET_remaining(pkt) == 0L) {3150/* We don't support ECDH client auth */3151SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);3152goto err;3153} else {3154unsigned int i;3155const unsigned char *data;31563157/*3158* Get client's public key from encoded point in the3159* ClientKeyExchange message.3160*/31613162/* Get encoded point length */3163if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)3164|| PACKET_remaining(pkt) != 0) {3165SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3166goto err;3167}3168if (skey == NULL) {3169SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);3170goto err;3171}31723173ckey = EVP_PKEY_new();3174if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {3175SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);3176goto err;3177}31783179if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {3180SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);3181goto err;3182}3183}31843185if (ssl_derive(s, skey, ckey, 1) == 0) {3186/* SSLfatal() already called */3187goto err;3188}31893190ret = 1;3191EVP_PKEY_free(s->s3.tmp.pkey);3192s->s3.tmp.pkey = NULL;3193err:3194EVP_PKEY_free(ckey);31953196return ret;3197}31983199static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)3200{3201#ifndef OPENSSL_NO_SRP3202unsigned int i;3203const unsigned char *data;32043205if (!PACKET_get_net_2(pkt, &i)3206|| !PACKET_get_bytes(pkt, &data, i)) {3207SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);3208return 0;3209}3210if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {3211SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);3212return 0;3213}3214if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {3215SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);3216return 0;3217}3218OPENSSL_free(s->session->srp_username);3219s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);3220if (s->session->srp_username == NULL) {3221SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3222return 0;3223}32243225if (!srp_generate_server_master_secret(s)) {3226/* SSLfatal() already called */3227return 0;3228}32293230return 1;3231#else3232/* Should never happen */3233SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3234return 0;3235#endif3236}32373238static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)3239{3240#ifndef OPENSSL_NO_GOST3241EVP_PKEY_CTX *pkey_ctx;3242EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;3243unsigned char premaster_secret[32];3244const unsigned char *start;3245size_t outlen = sizeof(premaster_secret), inlen;3246unsigned long alg_a;3247GOST_KX_MESSAGE *pKX = NULL;3248const unsigned char *ptr;3249int ret = 0;3250SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);32513252/* Get our certificate private key */3253alg_a = s->s3.tmp.new_cipher->algorithm_auth;3254if (alg_a & SSL_aGOST12) {3255/*3256* New GOST ciphersuites have SSL_aGOST01 bit too3257*/3258pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;3259if (pk == NULL) {3260pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;3261}3262if (pk == NULL) {3263pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;3264}3265} else if (alg_a & SSL_aGOST01) {3266pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;3267}32683269pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);3270if (pkey_ctx == NULL) {3271SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3272return 0;3273}3274if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {3275SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3276goto err;3277}3278/*3279* If client certificate is present and is of the same type, maybe3280* use it for key exchange. Don't mind errors from3281* EVP_PKEY_derive_set_peer, because it is completely valid to use a3282* client certificate for authorization only.3283*/3284client_pub_pkey = tls_get_peer_pkey(s);3285if (client_pub_pkey) {3286if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)3287ERR_clear_error();3288}32893290ptr = PACKET_data(pkt);3291/* Some implementations provide extra data in the opaqueBlob3292* We have nothing to do with this blob so we just skip it */3293pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));3294if (pKX == NULL3295|| pKX->kxBlob == NULL3296|| ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {3297SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3298goto err;3299}33003301if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {3302SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);3303goto err;3304}33053306if (PACKET_remaining(pkt) != 0) {3307SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);3308goto err;3309}33103311inlen = pKX->kxBlob->value.sequence->length;3312start = pKX->kxBlob->value.sequence->data;33133314if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,3315inlen)3316<= 0) {3317SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3318goto err;3319}3320/* Generate master secret */3321if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {3322/* SSLfatal() already called */3323goto err;3324}3325/* Check if pubkey from client certificate was used */3326if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,3327NULL)3328> 0)3329s->statem.no_cert_verify = 1;33303331ret = 1;3332err:3333EVP_PKEY_CTX_free(pkey_ctx);3334GOST_KX_MESSAGE_free(pKX);3335return ret;3336#else3337/* Should never happen */3338SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3339return 0;3340#endif3341}33423343static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)3344{3345#ifndef OPENSSL_NO_GOST3346unsigned char rnd_dgst[32];3347EVP_PKEY_CTX *pkey_ctx = NULL;3348EVP_PKEY *pk = NULL;3349unsigned char premaster_secret[32];3350const unsigned char *start = NULL;3351size_t outlen = sizeof(premaster_secret), inlen = 0;3352int ret = 0;3353int cipher_nid = ossl_gost18_cke_cipher_nid(s);3354SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);33553356if (cipher_nid == NID_undef) {3357SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3358return 0;3359}33603361if (ossl_gost_ukm(s, rnd_dgst) <= 0) {3362SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3363goto err;3364}33653366/* Get our certificate private key */3367pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ? s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey : s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;3368if (pk == NULL) {3369SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);3370goto err;3371}33723373pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);3374if (pkey_ctx == NULL) {3375SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3376goto err;3377}3378if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {3379SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3380goto err;3381}33823383/* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */3384if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,3385EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)3386<= 0) {3387SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3388goto err;3389}33903391if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,3392EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)3393<= 0) {3394SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3395goto err;3396}3397inlen = PACKET_remaining(pkt);3398start = PACKET_data(pkt);33993400if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {3401SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);3402goto err;3403}3404/* Generate master secret */3405if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {3406/* SSLfatal() already called */3407goto err;3408}3409ret = 1;34103411err:3412EVP_PKEY_CTX_free(pkey_ctx);3413return ret;3414#else3415/* Should never happen */3416SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3417return 0;3418#endif3419}34203421MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,3422PACKET *pkt)3423{3424unsigned long alg_k;34253426alg_k = s->s3.tmp.new_cipher->algorithm_mkey;34273428/* For PSK parse and retrieve identity, obtain PSK key */3429if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {3430/* SSLfatal() already called */3431goto err;3432}34333434if (alg_k & SSL_kPSK) {3435/* Identity extracted earlier: should be nothing left */3436if (PACKET_remaining(pkt) != 0) {3437SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3438goto err;3439}3440/* PSK handled by ssl_generate_master_secret */3441if (!ssl_generate_master_secret(s, NULL, 0, 0)) {3442/* SSLfatal() already called */3443goto err;3444}3445} else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {3446if (!tls_process_cke_rsa(s, pkt)) {3447/* SSLfatal() already called */3448goto err;3449}3450} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {3451if (!tls_process_cke_dhe(s, pkt)) {3452/* SSLfatal() already called */3453goto err;3454}3455} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {3456if (!tls_process_cke_ecdhe(s, pkt)) {3457/* SSLfatal() already called */3458goto err;3459}3460} else if (alg_k & SSL_kSRP) {3461if (!tls_process_cke_srp(s, pkt)) {3462/* SSLfatal() already called */3463goto err;3464}3465} else if (alg_k & SSL_kGOST) {3466if (!tls_process_cke_gost(s, pkt)) {3467/* SSLfatal() already called */3468goto err;3469}3470} else if (alg_k & SSL_kGOST18) {3471if (!tls_process_cke_gost18(s, pkt)) {3472/* SSLfatal() already called */3473goto err;3474}3475} else {3476SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);3477goto err;3478}34793480return MSG_PROCESS_CONTINUE_PROCESSING;3481err:3482#ifndef OPENSSL_NO_PSK3483OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);3484s->s3.tmp.psk = NULL;3485s->s3.tmp.psklen = 0;3486#endif3487return MSG_PROCESS_ERROR;3488}34893490WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,3491WORK_STATE wst)3492{3493#ifndef OPENSSL_NO_SCTP3494if (wst == WORK_MORE_A) {3495if (SSL_CONNECTION_IS_DTLS(s)) {3496unsigned char sctpauthkey[64];3497char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];3498size_t labellen;3499/*3500* Add new shared key for SCTP-Auth, will be ignored if no SCTP3501* used.3502*/3503memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,3504sizeof(DTLS1_SCTP_AUTH_LABEL));35053506/* Don't include the terminating zero. */3507labellen = sizeof(labelbuffer) - 1;3508if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)3509labellen += 1;35103511if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),3512sctpauthkey,3513sizeof(sctpauthkey), labelbuffer,3514labellen, NULL, 0,35150)3516<= 0) {3517SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3518return WORK_ERROR;3519}35203521BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,3522sizeof(sctpauthkey), sctpauthkey);3523}3524}3525#endif35263527if (s->statem.no_cert_verify || !received_client_cert(s)) {3528/*3529* No certificate verify or no peer certificate so we no longer need3530* the handshake_buffer3531*/3532if (!ssl3_digest_cached_records(s, 0)) {3533/* SSLfatal() already called */3534return WORK_ERROR;3535}3536return WORK_FINISHED_CONTINUE;3537} else {3538if (!s->s3.handshake_buffer) {3539SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3540return WORK_ERROR;3541}3542/*3543* For sigalgs freeze the handshake buffer. If we support3544* extms we've done this already so this is a no-op3545*/3546if (!ssl3_digest_cached_records(s, 1)) {3547/* SSLfatal() already called */3548return WORK_ERROR;3549}3550}35513552return WORK_FINISHED_CONTINUE;3553}35543555MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)3556{3557MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3558SSL_SESSION *new_sess = NULL;3559EVP_PKEY *peer_rpk = NULL;35603561if (!tls_process_rpk(sc, pkt, &peer_rpk)) {3562/* SSLfatal already called */3563goto err;3564}35653566if (peer_rpk == NULL) {3567if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)3568&& (sc->verify_mode & SSL_VERIFY_PEER)) {3569SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,3570SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);3571goto err;3572}3573} else {3574if (ssl_verify_rpk(sc, peer_rpk) <= 0) {3575SSLfatal(sc, ssl_x509err2alert(sc->verify_result),3576SSL_R_CERTIFICATE_VERIFY_FAILED);3577goto err;3578}3579}35803581/*3582* Sessions must be immutable once they go into the session cache. Otherwise3583* we can get multi-thread problems. Therefore we don't "update" sessions,3584* we replace them with a duplicate. Here, we need to do this every time3585* a new RPK (or certificate) is received via post-handshake authentication,3586* as the session may have already gone into the session cache.3587*/35883589if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {3590if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {3591SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);3592goto err;3593}35943595SSL_SESSION_free(sc->session);3596sc->session = new_sess;3597}35983599/* Ensure there is no peer/peer_chain */3600X509_free(sc->session->peer);3601sc->session->peer = NULL;3602sk_X509_pop_free(sc->session->peer_chain, X509_free);3603sc->session->peer_chain = NULL;3604/* Save RPK */3605EVP_PKEY_free(sc->session->peer_rpk);3606sc->session->peer_rpk = peer_rpk;3607peer_rpk = NULL;36083609sc->session->verify_result = sc->verify_result;36103611/*3612* Freeze the handshake buffer. For <TLS1.3 we do this after the CKE3613* message3614*/3615if (SSL_CONNECTION_IS_TLS13(sc)) {3616if (!ssl3_digest_cached_records(sc, 1)) {3617/* SSLfatal() already called */3618goto err;3619}36203621/* Save the current hash state for when we receive the CertificateVerify */3622if (!ssl_handshake_hash(sc, sc->cert_verify_hash,3623sizeof(sc->cert_verify_hash),3624&sc->cert_verify_hash_len)) {3625/* SSLfatal() already called */;3626goto err;3627}36283629/* resend session tickets */3630sc->sent_tickets = 0;3631}36323633ret = MSG_PROCESS_CONTINUE_READING;36343635err:3636EVP_PKEY_free(peer_rpk);3637return ret;3638}36393640MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,3641PACKET *pkt)3642{3643int i;3644MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3645X509 *x = NULL;3646unsigned long l;3647const unsigned char *certstart, *certbytes;3648STACK_OF(X509) *sk = NULL;3649PACKET spkt, context;3650size_t chainidx;3651SSL_SESSION *new_sess = NULL;3652SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);36533654/*3655* To get this far we must have read encrypted data from the client. We no3656* longer tolerate unencrypted alerts. This is ignored if less than TLSv1.33657*/3658if (s->rlayer.rrlmethod->set_plain_alerts != NULL)3659s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);36603661if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)3662return tls_process_client_rpk(s, pkt);36633664if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {3665SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,3666SSL_R_UNKNOWN_CERTIFICATE_TYPE);3667goto err;3668}36693670if ((sk = sk_X509_new_null()) == NULL) {3671SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3672goto err;3673}36743675if (SSL_CONNECTION_IS_TLS13(s)3676&& (!PACKET_get_length_prefixed_1(pkt, &context)3677|| (s->pha_context == NULL && PACKET_remaining(&context) != 0)3678|| (s->pha_context != NULL3679&& !PACKET_equal(&context, s->pha_context,3680s->pha_context_len)))) {3681SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);3682goto err;3683}36843685if (!PACKET_get_length_prefixed_3(pkt, &spkt)3686|| PACKET_remaining(pkt) != 0) {3687SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3688goto err;3689}36903691for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {3692if (!PACKET_get_net_3(&spkt, &l)3693|| !PACKET_get_bytes(&spkt, &certbytes, l)) {3694SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);3695goto err;3696}36973698certstart = certbytes;3699x = X509_new_ex(sctx->libctx, sctx->propq);3700if (x == NULL) {3701SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);3702goto err;3703}3704if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {3705SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);3706goto err;3707}37083709if (certbytes != (certstart + l)) {3710SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);3711goto err;3712}37133714if (SSL_CONNECTION_IS_TLS13(s)) {3715RAW_EXTENSION *rawexts = NULL;3716PACKET extensions;37173718if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {3719SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);3720goto err;3721}3722if (!tls_collect_extensions(s, &extensions,3723SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,3724NULL, chainidx == 0)3725|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,3726rawexts, x, chainidx,3727PACKET_remaining(&spkt) == 0)) {3728OPENSSL_free(rawexts);3729goto err;3730}3731OPENSSL_free(rawexts);3732}37333734if (!sk_X509_push(sk, x)) {3735SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3736goto err;3737}3738x = NULL;3739}37403741if (sk_X509_num(sk) <= 0) {3742/* TLS does not mind 0 certs returned */3743if (s->version == SSL3_VERSION) {3744SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3745SSL_R_NO_CERTIFICATES_RETURNED);3746goto err;3747}3748/* Fail for TLS only if we required a certificate */3749else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {3750SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,3751SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);3752goto err;3753}3754/* No client certificate so digest cached records */3755if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {3756/* SSLfatal() already called */3757goto err;3758}3759} else {3760EVP_PKEY *pkey;3761i = ssl_verify_cert_chain(s, sk);3762if (i <= 0) {3763SSLfatal(s, ssl_x509err2alert(s->verify_result),3764SSL_R_CERTIFICATE_VERIFY_FAILED);3765goto err;3766}3767pkey = X509_get0_pubkey(sk_X509_value(sk, 0));3768if (pkey == NULL) {3769SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3770SSL_R_UNKNOWN_CERTIFICATE_TYPE);3771goto err;3772}3773}37743775/*3776* Sessions must be immutable once they go into the session cache. Otherwise3777* we can get multi-thread problems. Therefore we don't "update" sessions,3778* we replace them with a duplicate. Here, we need to do this every time3779* a new certificate is received via post-handshake authentication, as the3780* session may have already gone into the session cache.3781*/37823783if (s->post_handshake_auth == SSL_PHA_REQUESTED) {3784if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {3785SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);3786goto err;3787}37883789SSL_SESSION_free(s->session);3790s->session = new_sess;3791}37923793X509_free(s->session->peer);3794s->session->peer = sk_X509_shift(sk);3795s->session->verify_result = s->verify_result;37963797OSSL_STACK_OF_X509_free(s->session->peer_chain);3798s->session->peer_chain = sk;3799sk = NULL;3800/* Ensure there is no RPK */3801EVP_PKEY_free(s->session->peer_rpk);3802s->session->peer_rpk = NULL;38033804/*3805* Freeze the handshake buffer. For <TLS1.3 we do this after the CKE3806* message3807*/3808if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {3809/* SSLfatal() already called */3810goto err;3811}38123813/*3814* Inconsistency alert: cert_chain does *not* include the peer's own3815* certificate, while we do include it in statem_clnt.c3816*/38173818/* Save the current hash state for when we receive the CertificateVerify */3819if (SSL_CONNECTION_IS_TLS13(s)) {3820if (!ssl_handshake_hash(s, s->cert_verify_hash,3821sizeof(s->cert_verify_hash),3822&s->cert_verify_hash_len)) {3823/* SSLfatal() already called */3824goto err;3825}38263827/* Resend session tickets */3828s->sent_tickets = 0;3829}38303831ret = MSG_PROCESS_CONTINUE_READING;38323833err:3834X509_free(x);3835OSSL_STACK_OF_X509_free(sk);3836return ret;3837}38383839#ifndef OPENSSL_NO_COMP_ALG3840MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)3841{3842MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;3843PACKET tmppkt;3844BUF_MEM *buf = BUF_MEM_new();38453846if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)3847ret = tls_process_client_certificate(sc, &tmppkt);38483849BUF_MEM_free(buf);3850return ret;3851}3852#endif38533854CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)3855{3856CERT_PKEY *cpk = s->s3.tmp.cert;38573858if (cpk == NULL) {3859SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3860return CON_FUNC_ERROR;3861}38623863/*3864* In TLSv1.3 the certificate chain is always preceded by a 0 length context3865* for the server Certificate message3866*/3867if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {3868SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3869return CON_FUNC_ERROR;3870}3871switch (s->ext.server_cert_type) {3872case TLSEXT_cert_type_rpk:3873if (!tls_output_rpk(s, pkt, cpk)) {3874/* SSLfatal() already called */3875return 0;3876}3877break;3878case TLSEXT_cert_type_x509:3879if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {3880/* SSLfatal() already called */3881return 0;3882}3883break;3884default:3885SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3886return 0;3887}38883889return CON_FUNC_SUCCESS;3890}38913892#ifndef OPENSSL_NO_COMP_ALG3893CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)3894{3895int alg = get_compressed_certificate_alg(sc);3896OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];38973898if (!ossl_assert(cc != NULL)) {3899SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3900return 0;3901}3902/*3903* Server can't compress on-demand3904* Use pre-compressed certificate3905*/3906if (!WPACKET_put_bytes_u16(pkt, alg)3907|| !WPACKET_put_bytes_u24(pkt, cc->orig_len)3908|| !WPACKET_start_sub_packet_u24(pkt)3909|| !WPACKET_memcpy(pkt, cc->data, cc->len)3910|| !WPACKET_close(pkt))3911return 0;39123913sc->s3.tmp.cert->cert_comp_used++;3914return 1;3915}3916#endif39173918static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,3919uint32_t age_add, unsigned char *tick_nonce)3920{3921uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);39223923/*3924* Ticket lifetime hint:3925* In TLSv1.3 we reset the "time" field above, and always specify the3926* timeout, limited to a 1 week period per RFC8446.3927* For TLSv1.2 this is advisory only and we leave this unspecified for3928* resumed session (for simplicity).3929*/3930#define ONE_WEEK_SEC (7 * 24 * 60 * 60)39313932if (SSL_CONNECTION_IS_TLS13(s)) {3933if (ossl_time_compare(s->session->timeout,3934ossl_seconds2time(ONE_WEEK_SEC))3935> 0)3936timeout = ONE_WEEK_SEC;3937} else if (s->hit)3938timeout = 0;39393940if (!WPACKET_put_bytes_u32(pkt, timeout)) {3941SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3942return 0;3943}39443945if (SSL_CONNECTION_IS_TLS13(s)) {3946if (!WPACKET_put_bytes_u32(pkt, age_add)3947|| !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {3948SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3949return 0;3950}3951}39523953/* Start the sub-packet for the actual ticket data */3954if (!WPACKET_start_sub_packet_u16(pkt)) {3955SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3956return 0;3957}39583959return 1;3960}39613962static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,3963WPACKET *pkt,3964uint32_t age_add,3965unsigned char *tick_nonce)3966{3967unsigned char *senc = NULL;3968EVP_CIPHER_CTX *ctx = NULL;3969SSL_HMAC *hctx = NULL;3970unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;3971const unsigned char *const_p;3972int len, slen_full, slen, lenfinal;3973SSL_SESSION *sess;3974size_t hlen;3975SSL_CTX *tctx = s->session_ctx;3976unsigned char iv[EVP_MAX_IV_LENGTH];3977unsigned char key_name[TLSEXT_KEYNAME_LENGTH];3978int iv_len;3979CON_FUNC_RETURN ok = CON_FUNC_ERROR;3980size_t macoffset, macendoffset;3981SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);3982SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);39833984/* get session encoding length */3985slen_full = i2d_SSL_SESSION(s->session, NULL);3986/*3987* Some length values are 16 bits, so forget it if session is too3988* long3989*/3990if (slen_full == 0 || slen_full > 0xFF00) {3991SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3992goto err;3993}3994senc = OPENSSL_malloc(slen_full);3995if (senc == NULL) {3996SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3997goto err;3998}39994000ctx = EVP_CIPHER_CTX_new();4001if (ctx == NULL) {4002SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);4003goto err;4004}4005hctx = ssl_hmac_new(tctx);4006if (hctx == NULL) {4007SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);4008goto err;4009}40104011p = senc;4012if (!i2d_SSL_SESSION(s->session, &p)) {4013SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4014goto err;4015}40164017/*4018* create a fresh copy (not shared with other threads) to clean up4019*/4020const_p = senc;4021sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,4022sctx->propq);4023if (sess == NULL) {4024SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4025goto err;4026}40274028slen = i2d_SSL_SESSION(sess, NULL);4029if (slen == 0 || slen > slen_full) {4030/* shouldn't ever happen */4031SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4032SSL_SESSION_free(sess);4033goto err;4034}4035p = senc;4036if (!i2d_SSL_SESSION(sess, &p)) {4037SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4038SSL_SESSION_free(sess);4039goto err;4040}4041SSL_SESSION_free(sess);40424043/*4044* Initialize HMAC and cipher contexts. If callback present it does4045* all the work otherwise use generated values from parent ctx.4046*/4047#ifndef OPENSSL_NO_DEPRECATED_3_04048if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)4049#else4050if (tctx->ext.ticket_key_evp_cb != NULL)4051#endif4052{4053int ret = 0;40544055if (tctx->ext.ticket_key_evp_cb != NULL)4056ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,4057ssl_hmac_get0_EVP_MAC_CTX(hctx),40581);4059#ifndef OPENSSL_NO_DEPRECATED_3_04060else if (tctx->ext.ticket_key_cb != NULL)4061/* if 0 is returned, write an empty ticket */4062ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,4063ssl_hmac_get0_HMAC_CTX(hctx), 1);4064#endif40654066if (ret == 0) {4067/*4068* In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 04069* length ticket is not allowed so we abort construction of the4070* ticket4071*/4072if (SSL_CONNECTION_IS_TLS13(s)) {4073ok = CON_FUNC_DONT_SEND;4074goto err;4075}4076/* Put timeout and length */4077if (!WPACKET_put_bytes_u32(pkt, 0)4078|| !WPACKET_put_bytes_u16(pkt, 0)) {4079SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4080goto err;4081}4082OPENSSL_free(senc);4083EVP_CIPHER_CTX_free(ctx);4084ssl_hmac_free(hctx);4085return CON_FUNC_SUCCESS;4086}4087if (ret < 0) {4088SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);4089goto err;4090}4091iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);4092if (iv_len < 0) {4093SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4094goto err;4095}4096} else {4097EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",4098sctx->propq);40994100if (cipher == NULL) {4101/* Error is already recorded */4102SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);4103goto err;4104}41054106iv_len = EVP_CIPHER_get_iv_length(cipher);4107if (iv_len < 04108|| RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 04109|| !EVP_EncryptInit_ex(ctx, cipher, NULL,4110tctx->ext.secure->tick_aes_key, iv)4111|| !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,4112sizeof(tctx->ext.secure->tick_hmac_key),4113"SHA256")) {4114EVP_CIPHER_free(cipher);4115SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4116goto err;4117}4118EVP_CIPHER_free(cipher);4119memcpy(key_name, tctx->ext.tick_key_name,4120sizeof(tctx->ext.tick_key_name));4121}41224123if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {4124/* SSLfatal() already called */4125goto err;4126}41274128if (!WPACKET_get_total_written(pkt, &macoffset)4129/* Output key name */4130|| !WPACKET_memcpy(pkt, key_name, sizeof(key_name))4131/* output IV */4132|| !WPACKET_memcpy(pkt, iv, iv_len)4133|| !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,4134&encdata1)4135/* Encrypt session data */4136|| !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)4137|| !WPACKET_allocate_bytes(pkt, len, &encdata2)4138|| encdata1 != encdata24139|| !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)4140|| !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)4141|| encdata1 + len != encdata24142|| len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH4143|| !WPACKET_get_total_written(pkt, &macendoffset)4144|| !ssl_hmac_update(hctx,4145(unsigned char *)s->init_buf->data + macoffset,4146macendoffset - macoffset)4147|| !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)4148|| !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)4149|| hlen > EVP_MAX_MD_SIZE4150|| !WPACKET_allocate_bytes(pkt, hlen, &macdata2)4151|| macdata1 != macdata2) {4152SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4153goto err;4154}41554156/* Close the sub-packet created by create_ticket_prequel() */4157if (!WPACKET_close(pkt)) {4158SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4159goto err;4160}41614162ok = CON_FUNC_SUCCESS;4163err:4164OPENSSL_free(senc);4165EVP_CIPHER_CTX_free(ctx);4166ssl_hmac_free(hctx);4167return ok;4168}41694170static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,4171uint32_t age_add,4172unsigned char *tick_nonce)4173{4174if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {4175/* SSLfatal() already called */4176return 0;4177}41784179if (!WPACKET_memcpy(pkt, s->session->session_id,4180s->session->session_id_length)4181|| !WPACKET_close(pkt)) {4182SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4183return 0;4184}41854186return 1;4187}41884189static void tls_update_ticket_counts(SSL_CONNECTION *s)4190{4191/*4192* Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|4193* gets reset to 0 if we send more tickets following a post-handshake4194* auth, but |next_ticket_nonce| does not. If we're sending extra4195* tickets, decrement the count of pending extra tickets.4196*/4197s->sent_tickets++;4198s->next_ticket_nonce++;4199if (s->ext.extra_tickets_expected > 0)4200s->ext.extra_tickets_expected--;4201}42024203CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)4204{4205SSL_CTX *tctx = s->session_ctx;4206unsigned char tick_nonce[TICKET_NONCE_SIZE];4207union {4208unsigned char age_add_c[sizeof(uint32_t)];4209uint32_t age_add;4210} age_add_u;4211CON_FUNC_RETURN ret = CON_FUNC_ERROR;42124213age_add_u.age_add = 0;42144215if (SSL_CONNECTION_IS_TLS13(s)) {4216size_t i, hashlen;4217uint64_t nonce;4218/* ASCII: "resumption", in hex for EBCDIC compatibility */4219static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,42200x70, 0x74, 0x69, 0x6F, 0x6E };4221const EVP_MD *md = ssl_handshake_md(s);4222int hashleni = EVP_MD_get_size(md);42234224/* Ensure cast to size_t is safe */4225if (!ossl_assert(hashleni > 0)) {4226SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4227goto err;4228}4229hashlen = (size_t)hashleni;42304231/*4232* If we already sent one NewSessionTicket, or we resumed then4233* s->session may already be in a cache and so we must not modify it.4234* Instead we need to take a copy of it and modify that.4235*/4236if (s->sent_tickets != 0 || s->hit) {4237SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);42384239if (new_sess == NULL) {4240/* SSLfatal already called */4241goto err;4242}42434244SSL_SESSION_free(s->session);4245s->session = new_sess;4246}42474248if (!ssl_generate_session_id(s, s->session)) {4249/* SSLfatal() already called */4250goto err;4251}4252if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,4253age_add_u.age_add_c, sizeof(age_add_u), 0)4254<= 0) {4255SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4256goto err;4257}4258s->session->ext.tick_age_add = age_add_u.age_add;42594260nonce = s->next_ticket_nonce;4261for (i = TICKET_NONCE_SIZE; i > 0; i--) {4262tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);4263nonce >>= 8;4264}42654266if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,4267nonce_label,4268sizeof(nonce_label),4269tick_nonce,4270TICKET_NONCE_SIZE,4271s->session->master_key,4272hashlen, 1)) {4273/* SSLfatal() already called */4274goto err;4275}4276s->session->master_key_length = hashlen;42774278s->session->time = ossl_time_now();4279ssl_session_calculate_timeout(s->session);4280if (s->s3.alpn_selected != NULL) {4281OPENSSL_free(s->session->ext.alpn_selected);4282s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);4283if (s->session->ext.alpn_selected == NULL) {4284s->session->ext.alpn_selected_len = 0;4285SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);4286goto err;4287}4288s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;4289}4290s->session->ext.max_early_data = s->max_early_data;4291}42924293if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s), tctx->ticket_cb_data) == 0) {4294SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4295goto err;4296}4297/*4298* If we are using anti-replay protection then we behave as if4299* SSL_OP_NO_TICKET is set - we are caching tickets anyway so there4300* is no point in using full stateless tickets.4301*/4302if (SSL_CONNECTION_IS_TLS13(s)4303&& ((s->options & SSL_OP_NO_TICKET) != 04304|| (s->max_early_data > 04305&& (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {4306if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {4307/* SSLfatal() already called */4308goto err;4309}4310} else {4311CON_FUNC_RETURN tmpret;43124313tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,4314tick_nonce);4315if (tmpret != CON_FUNC_SUCCESS) {4316if (tmpret == CON_FUNC_DONT_SEND) {4317/* Non-fatal. Abort construction but continue */4318ret = CON_FUNC_DONT_SEND;4319/* We count this as a success so update the counts anwyay */4320tls_update_ticket_counts(s);4321}4322/* else SSLfatal() already called */4323goto err;4324}4325}43264327if (SSL_CONNECTION_IS_TLS13(s)) {4328if (!tls_construct_extensions(s, pkt,4329SSL_EXT_TLS1_3_NEW_SESSION_TICKET,4330NULL, 0)) {4331/* SSLfatal() already called */4332goto err;4333}4334tls_update_ticket_counts(s);4335ssl_update_cache(s, SSL_SESS_CACHE_SERVER);4336}43374338ret = CON_FUNC_SUCCESS;4339err:4340return ret;4341}43424343/*4344* In TLSv1.3 this is called from the extensions code, otherwise it is used to4345* create a separate message. Returns 1 on success or 0 on failure.4346*/4347int tls_construct_cert_status_body(SSL_CONNECTION *s, WPACKET *pkt)4348{4349if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)4350|| !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,4351s->ext.ocsp.resp_len)) {4352SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4353return 0;4354}43554356return 1;4357}43584359CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)4360{4361if (!tls_construct_cert_status_body(s, pkt)) {4362/* SSLfatal() already called */4363return CON_FUNC_ERROR;4364}43654366return CON_FUNC_SUCCESS;4367}43684369#ifndef OPENSSL_NO_NEXTPROTONEG4370/*4371* tls_process_next_proto reads a Next Protocol Negotiation handshake message.4372* It sets the next_proto member in s if found4373*/4374MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)4375{4376PACKET next_proto, padding;4377size_t next_proto_len;43784379/*-4380* The payload looks like:4381* uint8 proto_len;4382* uint8 proto[proto_len];4383* uint8 padding_len;4384* uint8 padding[padding_len];4385*/4386if (!PACKET_get_length_prefixed_1(pkt, &next_proto)4387|| !PACKET_get_length_prefixed_1(pkt, &padding)4388|| PACKET_remaining(pkt) > 0) {4389SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4390return MSG_PROCESS_ERROR;4391}43924393if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {4394s->ext.npn_len = 0;4395SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4396return MSG_PROCESS_ERROR;4397}43984399s->ext.npn_len = (unsigned char)next_proto_len;44004401return MSG_PROCESS_CONTINUE_READING;4402}4403#endif44044405static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,4406WPACKET *pkt)4407{4408if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,4409NULL, 0)) {4410/* SSLfatal() already called */4411return CON_FUNC_ERROR;4412}44134414return CON_FUNC_SUCCESS;4415}44164417MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)4418{4419if (PACKET_remaining(pkt) != 0) {4420SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4421return MSG_PROCESS_ERROR;4422}44234424if (s->early_data_state != SSL_EARLY_DATA_READING4425&& s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {4426SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4427return MSG_PROCESS_ERROR;4428}44294430/*4431* EndOfEarlyData signals a key change so the end of the message must be on4432* a record boundary.4433*/4434if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {4435SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);4436return MSG_PROCESS_ERROR;4437}44384439s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;4440if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,4441SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {4442/* SSLfatal() already called */4443return MSG_PROCESS_ERROR;4444}44454446return MSG_PROCESS_CONTINUE_READING;4447}444844494450