Path: blob/main/crypto/openssl/ssl/statem/statem_clnt.c
105254 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 <stdio.h>12#include <time.h>13#include <assert.h>14#include "../ssl_local.h"15#include "statem_local.h"16#include <openssl/buffer.h>17#include <openssl/rand.h>18#include <openssl/objects.h>19#include <openssl/evp.h>20#include <openssl/md5.h>21#include <openssl/dh.h>22#include <openssl/rsa.h>23#include <openssl/bn.h>24#include <openssl/engine.h>25#include <openssl/trace.h>26#include <openssl/core_names.h>27#include <openssl/param_build.h>28#include "internal/cryptlib.h"29#include "internal/comp.h"30#include "internal/ssl_unwrap.h"3132static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,33PACKET *pkt);34static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,35PACKET *pkt);3637static ossl_inline int cert_req_allowed(SSL_CONNECTION *s);38static int key_exchange_expected(SSL_CONNECTION *s);39static int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,40WPACKET *pkt);4142static ossl_inline int received_server_cert(SSL_CONNECTION *sc)43{44return sc->session->peer_rpk != NULL || sc->session->peer != NULL;45}4647/*48* Is a CertificateRequest message allowed at the moment or not?49*50* Return values are:51* 1: Yes52* 0: No53*/54static ossl_inline int cert_req_allowed(SSL_CONNECTION *s)55{56/* TLS does not like anon-DH with client cert */57if ((s->version > SSL3_VERSION58&& (s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL))59|| (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))60return 0;6162return 1;63}6465/*66* Should we expect the ServerKeyExchange message or not?67*68* Return values are:69* 1: Yes70* 0: No71*/72static int key_exchange_expected(SSL_CONNECTION *s)73{74long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;7576/*77* Can't skip server key exchange if this is an ephemeral78* ciphersuite or for SRP79*/80if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK | SSL_kSRP)) {81return 1;82}8384return 0;85}8687/*88* ossl_statem_client_read_transition() encapsulates the logic for the allowed89* handshake state transitions when a TLS1.3 client is reading messages from the90* server. The message type that the server has sent is provided in |mt|. The91* current state is in |s->statem.hand_state|.92*93* Return values are 1 for success (transition allowed) and 0 on error94* (transition not allowed)95*/96static int ossl_statem_client13_read_transition(SSL_CONNECTION *s, int mt)97{98OSSL_STATEM *st = &s->statem;99100/*101* Note: There is no case for TLS_ST_CW_CLNT_HELLO, because we haven't102* yet negotiated TLSv1.3 at that point so that is handled by103* ossl_statem_client_read_transition()104*/105106switch (st->hand_state) {107default:108break;109110case TLS_ST_CW_CLNT_HELLO:111/*112* This must a ClientHello following a HelloRetryRequest, so the only113* thing we can get now is a ServerHello.114*/115if (mt == SSL3_MT_SERVER_HELLO) {116st->hand_state = TLS_ST_CR_SRVR_HELLO;117return 1;118}119break;120121case TLS_ST_CR_SRVR_HELLO:122if (mt == SSL3_MT_ENCRYPTED_EXTENSIONS) {123st->hand_state = TLS_ST_CR_ENCRYPTED_EXTENSIONS;124return 1;125}126break;127128case TLS_ST_CR_ENCRYPTED_EXTENSIONS:129if (s->hit) {130if (mt == SSL3_MT_FINISHED) {131st->hand_state = TLS_ST_CR_FINISHED;132return 1;133}134} else {135if (mt == SSL3_MT_CERTIFICATE_REQUEST) {136st->hand_state = TLS_ST_CR_CERT_REQ;137return 1;138}139if (mt == SSL3_MT_CERTIFICATE) {140st->hand_state = TLS_ST_CR_CERT;141return 1;142}143#ifndef OPENSSL_NO_COMP_ALG144if (mt == SSL3_MT_COMPRESSED_CERTIFICATE145&& s->ext.compress_certificate_sent) {146st->hand_state = TLS_ST_CR_COMP_CERT;147return 1;148}149#endif150}151break;152153case TLS_ST_CR_CERT_REQ:154if (mt == SSL3_MT_CERTIFICATE) {155st->hand_state = TLS_ST_CR_CERT;156return 1;157}158#ifndef OPENSSL_NO_COMP_ALG159if (mt == SSL3_MT_COMPRESSED_CERTIFICATE160&& s->ext.compress_certificate_sent) {161st->hand_state = TLS_ST_CR_COMP_CERT;162return 1;163}164#endif165break;166167case TLS_ST_CR_CERT:168case TLS_ST_CR_COMP_CERT:169if (mt == SSL3_MT_CERTIFICATE_VERIFY) {170st->hand_state = TLS_ST_CR_CERT_VRFY;171return 1;172}173break;174175case TLS_ST_CR_CERT_VRFY:176if (mt == SSL3_MT_FINISHED) {177st->hand_state = TLS_ST_CR_FINISHED;178return 1;179}180break;181182case TLS_ST_OK:183if (mt == SSL3_MT_NEWSESSION_TICKET) {184st->hand_state = TLS_ST_CR_SESSION_TICKET;185return 1;186}187if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {188st->hand_state = TLS_ST_CR_KEY_UPDATE;189return 1;190}191if (mt == SSL3_MT_CERTIFICATE_REQUEST) {192#if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION193/* Restore digest for PHA before adding message.*/194#error Internal DTLS version error195#endif196if (!SSL_CONNECTION_IS_DTLS(s)197&& s->post_handshake_auth == SSL_PHA_EXT_SENT) {198s->post_handshake_auth = SSL_PHA_REQUESTED;199/*200* In TLS, this is called before the message is added to the201* digest. In DTLS, this is expected to be called after adding202* to the digest. Either move the digest restore, or add the203* message here after the swap, or do it after the clientFinished?204*/205if (!tls13_restore_handshake_digest_for_pha(s)) {206/* SSLfatal() already called */207return 0;208}209st->hand_state = TLS_ST_CR_CERT_REQ;210return 1;211}212}213break;214}215216/* No valid transition found */217return 0;218}219220/*221* ossl_statem_client_read_transition() encapsulates the logic for the allowed222* handshake state transitions when the client is reading messages from the223* server. The message type that the server has sent is provided in |mt|. The224* current state is in |s->statem.hand_state|.225*226* Return values are 1 for success (transition allowed) and 0 on error227* (transition not allowed)228*/229int ossl_statem_client_read_transition(SSL_CONNECTION *s, int mt)230{231OSSL_STATEM *st = &s->statem;232int ske_expected;233234/*235* Note that after writing the first ClientHello we don't know what version236* we are going to negotiate yet, so we don't take this branch until later.237*/238if (SSL_CONNECTION_IS_TLS13(s)) {239if (!ossl_statem_client13_read_transition(s, mt))240goto err;241return 1;242}243244switch (st->hand_state) {245default:246break;247248case TLS_ST_CW_CLNT_HELLO:249if (mt == SSL3_MT_SERVER_HELLO) {250st->hand_state = TLS_ST_CR_SRVR_HELLO;251return 1;252}253254if (SSL_CONNECTION_IS_DTLS(s)) {255if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {256st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;257return 1;258}259}260break;261262case TLS_ST_EARLY_DATA:263/*264* We've not actually selected TLSv1.3 yet, but we have sent early265* data. The only thing allowed now is a ServerHello or a266* HelloRetryRequest.267*/268if (mt == SSL3_MT_SERVER_HELLO) {269st->hand_state = TLS_ST_CR_SRVR_HELLO;270return 1;271}272break;273274case TLS_ST_CR_SRVR_HELLO:275if (s->hit) {276if (s->ext.ticket_expected) {277if (mt == SSL3_MT_NEWSESSION_TICKET) {278st->hand_state = TLS_ST_CR_SESSION_TICKET;279return 1;280}281} else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {282st->hand_state = TLS_ST_CR_CHANGE;283return 1;284}285} else {286if (SSL_CONNECTION_IS_DTLS(s)287&& mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {288st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;289return 1;290} else if (s->version >= TLS1_VERSION291&& s->ext.session_secret_cb != NULL292&& s->session->ext.tick != NULL293&& mt == SSL3_MT_CHANGE_CIPHER_SPEC) {294/*295* Normally, we can tell if the server is resuming the session296* from the session ID. EAP-FAST (RFC 4851), however, relies on297* the next server message after the ServerHello to determine if298* the server is resuming.299*/300s->hit = 1;301st->hand_state = TLS_ST_CR_CHANGE;302return 1;303} else if (!(s->s3.tmp.new_cipher->algorithm_auth304& (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {305if (mt == SSL3_MT_CERTIFICATE) {306st->hand_state = TLS_ST_CR_CERT;307return 1;308}309} else {310ske_expected = key_exchange_expected(s);311/* SKE is optional for some PSK ciphersuites */312if (ske_expected313|| ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)314&& mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {315if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {316st->hand_state = TLS_ST_CR_KEY_EXCH;317return 1;318}319} else if (mt == SSL3_MT_CERTIFICATE_REQUEST320&& cert_req_allowed(s)) {321st->hand_state = TLS_ST_CR_CERT_REQ;322return 1;323} else if (mt == SSL3_MT_SERVER_DONE) {324st->hand_state = TLS_ST_CR_SRVR_DONE;325return 1;326}327}328}329break;330331case TLS_ST_CR_CERT:332case TLS_ST_CR_COMP_CERT:333/*334* The CertificateStatus message is optional even if335* |ext.status_expected| is set336*/337if (s->ext.status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {338st->hand_state = TLS_ST_CR_CERT_STATUS;339return 1;340}341/* Fall through */342343case TLS_ST_CR_CERT_STATUS:344ske_expected = key_exchange_expected(s);345/* SKE is optional for some PSK ciphersuites */346if (ske_expected || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK) && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {347if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {348st->hand_state = TLS_ST_CR_KEY_EXCH;349return 1;350}351goto err;352}353/* Fall through */354355case TLS_ST_CR_KEY_EXCH:356if (mt == SSL3_MT_CERTIFICATE_REQUEST) {357if (cert_req_allowed(s)) {358st->hand_state = TLS_ST_CR_CERT_REQ;359return 1;360}361goto err;362}363/* Fall through */364365case TLS_ST_CR_CERT_REQ:366if (mt == SSL3_MT_SERVER_DONE) {367st->hand_state = TLS_ST_CR_SRVR_DONE;368return 1;369}370break;371372case TLS_ST_CW_FINISHED:373if (s->ext.ticket_expected) {374if (mt == SSL3_MT_NEWSESSION_TICKET) {375st->hand_state = TLS_ST_CR_SESSION_TICKET;376return 1;377}378} else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {379st->hand_state = TLS_ST_CR_CHANGE;380return 1;381}382break;383384case TLS_ST_CR_SESSION_TICKET:385if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {386st->hand_state = TLS_ST_CR_CHANGE;387return 1;388}389break;390391case TLS_ST_CR_CHANGE:392if (mt == SSL3_MT_FINISHED) {393st->hand_state = TLS_ST_CR_FINISHED;394return 1;395}396break;397398case TLS_ST_OK:399if (mt == SSL3_MT_HELLO_REQUEST) {400st->hand_state = TLS_ST_CR_HELLO_REQ;401return 1;402}403break;404}405406err:407/* No valid transition found */408if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {409BIO *rbio;410411/*412* CCS messages don't have a message sequence number so this is probably413* because of an out-of-order CCS. We'll just drop it.414*/415s->init_num = 0;416s->rwstate = SSL_READING;417rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));418BIO_clear_retry_flags(rbio);419BIO_set_retry_read(rbio);420return 0;421}422SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);423return 0;424}425426static int do_compressed_cert(SSL_CONNECTION *sc)427{428/* If we negotiated RPK, we won't try to compress it */429return sc->ext.client_cert_type == TLSEXT_cert_type_x509430&& sc->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none;431}432433/*434* ossl_statem_client13_write_transition() works out what handshake state to435* move to next when the TLSv1.3 client is writing messages to be sent to the436* server.437*/438static WRITE_TRAN ossl_statem_client13_write_transition(SSL_CONNECTION *s)439{440OSSL_STATEM *st = &s->statem;441442/*443* Note: There are no cases for TLS_ST_BEFORE because we haven't negotiated444* TLSv1.3 yet at that point. They are handled by445* ossl_statem_client_write_transition().446*/447switch (st->hand_state) {448default:449/* Shouldn't happen */450SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);451return WRITE_TRAN_ERROR;452453case TLS_ST_CR_CERT_REQ:454if (s->post_handshake_auth == SSL_PHA_REQUESTED) {455if (do_compressed_cert(s))456st->hand_state = TLS_ST_CW_COMP_CERT;457else458st->hand_state = TLS_ST_CW_CERT;459return WRITE_TRAN_CONTINUE;460}461/*462* We should only get here if we received a CertificateRequest after463* we already sent close_notify464*/465if (!ossl_assert((s->shutdown & SSL_SENT_SHUTDOWN) != 0)) {466/* Shouldn't happen - same as default case */467SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);468return WRITE_TRAN_ERROR;469}470st->hand_state = TLS_ST_OK;471return WRITE_TRAN_CONTINUE;472473case TLS_ST_CR_FINISHED:474if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY475|| s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING)476st->hand_state = TLS_ST_PENDING_EARLY_DATA_END;477else if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0478&& s->hello_retry_request == SSL_HRR_NONE)479st->hand_state = TLS_ST_CW_CHANGE;480else if (s->s3.tmp.cert_req == 0)481st->hand_state = TLS_ST_CW_FINISHED;482else if (do_compressed_cert(s))483st->hand_state = TLS_ST_CW_COMP_CERT;484else485st->hand_state = TLS_ST_CW_CERT;486487s->ts_msg_read = ossl_time_now();488return WRITE_TRAN_CONTINUE;489490case TLS_ST_PENDING_EARLY_DATA_END:491if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED && !SSL_NO_EOED(s)) {492st->hand_state = TLS_ST_CW_END_OF_EARLY_DATA;493return WRITE_TRAN_CONTINUE;494}495/* Fall through */496497case TLS_ST_CW_END_OF_EARLY_DATA:498case TLS_ST_CW_CHANGE:499if (s->s3.tmp.cert_req == 0)500st->hand_state = TLS_ST_CW_FINISHED;501else if (do_compressed_cert(s))502st->hand_state = TLS_ST_CW_COMP_CERT;503else504st->hand_state = TLS_ST_CW_CERT;505return WRITE_TRAN_CONTINUE;506507case TLS_ST_CW_COMP_CERT:508case TLS_ST_CW_CERT:509/* If a non-empty Certificate we also send CertificateVerify */510st->hand_state = (s->s3.tmp.cert_req == 1) ? TLS_ST_CW_CERT_VRFY511: TLS_ST_CW_FINISHED;512return WRITE_TRAN_CONTINUE;513514case TLS_ST_CW_CERT_VRFY:515st->hand_state = TLS_ST_CW_FINISHED;516return WRITE_TRAN_CONTINUE;517518case TLS_ST_CR_KEY_UPDATE:519case TLS_ST_CW_KEY_UPDATE:520case TLS_ST_CR_SESSION_TICKET:521case TLS_ST_CW_FINISHED:522st->hand_state = TLS_ST_OK;523return WRITE_TRAN_CONTINUE;524525case TLS_ST_OK:526if (s->key_update != SSL_KEY_UPDATE_NONE) {527st->hand_state = TLS_ST_CW_KEY_UPDATE;528return WRITE_TRAN_CONTINUE;529}530531/* Try to read from the server instead */532return WRITE_TRAN_FINISHED;533}534}535536/*537* ossl_statem_client_write_transition() works out what handshake state to538* move to next when the client is writing messages to be sent to the server.539*/540WRITE_TRAN ossl_statem_client_write_transition(SSL_CONNECTION *s)541{542OSSL_STATEM *st = &s->statem;543544/*545* Note that immediately before/after a ClientHello we don't know what546* version we are going to negotiate yet, so we don't take this branch until547* later548*/549if (SSL_CONNECTION_IS_TLS13(s))550return ossl_statem_client13_write_transition(s);551552switch (st->hand_state) {553default:554/* Shouldn't happen */555SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);556return WRITE_TRAN_ERROR;557558case TLS_ST_OK:559if (!s->renegotiate) {560/*561* We haven't requested a renegotiation ourselves so we must have562* received a message from the server. Better read it.563*/564return WRITE_TRAN_FINISHED;565}566/* Renegotiation */567/* fall thru */568case TLS_ST_BEFORE:569st->hand_state = TLS_ST_CW_CLNT_HELLO;570return WRITE_TRAN_CONTINUE;571572case TLS_ST_CW_CLNT_HELLO:573if (s->early_data_state == SSL_EARLY_DATA_CONNECTING574&& !SSL_IS_QUIC_HANDSHAKE(s)) {575/*576* We are assuming this is a TLSv1.3 connection, although we haven't577* actually selected a version yet.578*/579if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)580st->hand_state = TLS_ST_CW_CHANGE;581else582st->hand_state = TLS_ST_EARLY_DATA;583return WRITE_TRAN_CONTINUE;584}585/*586* No transition at the end of writing because we don't know what587* we will be sent588*/589s->ts_msg_write = ossl_time_now();590return WRITE_TRAN_FINISHED;591592case TLS_ST_CR_SRVR_HELLO:593/*594* We only get here in TLSv1.3. We just received an HRR, so issue a595* CCS unless middlebox compat mode is off, or we already issued one596* because we did early data.597*/598if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0599&& s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING)600st->hand_state = TLS_ST_CW_CHANGE;601else602st->hand_state = TLS_ST_CW_CLNT_HELLO;603return WRITE_TRAN_CONTINUE;604605case TLS_ST_EARLY_DATA:606s->ts_msg_write = ossl_time_now();607return WRITE_TRAN_FINISHED;608609case DTLS_ST_CR_HELLO_VERIFY_REQUEST:610st->hand_state = TLS_ST_CW_CLNT_HELLO;611return WRITE_TRAN_CONTINUE;612613case TLS_ST_CR_SRVR_DONE:614s->ts_msg_read = ossl_time_now();615if (s->s3.tmp.cert_req)616st->hand_state = TLS_ST_CW_CERT;617else618st->hand_state = TLS_ST_CW_KEY_EXCH;619return WRITE_TRAN_CONTINUE;620621case TLS_ST_CW_CERT:622st->hand_state = TLS_ST_CW_KEY_EXCH;623return WRITE_TRAN_CONTINUE;624625case TLS_ST_CW_KEY_EXCH:626/*627* For TLS, cert_req is set to 2, so a cert chain of nothing is628* sent, but no verify packet is sent629*/630/*631* XXX: For now, we do not support client authentication in ECDH632* cipher suites with ECDH (rather than ECDSA) certificates. We633* need to skip the certificate verify message when client's634* ECDH public key is sent inside the client certificate.635*/636if (s->s3.tmp.cert_req == 1) {637st->hand_state = TLS_ST_CW_CERT_VRFY;638} else {639st->hand_state = TLS_ST_CW_CHANGE;640}641if (s->s3.flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {642st->hand_state = TLS_ST_CW_CHANGE;643}644return WRITE_TRAN_CONTINUE;645646case TLS_ST_CW_CERT_VRFY:647st->hand_state = TLS_ST_CW_CHANGE;648return WRITE_TRAN_CONTINUE;649650case TLS_ST_CW_CHANGE:651if (s->hello_retry_request == SSL_HRR_PENDING) {652st->hand_state = TLS_ST_CW_CLNT_HELLO;653} else if (s->early_data_state == SSL_EARLY_DATA_CONNECTING) {654st->hand_state = TLS_ST_EARLY_DATA;655} else {656#if defined(OPENSSL_NO_NEXTPROTONEG)657st->hand_state = TLS_ST_CW_FINISHED;658#else659if (!SSL_CONNECTION_IS_DTLS(s) && s->s3.npn_seen)660st->hand_state = TLS_ST_CW_NEXT_PROTO;661else662st->hand_state = TLS_ST_CW_FINISHED;663#endif664}665return WRITE_TRAN_CONTINUE;666667#if !defined(OPENSSL_NO_NEXTPROTONEG)668case TLS_ST_CW_NEXT_PROTO:669st->hand_state = TLS_ST_CW_FINISHED;670return WRITE_TRAN_CONTINUE;671#endif672673case TLS_ST_CW_FINISHED:674if (s->hit) {675st->hand_state = TLS_ST_OK;676return WRITE_TRAN_CONTINUE;677} else {678return WRITE_TRAN_FINISHED;679}680681case TLS_ST_CR_FINISHED:682if (s->hit) {683st->hand_state = TLS_ST_CW_CHANGE;684return WRITE_TRAN_CONTINUE;685} else {686st->hand_state = TLS_ST_OK;687return WRITE_TRAN_CONTINUE;688}689690case TLS_ST_CR_HELLO_REQ:691/*692* If we can renegotiate now then do so, otherwise wait for a more693* convenient time.694*/695if (ssl3_renegotiate_check(SSL_CONNECTION_GET_SSL(s), 1)) {696if (!tls_setup_handshake(s)) {697/* SSLfatal() already called */698return WRITE_TRAN_ERROR;699}700st->hand_state = TLS_ST_CW_CLNT_HELLO;701return WRITE_TRAN_CONTINUE;702}703st->hand_state = TLS_ST_OK;704return WRITE_TRAN_CONTINUE;705}706}707708/*709* Perform any pre work that needs to be done prior to sending a message from710* the client to the server.711*/712WORK_STATE ossl_statem_client_pre_work(SSL_CONNECTION *s, WORK_STATE wst)713{714OSSL_STATEM *st = &s->statem;715716switch (st->hand_state) {717default:718/* No pre work to be done */719break;720721case TLS_ST_CW_CLNT_HELLO:722s->shutdown = 0;723if (SSL_CONNECTION_IS_DTLS(s)) {724/* every DTLS ClientHello resets Finished MAC */725if (!ssl3_init_finished_mac(s)) {726/* SSLfatal() already called */727return WORK_ERROR;728}729} else if (s->ext.early_data == SSL_EARLY_DATA_REJECTED) {730/*731* This must be a second ClientHello after an HRR following an732* earlier rejected attempt to send early data. Since we were733* previously encrypting the early data we now need to reset the734* write record layer in order to write in plaintext again.735*/736if (!ssl_set_new_record_layer(s,737TLS_ANY_VERSION,738OSSL_RECORD_DIRECTION_WRITE,739OSSL_RECORD_PROTECTION_LEVEL_NONE,740NULL, 0, NULL, 0, NULL, 0, NULL, 0,741NULL, 0, NID_undef, NULL, NULL,742NULL)) {743/* SSLfatal already called */744return WORK_ERROR;745}746}747break;748749case TLS_ST_CW_CHANGE:750if (SSL_CONNECTION_IS_DTLS(s)) {751if (s->hit) {752/*753* We're into the last flight so we don't retransmit these754* messages unless we need to.755*/756st->use_timer = 0;757}758#ifndef OPENSSL_NO_SCTP759if (BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))) {760/* Calls SSLfatal() as required */761return dtls_wait_for_dry(s);762}763#endif764}765break;766767case TLS_ST_PENDING_EARLY_DATA_END:768/*769* If we've been called by SSL_do_handshake()/SSL_write(), or we did not770* attempt to write early data before calling SSL_read() then we press771* on with the handshake. Otherwise we pause here.772*/773if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING774|| s->early_data_state == SSL_EARLY_DATA_NONE)775return WORK_FINISHED_CONTINUE;776/* Fall through */777778case TLS_ST_EARLY_DATA:779return tls_finish_handshake(s, wst, 0, 1);780781case TLS_ST_OK:782/* Calls SSLfatal() as required */783return tls_finish_handshake(s, wst, 1, 1);784}785786return WORK_FINISHED_CONTINUE;787}788789/*790* Perform any work that needs to be done after sending a message from the791* client to the server.792*/793WORK_STATE ossl_statem_client_post_work(SSL_CONNECTION *s, WORK_STATE wst)794{795OSSL_STATEM *st = &s->statem;796SSL *ssl = SSL_CONNECTION_GET_SSL(s);797798s->init_num = 0;799800switch (st->hand_state) {801default:802/* No post work to be done */803break;804805case TLS_ST_CW_CLNT_HELLO:806if (s->early_data_state == SSL_EARLY_DATA_CONNECTING807&& s->max_early_data > 0) {808/*809* We haven't selected TLSv1.3 yet so we don't call the change810* cipher state function associated with the SSL_METHOD. Instead811* we call tls13_change_cipher_state() directly.812*/813if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0) {814if (!tls13_change_cipher_state(s,815SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {816/* SSLfatal() already called */817return WORK_ERROR;818}819}820/* else we're in compat mode so we delay flushing until after CCS */821} else if (!statem_flush(s)) {822return WORK_MORE_A;823}824825if (SSL_CONNECTION_IS_DTLS(s)) {826/* Treat the next message as the first packet */827s->first_packet = 1;828}829break;830831case TLS_ST_CW_KEY_EXCH:832if (tls_client_key_exchange_post_work(s) == 0) {833/* SSLfatal() already called */834return WORK_ERROR;835}836break;837838case TLS_ST_CW_CHANGE:839if (SSL_CONNECTION_IS_TLS13(s)840|| s->hello_retry_request == SSL_HRR_PENDING)841break;842if (s->early_data_state == SSL_EARLY_DATA_CONNECTING843&& s->max_early_data > 0) {844/*845* We haven't selected TLSv1.3 yet so we don't call the change846* cipher state function associated with the SSL_METHOD. Instead847* we call tls13_change_cipher_state() directly.848*/849if (!tls13_change_cipher_state(s,850SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE))851return WORK_ERROR;852break;853}854s->session->cipher = s->s3.tmp.new_cipher;855#ifdef OPENSSL_NO_COMP856s->session->compress_meth = 0;857#else858if (s->s3.tmp.new_compression == NULL)859s->session->compress_meth = 0;860else861s->session->compress_meth = s->s3.tmp.new_compression->id;862#endif863if (!ssl->method->ssl3_enc->setup_key_block(s)) {864/* SSLfatal() already called */865return WORK_ERROR;866}867868if (!ssl->method->ssl3_enc->change_cipher_state(s,869SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {870/* SSLfatal() already called */871return WORK_ERROR;872}873874#ifndef OPENSSL_NO_SCTP875if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {876/*877* Change to new shared key of SCTP-Auth, will be ignored if878* no SCTP used.879*/880BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,8810, NULL);882}883#endif884break;885886case TLS_ST_CW_FINISHED:887#ifndef OPENSSL_NO_SCTP888if (wst == WORK_MORE_A && SSL_CONNECTION_IS_DTLS(s) && s->hit == 0) {889/*890* Change to new shared key of SCTP-Auth, will be ignored if891* no SCTP used.892*/893BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,8940, NULL);895}896#endif897if (statem_flush(s) != 1)898return WORK_MORE_B;899900if (SSL_CONNECTION_IS_TLS13(s)) {901if (!tls13_save_handshake_digest_for_pha(s)) {902/* SSLfatal() already called */903return WORK_ERROR;904}905if (s->post_handshake_auth != SSL_PHA_REQUESTED) {906if (!ssl->method->ssl3_enc->change_cipher_state(s,907SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {908/* SSLfatal() already called */909return WORK_ERROR;910}911/*912* For QUIC we deferred setting up these keys until now so913* that we can ensure write keys are always set up before read914* keys.915*/916if (SSL_IS_QUIC_HANDSHAKE(s)917&& !ssl->method->ssl3_enc->change_cipher_state(s,918SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {919/* SSLfatal() already called */920return WORK_ERROR;921}922}923}924break;925926case TLS_ST_CW_KEY_UPDATE:927if (statem_flush(s) != 1)928return WORK_MORE_A;929if (!tls13_update_key(s, 1)) {930/* SSLfatal() already called */931return WORK_ERROR;932}933break;934}935936return WORK_FINISHED_CONTINUE;937}938939/*940* Get the message construction function and message type for sending from the941* client942*943* Valid return values are:944* 1: Success945* 0: Error946*/947int ossl_statem_client_construct_message(SSL_CONNECTION *s,948confunc_f *confunc, int *mt)949{950OSSL_STATEM *st = &s->statem;951952switch (st->hand_state) {953default:954/* Shouldn't happen */955SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);956return 0;957958case TLS_ST_CW_CHANGE:959if (SSL_CONNECTION_IS_DTLS(s))960*confunc = dtls_construct_change_cipher_spec;961else962*confunc = tls_construct_change_cipher_spec;963*mt = SSL3_MT_CHANGE_CIPHER_SPEC;964break;965966case TLS_ST_CW_CLNT_HELLO:967*confunc = tls_construct_client_hello;968*mt = SSL3_MT_CLIENT_HELLO;969break;970971case TLS_ST_CW_END_OF_EARLY_DATA:972*confunc = tls_construct_end_of_early_data;973*mt = SSL3_MT_END_OF_EARLY_DATA;974break;975976case TLS_ST_PENDING_EARLY_DATA_END:977*confunc = NULL;978*mt = SSL3_MT_DUMMY;979break;980981case TLS_ST_CW_CERT:982*confunc = tls_construct_client_certificate;983*mt = SSL3_MT_CERTIFICATE;984break;985986#ifndef OPENSSL_NO_COMP_ALG987case TLS_ST_CW_COMP_CERT:988*confunc = tls_construct_client_compressed_certificate;989*mt = SSL3_MT_COMPRESSED_CERTIFICATE;990break;991#endif992993case TLS_ST_CW_KEY_EXCH:994*confunc = tls_construct_client_key_exchange;995*mt = SSL3_MT_CLIENT_KEY_EXCHANGE;996break;997998case TLS_ST_CW_CERT_VRFY:999*confunc = tls_construct_cert_verify;1000*mt = SSL3_MT_CERTIFICATE_VERIFY;1001break;10021003#if !defined(OPENSSL_NO_NEXTPROTONEG)1004case TLS_ST_CW_NEXT_PROTO:1005*confunc = tls_construct_next_proto;1006*mt = SSL3_MT_NEXT_PROTO;1007break;1008#endif1009case TLS_ST_CW_FINISHED:1010*confunc = tls_construct_finished;1011*mt = SSL3_MT_FINISHED;1012break;10131014case TLS_ST_CW_KEY_UPDATE:1015*confunc = tls_construct_key_update;1016*mt = SSL3_MT_KEY_UPDATE;1017break;1018}10191020return 1;1021}10221023/*1024* Returns the maximum allowed length for the current message that we are1025* reading. Excludes the message header.1026*/1027size_t ossl_statem_client_max_message_size(SSL_CONNECTION *s)1028{1029OSSL_STATEM *st = &s->statem;10301031switch (st->hand_state) {1032default:1033/* Shouldn't happen */1034return 0;10351036case TLS_ST_CR_SRVR_HELLO:1037return SERVER_HELLO_MAX_LENGTH;10381039case DTLS_ST_CR_HELLO_VERIFY_REQUEST:1040return HELLO_VERIFY_REQUEST_MAX_LENGTH;10411042case TLS_ST_CR_COMP_CERT:1043case TLS_ST_CR_CERT:1044return s->max_cert_list;10451046case TLS_ST_CR_CERT_VRFY:1047return CERTIFICATE_VERIFY_MAX_LENGTH;10481049case TLS_ST_CR_CERT_STATUS:1050return SSL3_RT_MAX_PLAIN_LENGTH;10511052case TLS_ST_CR_KEY_EXCH:1053return SERVER_KEY_EXCH_MAX_LENGTH;10541055case TLS_ST_CR_CERT_REQ:1056/*1057* Set to s->max_cert_list for compatibility with previous releases. In1058* practice these messages can get quite long if servers are configured1059* to provide a long list of acceptable CAs1060*/1061return s->max_cert_list;10621063case TLS_ST_CR_SRVR_DONE:1064return SERVER_HELLO_DONE_MAX_LENGTH;10651066case TLS_ST_CR_CHANGE:1067if (s->version == DTLS1_BAD_VER)1068return 3;1069return CCS_MAX_LENGTH;10701071case TLS_ST_CR_SESSION_TICKET:1072return (SSL_CONNECTION_IS_TLS13(s)) ? SESSION_TICKET_MAX_LENGTH_TLS131073: SESSION_TICKET_MAX_LENGTH_TLS12;10741075case TLS_ST_CR_FINISHED:1076return FINISHED_MAX_LENGTH;10771078case TLS_ST_CR_ENCRYPTED_EXTENSIONS:1079return ENCRYPTED_EXTENSIONS_MAX_LENGTH;10801081case TLS_ST_CR_KEY_UPDATE:1082return KEY_UPDATE_MAX_LENGTH;1083}1084}10851086/*1087* Process a message that the client has received from the server.1088*/1089MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL_CONNECTION *s,1090PACKET *pkt)1091{1092OSSL_STATEM *st = &s->statem;10931094switch (st->hand_state) {1095default:1096/* Shouldn't happen */1097SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1098return MSG_PROCESS_ERROR;10991100case TLS_ST_CR_SRVR_HELLO:1101return tls_process_server_hello(s, pkt);11021103case DTLS_ST_CR_HELLO_VERIFY_REQUEST:1104return dtls_process_hello_verify(s, pkt);11051106case TLS_ST_CR_CERT:1107return tls_process_server_certificate(s, pkt);11081109#ifndef OPENSSL_NO_COMP_ALG1110case TLS_ST_CR_COMP_CERT:1111return tls_process_server_compressed_certificate(s, pkt);1112#endif11131114case TLS_ST_CR_CERT_VRFY:1115return tls_process_cert_verify(s, pkt);11161117case TLS_ST_CR_CERT_STATUS:1118return tls_process_cert_status(s, pkt);11191120case TLS_ST_CR_KEY_EXCH:1121return tls_process_key_exchange(s, pkt);11221123case TLS_ST_CR_CERT_REQ:1124return tls_process_certificate_request(s, pkt);11251126case TLS_ST_CR_SRVR_DONE:1127return tls_process_server_done(s, pkt);11281129case TLS_ST_CR_CHANGE:1130return tls_process_change_cipher_spec(s, pkt);11311132case TLS_ST_CR_SESSION_TICKET:1133return tls_process_new_session_ticket(s, pkt);11341135case TLS_ST_CR_FINISHED:1136return tls_process_finished(s, pkt);11371138case TLS_ST_CR_HELLO_REQ:1139return tls_process_hello_req(s, pkt);11401141case TLS_ST_CR_ENCRYPTED_EXTENSIONS:1142return tls_process_encrypted_extensions(s, pkt);11431144case TLS_ST_CR_KEY_UPDATE:1145return tls_process_key_update(s, pkt);1146}1147}11481149/*1150* Perform any further processing required following the receipt of a message1151* from the server1152*/1153WORK_STATE ossl_statem_client_post_process_message(SSL_CONNECTION *s,1154WORK_STATE wst)1155{1156OSSL_STATEM *st = &s->statem;11571158switch (st->hand_state) {1159default:1160/* Shouldn't happen */1161SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1162return WORK_ERROR;11631164case TLS_ST_CR_CERT:1165case TLS_ST_CR_COMP_CERT:1166return tls_post_process_server_certificate(s, wst);11671168case TLS_ST_CR_CERT_VRFY:1169case TLS_ST_CR_CERT_REQ:1170return tls_prepare_client_certificate(s, wst);1171}1172}11731174CON_FUNC_RETURN tls_construct_client_hello(SSL_CONNECTION *s, WPACKET *pkt)1175{1176unsigned char *p;1177size_t sess_id_len;1178int i, protverr;1179#ifndef OPENSSL_NO_COMP1180SSL_COMP *comp;1181#endif1182SSL_SESSION *sess = s->session;1183unsigned char *session_id;1184SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);11851186/* Work out what SSL/TLS/DTLS version to use */1187protverr = ssl_set_client_hello_version(s);1188if (protverr != 0) {1189SSLfatal(s, SSL_AD_INTERNAL_ERROR, protverr);1190return CON_FUNC_ERROR;1191}11921193if (sess == NULL1194|| !ssl_version_supported(s, sess->ssl_version, NULL)1195|| !SSL_SESSION_is_resumable(sess)) {1196if (s->hello_retry_request == SSL_HRR_NONE1197&& !ssl_get_new_session(s, 0)) {1198/* SSLfatal() already called */1199return CON_FUNC_ERROR;1200}1201}1202/* else use the pre-loaded session */12031204p = s->s3.client_random;12051206/*1207* for DTLS if client_random is initialized, reuse it, we are1208* required to use same upon reply to HelloVerify1209*/1210if (SSL_CONNECTION_IS_DTLS(s)) {1211size_t idx;1212i = 1;1213for (idx = 0; idx < sizeof(s->s3.client_random); idx++) {1214if (p[idx]) {1215i = 0;1216break;1217}1218}1219} else {1220i = (s->hello_retry_request == SSL_HRR_NONE);1221}12221223if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3.client_random), DOWNGRADE_NONE) <= 0) {1224SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1225return CON_FUNC_ERROR;1226}12271228/*-1229* version indicates the negotiated version: for example from1230* an SSLv2/v3 compatible client hello). The client_version1231* field is the maximum version we permit and it is also1232* used in RSA encrypted premaster secrets. Some servers can1233* choke if we initially report a higher version then1234* renegotiate to a lower one in the premaster secret. This1235* didn't happen with TLS 1.0 as most servers supported it1236* but it can with TLS 1.1 or later if the server only supports1237* 1.0.1238*1239* Possible scenario with previous logic:1240* 1. Client hello indicates TLS 1.21241* 2. Server hello says TLS 1.01242* 3. RSA encrypted premaster secret uses 1.2.1243* 4. Handshake proceeds using TLS 1.0.1244* 5. Server sends hello request to renegotiate.1245* 6. Client hello indicates TLS v1.0 as we now1246* know that is maximum server supports.1247* 7. Server chokes on RSA encrypted premaster secret1248* containing version 1.0.1249*1250* For interoperability it should be OK to always use the1251* maximum version we support in client hello and then rely1252* on the checking of version to ensure the servers isn't1253* being inconsistent: for example initially negotiating with1254* TLS 1.0 and renegotiating with TLS 1.2. We do this by using1255* client_version in client hello and not resetting it to1256* the negotiated version.1257*1258* For TLS 1.3 we always set the ClientHello version to 1.2 and rely on the1259* supported_versions extension for the real supported versions.1260*/1261if (!WPACKET_put_bytes_u16(pkt, s->client_version)1262|| !WPACKET_memcpy(pkt, s->s3.client_random, SSL3_RANDOM_SIZE)) {1263SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1264return CON_FUNC_ERROR;1265}12661267/* Session ID */1268session_id = s->session->session_id;1269if (s->new_session || s->session->ssl_version == TLS1_3_VERSION) {1270if (s->version == TLS1_3_VERSION1271&& (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0) {1272sess_id_len = sizeof(s->tmp_session_id);1273s->tmp_session_id_len = sess_id_len;1274session_id = s->tmp_session_id;1275if (s->hello_retry_request == SSL_HRR_NONE1276&& RAND_bytes_ex(sctx->libctx, s->tmp_session_id,1277sess_id_len, 0)1278<= 0) {1279SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1280return CON_FUNC_ERROR;1281}1282} else {1283sess_id_len = 0;1284}1285} else {1286assert(s->session->session_id_length <= sizeof(s->session->session_id));1287sess_id_len = s->session->session_id_length;1288if (s->version == TLS1_3_VERSION) {1289s->tmp_session_id_len = sess_id_len;1290memcpy(s->tmp_session_id, s->session->session_id, sess_id_len);1291}1292}1293if (!WPACKET_start_sub_packet_u8(pkt)1294|| (sess_id_len != 0 && !WPACKET_memcpy(pkt, session_id, sess_id_len))1295|| !WPACKET_close(pkt)) {1296SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1297return CON_FUNC_ERROR;1298}12991300/* cookie stuff for DTLS */1301if (SSL_CONNECTION_IS_DTLS(s)) {1302if (s->d1->cookie_len > sizeof(s->d1->cookie)1303|| !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,1304s->d1->cookie_len)) {1305SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1306return CON_FUNC_ERROR;1307}1308}13091310/* Ciphers supported */1311if (!WPACKET_start_sub_packet_u16(pkt)) {1312SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1313return CON_FUNC_ERROR;1314}13151316if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(SSL_CONNECTION_GET_SSL(s)),1317pkt)) {1318/* SSLfatal() already called */1319return CON_FUNC_ERROR;1320}1321if (!WPACKET_close(pkt)) {1322SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1323return CON_FUNC_ERROR;1324}13251326/* COMPRESSION */1327if (!WPACKET_start_sub_packet_u8(pkt)) {1328SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1329return CON_FUNC_ERROR;1330}1331#ifndef OPENSSL_NO_COMP1332if (ssl_allow_compression(s)1333&& sctx->comp_methods1334&& (SSL_CONNECTION_IS_DTLS(s)1335|| s->s3.tmp.max_ver < TLS1_3_VERSION)) {1336int compnum = sk_SSL_COMP_num(sctx->comp_methods);1337for (i = 0; i < compnum; i++) {1338comp = sk_SSL_COMP_value(sctx->comp_methods, i);1339if (!WPACKET_put_bytes_u8(pkt, comp->id)) {1340SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1341return CON_FUNC_ERROR;1342}1343}1344}1345#endif1346/* Add the NULL method */1347if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {1348SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1349return CON_FUNC_ERROR;1350}13511352/* TLS extensions */1353if (!tls_construct_extensions(s, pkt, SSL_EXT_CLIENT_HELLO, NULL, 0)) {1354/* SSLfatal() already called */1355return CON_FUNC_ERROR;1356}13571358return CON_FUNC_SUCCESS;1359}13601361MSG_PROCESS_RETURN dtls_process_hello_verify(SSL_CONNECTION *s, PACKET *pkt)1362{1363size_t cookie_len;1364PACKET cookiepkt;13651366if (!PACKET_forward(pkt, 2)1367|| !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {1368SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1369return MSG_PROCESS_ERROR;1370}13711372cookie_len = PACKET_remaining(&cookiepkt);1373if (cookie_len > sizeof(s->d1->cookie)) {1374SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);1375return MSG_PROCESS_ERROR;1376}13771378if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {1379SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1380return MSG_PROCESS_ERROR;1381}1382s->d1->cookie_len = cookie_len;13831384return MSG_PROCESS_FINISHED_READING;1385}13861387static int set_client_ciphersuite(SSL_CONNECTION *s,1388const unsigned char *cipherchars)1389{1390STACK_OF(SSL_CIPHER) *sk;1391const SSL_CIPHER *c;1392int i;1393SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);13941395c = ssl_get_cipher_by_char(s, cipherchars, 0);1396if (c == NULL) {1397/* unknown cipher */1398SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CIPHER_RETURNED);1399return 0;1400}1401/*1402* If it is a disabled cipher we either didn't send it in client hello,1403* or it's not allowed for the selected protocol. So we return an error.1404*/1405if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK, 1)) {1406SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1407return 0;1408}14091410sk = ssl_get_ciphers_by_id(s);1411i = sk_SSL_CIPHER_find(sk, c);1412if (i < 0) {1413/* we did not say we would use this cipher */1414SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1415return 0;1416}14171418if (SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.new_cipher != NULL1419&& s->s3.tmp.new_cipher->id != c->id) {1420/* ServerHello selected a different ciphersuite to that in the HRR */1421SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1422return 0;1423}14241425/*1426* Depending on the session caching (internal/external), the cipher1427* and/or cipher_id values may not be set. Make sure that cipher_id is1428* set and use it for comparison.1429*/1430if (s->session->cipher != NULL)1431s->session->cipher_id = s->session->cipher->id;1432if (s->hit && (s->session->cipher_id != c->id)) {1433if (SSL_CONNECTION_IS_TLS13(s)) {1434const EVP_MD *md = ssl_md(sctx, c->algorithm2);14351436if (!ossl_assert(s->session->cipher != NULL)) {1437SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1438return 0;1439}1440/*1441* In TLSv1.3 it is valid for the server to select a different1442* ciphersuite as long as the hash is the same.1443*/1444if (md == NULL1445|| md != ssl_md(sctx, s->session->cipher->algorithm2)) {1446SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1447SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED);1448return 0;1449}1450} else {1451/*1452* Prior to TLSv1.3 resuming a session always meant using the same1453* ciphersuite.1454*/1455SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1456SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);1457return 0;1458}1459}1460s->s3.tmp.new_cipher = c;14611462return 1;1463}14641465MSG_PROCESS_RETURN tls_process_server_hello(SSL_CONNECTION *s, PACKET *pkt)1466{1467PACKET session_id, extpkt;1468size_t session_id_len;1469const unsigned char *cipherchars;1470int hrr = 0;1471unsigned int compression;1472unsigned int sversion;1473unsigned int context;1474RAW_EXTENSION *extensions = NULL;1475SSL *ssl = SSL_CONNECTION_GET_SSL(s);1476SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);1477#ifndef OPENSSL_NO_COMP1478SSL_COMP *comp;1479#endif14801481if (!PACKET_get_net_2(pkt, &sversion)) {1482SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1483goto err;1484}14851486/* load the server random */1487if (s->version == TLS1_3_VERSION1488&& sversion == TLS1_2_VERSION1489&& PACKET_remaining(pkt) >= SSL3_RANDOM_SIZE1490&& memcmp(hrrrandom, PACKET_data(pkt), SSL3_RANDOM_SIZE) == 0) {1491if (s->hello_retry_request != SSL_HRR_NONE) {1492SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);1493goto err;1494}1495s->hello_retry_request = SSL_HRR_PENDING;1496/* Tell the record layer that we know we're going to get TLSv1.3 */1497if (!ssl_set_record_protocol_version(s, s->version)) {1498SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1499goto err;1500}1501hrr = 1;1502if (!PACKET_forward(pkt, SSL3_RANDOM_SIZE)) {1503SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1504goto err;1505}1506} else {1507if (!PACKET_copy_bytes(pkt, s->s3.server_random, SSL3_RANDOM_SIZE)) {1508SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1509goto err;1510}1511}15121513/* Get the session-id. */1514if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {1515SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1516goto err;1517}1518session_id_len = PACKET_remaining(&session_id);1519if (session_id_len > sizeof(s->session->session_id)1520|| session_id_len > SSL3_SESSION_ID_SIZE) {1521SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_SSL3_SESSION_ID_TOO_LONG);1522goto err;1523}15241525if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {1526SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1527goto err;1528}15291530if (!PACKET_get_1(pkt, &compression)) {1531SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1532goto err;1533}15341535/* TLS extensions */1536if (PACKET_remaining(pkt) == 0 && !hrr) {1537PACKET_null_init(&extpkt);1538} else if (!PACKET_as_length_prefixed_2(pkt, &extpkt)1539|| PACKET_remaining(pkt) != 0) {1540SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);1541goto err;1542}15431544if (!hrr) {1545if (!tls_collect_extensions(s, &extpkt,1546SSL_EXT_TLS1_2_SERVER_HELLO1547| SSL_EXT_TLS1_3_SERVER_HELLO,1548&extensions, NULL, 1)) {1549/* SSLfatal() already called */1550goto err;1551}15521553if (!ssl_choose_client_version(s, sversion, extensions)) {1554/* SSLfatal() already called */1555goto err;1556}1557}15581559if (SSL_CONNECTION_IS_TLS13(s) || hrr) {1560if (compression != 0) {1561SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1562SSL_R_INVALID_COMPRESSION_ALGORITHM);1563goto err;1564}15651566if (session_id_len != s->tmp_session_id_len1567|| memcmp(PACKET_data(&session_id), s->tmp_session_id,1568session_id_len)1569!= 0) {1570SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_INVALID_SESSION_ID);1571goto err;1572}1573}15741575if (hrr) {1576if (!set_client_ciphersuite(s, cipherchars)) {1577/* SSLfatal() already called */1578goto err;1579}15801581return tls_process_as_hello_retry_request(s, &extpkt);1582}15831584/*1585* Now we have chosen the version we need to check again that the extensions1586* are appropriate for this version.1587*/1588context = SSL_CONNECTION_IS_TLS13(s) ? SSL_EXT_TLS1_3_SERVER_HELLO1589: SSL_EXT_TLS1_2_SERVER_HELLO;1590if (!tls_validate_all_contexts(s, context, extensions)) {1591SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);1592goto err;1593}15941595s->hit = 0;15961597if (SSL_CONNECTION_IS_TLS13(s)) {1598/*1599* In TLSv1.3 a ServerHello message signals a key change so the end of1600* the message must be on a record boundary.1601*/1602if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {1603SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,1604SSL_R_NOT_ON_RECORD_BOUNDARY);1605goto err;1606}16071608/* This will set s->hit if we are resuming */1609if (!tls_parse_extension(s, TLSEXT_IDX_psk,1610SSL_EXT_TLS1_3_SERVER_HELLO,1611extensions, NULL, 0)) {1612/* SSLfatal() already called */1613goto err;1614}1615} else {1616/*1617* Check if we can resume the session based on external pre-shared1618* secret. EAP-FAST (RFC 4851) supports two types of session resumption.1619* Resumption based on server-side state works with session IDs.1620* Resumption based on pre-shared Protected Access Credentials (PACs)1621* works by overriding the SessionTicket extension at the application1622* layer, and does not send a session ID. (We do not know whether1623* EAP-FAST servers would honour the session ID.) Therefore, the session1624* ID alone is not a reliable indicator of session resumption, so we1625* first check if we can resume, and later peek at the next handshake1626* message to see if the server wants to resume.1627*/1628if (s->version >= TLS1_VERSION1629&& s->ext.session_secret_cb != NULL && s->session->ext.tick) {1630const SSL_CIPHER *pref_cipher = NULL;1631/*1632* s->session->master_key_length is a size_t, but this is an int for1633* backwards compat reasons1634*/1635int master_key_length;16361637master_key_length = sizeof(s->session->master_key);1638if (s->ext.session_secret_cb(ussl, s->session->master_key,1639&master_key_length,1640NULL, &pref_cipher,1641s->ext.session_secret_cb_arg)1642&& master_key_length > 0) {1643s->session->master_key_length = master_key_length;1644s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, cipherchars, 0);1645} else {1646SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1647goto err;1648}1649}16501651if (session_id_len != 01652&& session_id_len == s->session->session_id_length1653&& memcmp(PACKET_data(&session_id), s->session->session_id,1654session_id_len)1655== 0)1656s->hit = 1;1657}16581659if (s->hit) {1660if (s->sid_ctx_length != s->session->sid_ctx_length1661|| memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {1662/* actually a client application bug */1663SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1664SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);1665goto err;1666}1667} else {1668/*1669* If we were trying for session-id reuse but the server1670* didn't resume, make a new SSL_SESSION.1671* In the case of EAP-FAST and PAC, we do not send a session ID,1672* so the PAC-based session secret is always preserved. It'll be1673* overwritten if the server refuses resumption.1674*/1675if (s->session->session_id_length > 0) {1676ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);1677if (!ssl_get_new_session(s, 0)) {1678/* SSLfatal() already called */1679goto err;1680}1681}16821683s->session->ssl_version = s->version;1684/*1685* In TLSv1.2 and below we save the session id we were sent so we can1686* resume it later. In TLSv1.3 the session id we were sent is just an1687* echo of what we originally sent in the ClientHello and should not be1688* used for resumption.1689*/1690if (!SSL_CONNECTION_IS_TLS13(s)) {1691s->session->session_id_length = session_id_len;1692/* session_id_len could be 0 */1693if (session_id_len > 0)1694memcpy(s->session->session_id, PACKET_data(&session_id),1695session_id_len);1696}1697}16981699/* Session version and negotiated protocol version should match */1700if (s->version != s->session->ssl_version) {1701SSLfatal(s, SSL_AD_PROTOCOL_VERSION,1702SSL_R_SSL_SESSION_VERSION_MISMATCH);1703goto err;1704}1705/*1706* Now that we know the version, update the check to see if it's an allowed1707* version.1708*/1709s->s3.tmp.min_ver = s->version;1710s->s3.tmp.max_ver = s->version;17111712if (!set_client_ciphersuite(s, cipherchars)) {1713/* SSLfatal() already called */1714goto err;1715}17161717#ifdef OPENSSL_NO_COMP1718if (compression != 0) {1719SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1720SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);1721goto err;1722}1723/*1724* If compression is disabled we'd better not try to resume a session1725* using compression.1726*/1727if (s->session->compress_meth != 0) {1728SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);1729goto err;1730}1731#else1732if (s->hit && compression != s->session->compress_meth) {1733SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1734SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);1735goto err;1736}1737if (compression == 0)1738comp = NULL;1739else if (!ssl_allow_compression(s)) {1740SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COMPRESSION_DISABLED);1741goto err;1742} else {1743comp = ssl3_comp_find(SSL_CONNECTION_GET_CTX(s)->comp_methods,1744compression);1745}17461747if (compression != 0 && comp == NULL) {1748SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1749SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);1750goto err;1751} else {1752s->s3.tmp.new_compression = comp;1753}1754#endif17551756if (!tls_parse_all_extensions(s, context, extensions, NULL, 0, 1)) {1757/* SSLfatal() already called */1758goto err;1759}17601761#ifndef OPENSSL_NO_SCTP1762if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {1763unsigned char sctpauthkey[64];1764char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];1765size_t labellen;17661767/*1768* Add new shared key for SCTP-Auth, will be ignored if1769* no SCTP used.1770*/1771memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,1772sizeof(DTLS1_SCTP_AUTH_LABEL));17731774/* Don't include the terminating zero. */1775labellen = sizeof(labelbuffer) - 1;1776if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)1777labellen += 1;17781779if (SSL_export_keying_material(ssl, sctpauthkey,1780sizeof(sctpauthkey),1781labelbuffer,1782labellen, NULL, 0, 0)1783<= 0) {1784SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1785goto err;1786}17871788BIO_ctrl(SSL_get_wbio(ssl),1789BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,1790sizeof(sctpauthkey), sctpauthkey);1791}1792#endif17931794/*1795* In TLSv1.3 we have some post-processing to change cipher state, otherwise1796* we're done with this message1797*/1798if (SSL_CONNECTION_IS_TLS13(s)) {1799if (!ssl->method->ssl3_enc->setup_key_block(s)1800|| !tls13_store_handshake_traffic_hash(s)) {1801/* SSLfatal() already called */1802goto err;1803}1804/*1805* If we're not doing early-data and we're not going to send a dummy CCS1806* (i.e. no middlebox compat mode) then we can change the write keys1807* immediately. Otherwise we have to defer this until after all possible1808* early data is written. We could just always defer until the last1809* moment except QUIC needs it done at the same time as the read keys1810* are changed. Since QUIC doesn't do TLS early data or need middlebox1811* compat this doesn't cause a problem.1812*/1813if (SSL_IS_QUIC_HANDSHAKE(s)1814|| (s->early_data_state == SSL_EARLY_DATA_NONE1815&& (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0)) {1816if (!ssl->method->ssl3_enc->change_cipher_state(s,1817SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {1818/* SSLfatal() already called */1819goto err;1820}1821}1822if (!ssl->method->ssl3_enc->change_cipher_state(s,1823SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ)) {1824/* SSLfatal() already called */1825goto err;1826}1827}18281829OPENSSL_free(extensions);1830return MSG_PROCESS_CONTINUE_READING;1831err:1832OPENSSL_free(extensions);1833return MSG_PROCESS_ERROR;1834}18351836static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,1837PACKET *extpkt)1838{1839RAW_EXTENSION *extensions = NULL;18401841/*1842* If we were sending early_data then any alerts should not be sent using1843* the old wrlmethod.1844*/1845if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING1846&& !ssl_set_new_record_layer(s,1847TLS_ANY_VERSION,1848OSSL_RECORD_DIRECTION_WRITE,1849OSSL_RECORD_PROTECTION_LEVEL_NONE,1850NULL, 0, NULL, 0, NULL, 0, NULL, 0,1851NULL, 0, NID_undef, NULL, NULL, NULL)) {1852/* SSLfatal already called */1853goto err;1854}1855/* We are definitely going to be using TLSv1.3 */1856s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, TLS1_3_VERSION);18571858if (!tls_collect_extensions(s, extpkt, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,1859&extensions, NULL, 1)1860|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,1861extensions, NULL, 0, 1)) {1862/* SSLfatal() already called */1863goto err;1864}18651866OPENSSL_free(extensions);1867extensions = NULL;18681869if (s->ext.tls13_cookie_len == 0 && s->s3.tmp.pkey != NULL) {1870/*1871* We didn't receive a cookie or a new key_share so the next1872* ClientHello will not change1873*/1874SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CHANGE_FOLLOWING_HRR);1875goto err;1876}18771878/*1879* Re-initialise the Transcript Hash. We're going to prepopulate it with1880* a synthetic message_hash in place of ClientHello1.1881*/1882if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {1883/* SSLfatal() already called */1884goto err;1885}18861887/*1888* Add this message to the Transcript Hash. Normally this is done1889* automatically prior to the message processing stage. However due to the1890* need to create the synthetic message hash, we defer that step until now1891* for HRR messages.1892*/1893if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,1894s->init_num + SSL3_HM_HEADER_LENGTH)) {1895/* SSLfatal() already called */1896goto err;1897}18981899return MSG_PROCESS_FINISHED_READING;1900err:1901OPENSSL_free(extensions);1902return MSG_PROCESS_ERROR;1903}19041905MSG_PROCESS_RETURN tls_process_server_rpk(SSL_CONNECTION *sc, PACKET *pkt)1906{1907EVP_PKEY *peer_rpk = NULL;19081909if (!tls_process_rpk(sc, pkt, &peer_rpk)) {1910/* SSLfatal() already called */1911return MSG_PROCESS_ERROR;1912}19131914if (peer_rpk == NULL) {1915SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_CERTIFICATE);1916return MSG_PROCESS_ERROR;1917}19181919EVP_PKEY_free(sc->session->peer_rpk);1920sc->session->peer_rpk = peer_rpk;19211922return MSG_PROCESS_CONTINUE_PROCESSING;1923}19241925static WORK_STATE tls_post_process_server_rpk(SSL_CONNECTION *sc,1926WORK_STATE wst)1927{1928size_t certidx;1929const SSL_CERT_LOOKUP *clu;1930int v_ok;19311932if (sc->session->peer_rpk == NULL) {1933SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER,1934SSL_R_INVALID_RAW_PUBLIC_KEY);1935return WORK_ERROR;1936}19371938if (sc->rwstate == SSL_RETRY_VERIFY)1939sc->rwstate = SSL_NOTHING;19401941ERR_set_mark();1942v_ok = ssl_verify_rpk(sc, sc->session->peer_rpk);1943if (v_ok <= 0 && sc->verify_mode != SSL_VERIFY_NONE) {1944ERR_clear_last_mark();1945SSLfatal(sc, ssl_x509err2alert(sc->verify_result),1946SSL_R_CERTIFICATE_VERIFY_FAILED);1947return WORK_ERROR;1948}1949ERR_pop_to_mark(); /* but we keep s->verify_result */1950if (v_ok > 0 && sc->rwstate == SSL_RETRY_VERIFY) {1951return WORK_MORE_A;1952}19531954if ((clu = ssl_cert_lookup_by_pkey(sc->session->peer_rpk, &certidx,1955SSL_CONNECTION_GET_CTX(sc)))1956== NULL) {1957SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);1958return WORK_ERROR;1959}19601961/*1962* Check certificate type is consistent with ciphersuite. For TLS 1.31963* skip check since TLS 1.3 ciphersuites can be used with any certificate1964* type.1965*/1966if (!SSL_CONNECTION_IS_TLS13(sc)) {1967if ((clu->amask & sc->s3.tmp.new_cipher->algorithm_auth) == 0) {1968SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_RPK_TYPE);1969return WORK_ERROR;1970}1971}19721973/* Ensure there is no peer/peer_chain */1974X509_free(sc->session->peer);1975sc->session->peer = NULL;1976sk_X509_pop_free(sc->session->peer_chain, X509_free);1977sc->session->peer_chain = NULL;1978sc->session->verify_result = sc->verify_result;19791980/* Save the current hash state for when we receive the CertificateVerify */1981if (SSL_CONNECTION_IS_TLS13(sc)1982&& !ssl_handshake_hash(sc, sc->cert_verify_hash,1983sizeof(sc->cert_verify_hash),1984&sc->cert_verify_hash_len)) {1985/* SSLfatal() already called */1986return WORK_ERROR;1987}19881989return WORK_FINISHED_CONTINUE;1990}19911992/* prepare server cert verification by setting s->session->peer_chain from pkt */1993MSG_PROCESS_RETURN tls_process_server_certificate(SSL_CONNECTION *s,1994PACKET *pkt)1995{1996unsigned long cert_list_len, cert_len;1997X509 *x = NULL;1998const unsigned char *certstart, *certbytes;1999size_t chainidx;2000unsigned int context = 0;2001SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);20022003if (s->ext.server_cert_type == TLSEXT_cert_type_rpk)2004return tls_process_server_rpk(s, pkt);2005if (s->ext.server_cert_type != TLSEXT_cert_type_x509) {2006SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,2007SSL_R_UNKNOWN_CERTIFICATE_TYPE);2008goto err;2009}20102011if ((s->session->peer_chain = sk_X509_new_null()) == NULL) {2012SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2013goto err;2014}20152016if ((SSL_CONNECTION_IS_TLS13(s) && !PACKET_get_1(pkt, &context))2017|| context != 02018|| !PACKET_get_net_3(pkt, &cert_list_len)2019|| PACKET_remaining(pkt) != cert_list_len2020|| PACKET_remaining(pkt) == 0) {2021SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2022goto err;2023}2024for (chainidx = 0; PACKET_remaining(pkt); chainidx++) {2025if (!PACKET_get_net_3(pkt, &cert_len)2026|| !PACKET_get_bytes(pkt, &certbytes, cert_len)) {2027SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);2028goto err;2029}20302031certstart = certbytes;2032x = X509_new_ex(sctx->libctx, sctx->propq);2033if (x == NULL) {2034SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);2035goto err;2036}2037if (d2i_X509(&x, (const unsigned char **)&certbytes,2038cert_len)2039== NULL) {2040SSLfatal(s, SSL_AD_BAD_CERTIFICATE, ERR_R_ASN1_LIB);2041goto err;2042}20432044if (certbytes != (certstart + cert_len)) {2045SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);2046goto err;2047}20482049if (SSL_CONNECTION_IS_TLS13(s)) {2050RAW_EXTENSION *rawexts = NULL;2051PACKET extensions;20522053if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {2054SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);2055goto err;2056}2057if (!tls_collect_extensions(s, &extensions,2058SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,2059NULL, chainidx == 0)2060|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,2061rawexts, x, chainidx,2062PACKET_remaining(pkt) == 0)) {2063OPENSSL_free(rawexts);2064/* SSLfatal already called */2065goto err;2066}2067OPENSSL_free(rawexts);2068}20692070if (!sk_X509_push(s->session->peer_chain, x)) {2071SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2072goto err;2073}2074x = NULL;2075}2076return MSG_PROCESS_CONTINUE_PROCESSING;20772078err:2079X509_free(x);2080OSSL_STACK_OF_X509_free(s->session->peer_chain);2081s->session->peer_chain = NULL;2082return MSG_PROCESS_ERROR;2083}20842085/*2086* Verify the s->session->peer_chain and check server cert type.2087* On success set s->session->peer and s->session->verify_result.2088* Else the peer certificate verification callback may request retry.2089*/2090WORK_STATE tls_post_process_server_certificate(SSL_CONNECTION *s,2091WORK_STATE wst)2092{2093X509 *x;2094EVP_PKEY *pkey = NULL;2095const SSL_CERT_LOOKUP *clu;2096size_t certidx;2097int i;20982099if (s->ext.server_cert_type == TLSEXT_cert_type_rpk)2100return tls_post_process_server_rpk(s, wst);21012102if (s->rwstate == SSL_RETRY_VERIFY)2103s->rwstate = SSL_NOTHING;21042105/*2106* The documented interface is that SSL_VERIFY_PEER should be set in order2107* for client side verification of the server certificate to take place.2108* However, historically the code has only checked that *any* flag is set2109* to cause server verification to take place. Use of the other flags makes2110* no sense in client mode. An attempt to clean up the semantics was2111* reverted because at least one application *only* set2112* SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused2113* server verification to take place, after the clean up it silently did2114* nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags2115* sent to them because they are void functions. Therefore, we now use the2116* (less clean) historic behaviour of performing validation if any flag is2117* set. The *documented* interface remains the same.2118*/2119ERR_set_mark();2120i = ssl_verify_cert_chain(s, s->session->peer_chain);2121if (i <= 0 && s->verify_mode != SSL_VERIFY_NONE) {2122ERR_clear_last_mark();2123SSLfatal(s, ssl_x509err2alert(s->verify_result),2124SSL_R_CERTIFICATE_VERIFY_FAILED);2125return WORK_ERROR;2126}2127ERR_pop_to_mark(); /* but we keep s->verify_result */2128if (i > 0 && s->rwstate == SSL_RETRY_VERIFY)2129return WORK_MORE_A;21302131/*2132* Inconsistency alert: cert_chain does include the peer's certificate,2133* which we don't include in statem_srvr.c2134*/2135x = sk_X509_value(s->session->peer_chain, 0);21362137pkey = X509_get0_pubkey(x);21382139if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {2140SSLfatal(s, SSL_AD_INTERNAL_ERROR,2141SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);2142return WORK_ERROR;2143}21442145if ((clu = ssl_cert_lookup_by_pkey(pkey, &certidx,2146SSL_CONNECTION_GET_CTX(s)))2147== NULL) {2148SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);2149return WORK_ERROR;2150}2151/*2152* Check certificate type is consistent with ciphersuite. For TLS 1.32153* skip check since TLS 1.3 ciphersuites can be used with any certificate2154* type.2155*/2156if (!SSL_CONNECTION_IS_TLS13(s)) {2157if ((clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0) {2158SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CERTIFICATE_TYPE);2159return WORK_ERROR;2160}2161}21622163if (!X509_up_ref(x)) {2164SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2165return WORK_ERROR;2166}21672168X509_free(s->session->peer);2169s->session->peer = x;2170s->session->verify_result = s->verify_result;2171/* Ensure there is no RPK */2172EVP_PKEY_free(s->session->peer_rpk);2173s->session->peer_rpk = NULL;21742175/* Save the current hash state for when we receive the CertificateVerify */2176if (SSL_CONNECTION_IS_TLS13(s)2177&& !ssl_handshake_hash(s, s->cert_verify_hash,2178sizeof(s->cert_verify_hash),2179&s->cert_verify_hash_len)) {2180/* SSLfatal() already called */;2181return WORK_ERROR;2182}2183return WORK_FINISHED_CONTINUE;2184}21852186#ifndef OPENSSL_NO_COMP_ALG2187MSG_PROCESS_RETURN tls_process_server_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)2188{2189MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;2190PACKET tmppkt;2191BUF_MEM *buf = BUF_MEM_new();21922193if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)2194ret = tls_process_server_certificate(sc, &tmppkt);21952196BUF_MEM_free(buf);2197return ret;2198}2199#endif22002201static int tls_process_ske_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)2202{2203#ifndef OPENSSL_NO_PSK2204PACKET psk_identity_hint;22052206/* PSK ciphersuites are preceded by an identity hint */22072208if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {2209SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2210return 0;2211}22122213/*2214* Store PSK identity hint for later use, hint is used in2215* tls_construct_client_key_exchange. Assume that the maximum length of2216* a PSK identity hint can be as long as the maximum length of a PSK2217* identity.2218*/2219if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {2220SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DATA_LENGTH_TOO_LONG);2221return 0;2222}22232224if (PACKET_remaining(&psk_identity_hint) == 0) {2225OPENSSL_free(s->session->psk_identity_hint);2226s->session->psk_identity_hint = NULL;2227} else if (!PACKET_strndup(&psk_identity_hint,2228&s->session->psk_identity_hint)) {2229SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2230return 0;2231}22322233return 1;2234#else2235SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2236return 0;2237#endif2238}22392240static int tls_process_ske_srp(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2241{2242#ifndef OPENSSL_NO_SRP2243PACKET prime, generator, salt, server_pub;22442245if (!PACKET_get_length_prefixed_2(pkt, &prime)2246|| !PACKET_get_length_prefixed_2(pkt, &generator)2247|| !PACKET_get_length_prefixed_1(pkt, &salt)2248|| !PACKET_get_length_prefixed_2(pkt, &server_pub)) {2249SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2250return 0;2251}22522253if ((s->srp_ctx.N = BN_bin2bn(PACKET_data(&prime),2254(int)PACKET_remaining(&prime), NULL))2255== NULL2256|| (s->srp_ctx.g = BN_bin2bn(PACKET_data(&generator),2257(int)PACKET_remaining(&generator), NULL))2258== NULL2259|| (s->srp_ctx.s = BN_bin2bn(PACKET_data(&salt),2260(int)PACKET_remaining(&salt), NULL))2261== NULL2262|| (s->srp_ctx.B = BN_bin2bn(PACKET_data(&server_pub),2263(int)PACKET_remaining(&server_pub), NULL))2264== NULL) {2265SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);2266return 0;2267}22682269if (!srp_verify_server_param(s)) {2270/* SSLfatal() already called */2271return 0;2272}22732274/* We must check if there is a certificate */2275if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))2276*pkey = tls_get_peer_pkey(s);22772278return 1;2279#else2280SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2281return 0;2282#endif2283}22842285static int tls_process_ske_dhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2286{2287PACKET prime, generator, pub_key;2288EVP_PKEY *peer_tmp = NULL;2289BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;2290EVP_PKEY_CTX *pctx = NULL;2291OSSL_PARAM *params = NULL;2292OSSL_PARAM_BLD *tmpl = NULL;2293SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);2294int ret = 0;22952296if (!PACKET_get_length_prefixed_2(pkt, &prime)2297|| !PACKET_get_length_prefixed_2(pkt, &generator)2298|| !PACKET_get_length_prefixed_2(pkt, &pub_key)) {2299SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2300return 0;2301}23022303p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);2304g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),2305NULL);2306bnpub_key = BN_bin2bn(PACKET_data(&pub_key),2307(int)PACKET_remaining(&pub_key), NULL);2308if (p == NULL || g == NULL || bnpub_key == NULL) {2309SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);2310goto err;2311}23122313tmpl = OSSL_PARAM_BLD_new();2314if (tmpl == NULL2315|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)2316|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)2317|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY,2318bnpub_key)2319|| (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {2320SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2321goto err;2322}23232324pctx = EVP_PKEY_CTX_new_from_name(sctx->libctx, "DH", sctx->propq);2325if (pctx == NULL) {2326SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2327goto err;2328}2329if (EVP_PKEY_fromdata_init(pctx) <= 02330|| EVP_PKEY_fromdata(pctx, &peer_tmp, EVP_PKEY_KEYPAIR, params) <= 0) {2331SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_DH_VALUE);2332goto err;2333}23342335EVP_PKEY_CTX_free(pctx);2336pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, peer_tmp, sctx->propq);2337if (pctx == NULL2338/*2339* EVP_PKEY_param_check() will verify that the DH params are using2340* a safe prime. In this context, because we're using ephemeral DH,2341* we're ok with it not being a safe prime.2342* EVP_PKEY_param_check_quick() skips the safe prime check.2343*/2344|| EVP_PKEY_param_check_quick(pctx) != 12345|| EVP_PKEY_public_check(pctx) != 1) {2346SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_DH_VALUE);2347goto err;2348}23492350if (!ssl_security(s, SSL_SECOP_TMP_DH,2351EVP_PKEY_get_security_bits(peer_tmp),23520, peer_tmp)) {2353SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);2354goto err;2355}23562357s->s3.peer_tmp = peer_tmp;2358peer_tmp = NULL;23592360/*2361* FIXME: This makes assumptions about which ciphersuites come with2362* public keys. We should have a less ad-hoc way of doing this2363*/2364if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))2365*pkey = tls_get_peer_pkey(s);2366/* else anonymous DH, so no certificate or pkey. */23672368ret = 1;23692370err:2371OSSL_PARAM_BLD_free(tmpl);2372OSSL_PARAM_free(params);2373EVP_PKEY_free(peer_tmp);2374EVP_PKEY_CTX_free(pctx);2375BN_free(p);2376BN_free(g);2377BN_free(bnpub_key);23782379return ret;2380}23812382static int tls_process_ske_ecdhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2383{2384PACKET encoded_pt;2385unsigned int curve_type, curve_id;23862387/*2388* Extract elliptic curve parameters and the server's ephemeral ECDH2389* public key. We only support named (not generic) curves and2390* ECParameters in this case is just three bytes.2391*/2392if (!PACKET_get_1(pkt, &curve_type) || !PACKET_get_net_2(pkt, &curve_id)) {2393SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);2394return 0;2395}2396/*2397* Check curve is named curve type and one of our preferences, if not2398* server has sent an invalid curve.2399*/2400if (curve_type != NAMED_CURVE_TYPE2401|| !tls1_check_group_id(s, curve_id, 1)) {2402SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);2403return 0;2404}24052406if ((s->s3.peer_tmp = ssl_generate_param_group(s, curve_id)) == NULL) {2407SSLfatal(s, SSL_AD_INTERNAL_ERROR,2408SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);2409return 0;2410}24112412if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {2413SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2414return 0;2415}24162417if (EVP_PKEY_set1_encoded_public_key(s->s3.peer_tmp,2418PACKET_data(&encoded_pt),2419PACKET_remaining(&encoded_pt))2420<= 0) {2421SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);2422return 0;2423}24242425/*2426* The ECC/TLS specification does not mention the use of DSA to sign2427* ECParameters in the server key exchange message. We do support RSA2428* and ECDSA.2429*/2430if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA)2431*pkey = tls_get_peer_pkey(s);2432else if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aRSA)2433*pkey = tls_get_peer_pkey(s);2434/* else anonymous ECDH, so no certificate or pkey. */24352436/* Cache the agreed upon group in the SSL_SESSION */2437s->session->kex_group = curve_id;2438return 1;2439}24402441MSG_PROCESS_RETURN tls_process_key_exchange(SSL_CONNECTION *s, PACKET *pkt)2442{2443long alg_k;2444EVP_PKEY *pkey = NULL;2445EVP_MD_CTX *md_ctx = NULL;2446EVP_PKEY_CTX *pctx = NULL;2447PACKET save_param_start, signature;2448SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);24492450alg_k = s->s3.tmp.new_cipher->algorithm_mkey;24512452save_param_start = *pkt;24532454EVP_PKEY_free(s->s3.peer_tmp);2455s->s3.peer_tmp = NULL;24562457if (alg_k & SSL_PSK) {2458if (!tls_process_ske_psk_preamble(s, pkt)) {2459/* SSLfatal() already called */2460goto err;2461}2462}24632464/* Nothing else to do for plain PSK or RSAPSK */2465if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {2466} else if (alg_k & SSL_kSRP) {2467if (!tls_process_ske_srp(s, pkt, &pkey)) {2468/* SSLfatal() already called */2469goto err;2470}2471} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {2472if (!tls_process_ske_dhe(s, pkt, &pkey)) {2473/* SSLfatal() already called */2474goto err;2475}2476} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {2477if (!tls_process_ske_ecdhe(s, pkt, &pkey)) {2478/* SSLfatal() already called */2479goto err;2480}2481} else if (alg_k) {2482SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);2483goto err;2484}24852486/* if it was signed, check the signature */2487if (pkey != NULL) {2488PACKET params;2489const EVP_MD *md = NULL;2490unsigned char *tbs;2491size_t tbslen;2492int rv;24932494/*2495* |pkt| now points to the beginning of the signature, so the difference2496* equals the length of the parameters.2497*/2498if (!PACKET_get_sub_packet(&save_param_start, ¶ms,2499PACKET_remaining(&save_param_start) - PACKET_remaining(pkt))) {2500SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);2501goto err;2502}25032504if (SSL_USE_SIGALGS(s)) {2505unsigned int sigalg;25062507if (!PACKET_get_net_2(pkt, &sigalg)) {2508SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);2509goto err;2510}2511if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {2512/* SSLfatal() already called */2513goto err;2514}2515} else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {2516SSLfatal(s, SSL_AD_INTERNAL_ERROR,2517SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);2518goto err;2519}25202521if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {2522SSLfatal(s, SSL_AD_INTERNAL_ERROR,2523SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);2524goto err;2525}2526if (SSL_USE_SIGALGS(s))2527OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",2528md == NULL ? "n/a" : EVP_MD_get0_name(md));25292530if (!PACKET_get_length_prefixed_2(pkt, &signature)2531|| PACKET_remaining(pkt) != 0) {2532SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2533goto err;2534}25352536md_ctx = EVP_MD_CTX_new();2537if (md_ctx == NULL) {2538SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2539goto err;2540}25412542if (EVP_DigestVerifyInit_ex(md_ctx, &pctx,2543md == NULL ? NULL : EVP_MD_get0_name(md),2544sctx->libctx, sctx->propq, pkey,2545NULL)2546<= 0) {2547SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2548goto err;2549}2550if (SSL_USE_PSS(s)) {2551if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 02552|| EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,2553RSA_PSS_SALTLEN_DIGEST)2554<= 0) {2555SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2556goto err;2557}2558}2559tbslen = construct_key_exchange_tbs(s, &tbs, PACKET_data(¶ms),2560PACKET_remaining(¶ms));2561if (tbslen == 0) {2562/* SSLfatal() already called */2563goto err;2564}25652566rv = EVP_DigestVerify(md_ctx, PACKET_data(&signature),2567PACKET_remaining(&signature), tbs, tbslen);2568OPENSSL_free(tbs);2569if (rv <= 0) {2570SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);2571goto err;2572}2573EVP_MD_CTX_free(md_ctx);2574md_ctx = NULL;2575} else {2576/* aNULL, aSRP or PSK do not need public keys */2577if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))2578&& !(alg_k & SSL_PSK)) {2579/* Might be wrong key type, check it */2580if (ssl3_check_cert_and_algorithm(s)) {2581SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DATA);2582}2583/* else this shouldn't happen, SSLfatal() already called */2584goto err;2585}2586/* still data left over */2587if (PACKET_remaining(pkt) != 0) {2588SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_EXTRA_DATA_IN_MESSAGE);2589goto err;2590}2591}25922593return MSG_PROCESS_CONTINUE_READING;2594err:2595EVP_MD_CTX_free(md_ctx);2596return MSG_PROCESS_ERROR;2597}25982599MSG_PROCESS_RETURN tls_process_certificate_request(SSL_CONNECTION *s,2600PACKET *pkt)2601{2602/* Clear certificate validity flags */2603if (s->s3.tmp.valid_flags != NULL)2604memset(s->s3.tmp.valid_flags, 0, s->ssl_pkey_num * sizeof(uint32_t));2605else2606s->s3.tmp.valid_flags = OPENSSL_zalloc(s->ssl_pkey_num * sizeof(uint32_t));26072608/* Give up for good if allocation didn't work */2609if (s->s3.tmp.valid_flags == NULL)2610return 0;26112612if (SSL_CONNECTION_IS_TLS13(s)) {2613PACKET reqctx, extensions;2614RAW_EXTENSION *rawexts = NULL;26152616if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {2617/*2618* We already sent close_notify. This can only happen in TLSv1.32619* post-handshake messages. We can't reasonably respond to this, so2620* we just ignore it2621*/2622return MSG_PROCESS_FINISHED_READING;2623}26242625/* Free and zero certificate types: it is not present in TLS 1.3 */2626OPENSSL_free(s->s3.tmp.ctype);2627s->s3.tmp.ctype = NULL;2628s->s3.tmp.ctype_len = 0;2629OPENSSL_free(s->pha_context);2630s->pha_context = NULL;2631s->pha_context_len = 0;26322633if (!PACKET_get_length_prefixed_1(pkt, &reqctx) || !PACKET_memdup(&reqctx, &s->pha_context, &s->pha_context_len)) {2634SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2635return MSG_PROCESS_ERROR;2636}26372638if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {2639SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);2640return MSG_PROCESS_ERROR;2641}2642if (!tls_collect_extensions(s, &extensions,2643SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,2644&rawexts, NULL, 1)2645|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,2646rawexts, NULL, 0, 1)) {2647/* SSLfatal() already called */2648OPENSSL_free(rawexts);2649return MSG_PROCESS_ERROR;2650}2651OPENSSL_free(rawexts);2652if (!tls1_process_sigalgs(s)) {2653SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);2654return MSG_PROCESS_ERROR;2655}2656} else {2657PACKET ctypes;26582659/* get the certificate types */2660if (!PACKET_get_length_prefixed_1(pkt, &ctypes)) {2661SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2662return MSG_PROCESS_ERROR;2663}26642665if (!PACKET_memdup(&ctypes, &s->s3.tmp.ctype, &s->s3.tmp.ctype_len)) {2666SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2667return MSG_PROCESS_ERROR;2668}26692670if (SSL_USE_SIGALGS(s)) {2671PACKET sigalgs;26722673if (!PACKET_get_length_prefixed_2(pkt, &sigalgs)) {2674SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2675return MSG_PROCESS_ERROR;2676}26772678/*2679* Despite this being for certificates, preserve compatibility2680* with pre-TLS 1.3 and use the regular sigalgs field.2681*/2682if (!tls1_save_sigalgs(s, &sigalgs, 0)) {2683SSLfatal(s, SSL_AD_INTERNAL_ERROR,2684SSL_R_SIGNATURE_ALGORITHMS_ERROR);2685return MSG_PROCESS_ERROR;2686}2687if (!tls1_process_sigalgs(s)) {2688SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);2689return MSG_PROCESS_ERROR;2690}2691}26922693/* get the CA RDNs */2694if (!parse_ca_names(s, pkt)) {2695/* SSLfatal() already called */2696return MSG_PROCESS_ERROR;2697}2698}26992700if (PACKET_remaining(pkt) != 0) {2701SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2702return MSG_PROCESS_ERROR;2703}27042705/* we should setup a certificate to return.... */2706s->s3.tmp.cert_req = 1;27072708/*2709* In TLSv1.3 we don't prepare the client certificate yet. We wait until2710* after the CertificateVerify message has been received. This is because2711* in TLSv1.3 the CertificateRequest arrives before the Certificate message2712* but in TLSv1.2 it is the other way around. We want to make sure that2713* SSL_get1_peer_certificate() returns something sensible in2714* client_cert_cb.2715*/2716if (SSL_CONNECTION_IS_TLS13(s)2717&& s->post_handshake_auth != SSL_PHA_REQUESTED)2718return MSG_PROCESS_CONTINUE_READING;27192720return MSG_PROCESS_CONTINUE_PROCESSING;2721}27222723MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL_CONNECTION *s,2724PACKET *pkt)2725{2726unsigned int ticklen;2727unsigned long ticket_lifetime_hint, age_add = 0;2728unsigned int sess_len;2729RAW_EXTENSION *exts = NULL;2730PACKET nonce;2731EVP_MD *sha256 = NULL;2732SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);27332734PACKET_null_init(&nonce);27352736if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)2737|| (SSL_CONNECTION_IS_TLS13(s)2738&& (!PACKET_get_net_4(pkt, &age_add)2739|| !PACKET_get_length_prefixed_1(pkt, &nonce)))2740|| !PACKET_get_net_2(pkt, &ticklen)2741|| (SSL_CONNECTION_IS_TLS13(s) ? (ticklen == 02742|| PACKET_remaining(pkt) < ticklen)2743: PACKET_remaining(pkt) != ticklen)) {2744SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2745goto err;2746}27472748/*2749* Server is allowed to change its mind (in <=TLSv1.2) and send an empty2750* ticket. We already checked this TLSv1.3 case above, so it should never2751* be 0 here in that instance2752*/2753if (ticklen == 0)2754return MSG_PROCESS_CONTINUE_READING;27552756/*2757* Sessions must be immutable once they go into the session cache. Otherwise2758* we can get multi-thread problems. Therefore we don't "update" sessions,2759* we replace them with a duplicate. In TLSv1.3 we need to do this every2760* time a NewSessionTicket arrives because those messages arrive2761* post-handshake and the session may have already gone into the session2762* cache.2763*/2764if (SSL_CONNECTION_IS_TLS13(s) || s->session->session_id_length > 0) {2765SSL_SESSION *new_sess;27662767/*2768* We reused an existing session, so we need to replace it with a new2769* one2770*/2771if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {2772SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);2773goto err;2774}27752776if ((s->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) != 02777&& !SSL_CONNECTION_IS_TLS13(s)) {2778/*2779* In TLSv1.2 and below the arrival of a new tickets signals that2780* any old ticket we were using is now out of date, so we remove the2781* old session from the cache. We carry on if this fails2782*/2783SSL_CTX_remove_session(s->session_ctx, s->session);2784}27852786SSL_SESSION_free(s->session);2787s->session = new_sess;2788}27892790s->session->time = ossl_time_now();2791ssl_session_calculate_timeout(s->session);27922793OPENSSL_free(s->session->ext.tick);2794s->session->ext.tick = NULL;2795s->session->ext.ticklen = 0;27962797s->session->ext.tick = OPENSSL_malloc(ticklen);2798if (s->session->ext.tick == NULL) {2799SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2800goto err;2801}2802if (!PACKET_copy_bytes(pkt, s->session->ext.tick, ticklen)) {2803SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2804goto err;2805}28062807s->session->ext.tick_lifetime_hint = ticket_lifetime_hint;2808s->session->ext.tick_age_add = age_add;2809s->session->ext.ticklen = ticklen;28102811if (SSL_CONNECTION_IS_TLS13(s)) {2812PACKET extpkt;28132814if (!PACKET_as_length_prefixed_2(pkt, &extpkt)2815|| PACKET_remaining(pkt) != 0) {2816SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2817goto err;2818}28192820if (!tls_collect_extensions(s, &extpkt,2821SSL_EXT_TLS1_3_NEW_SESSION_TICKET, &exts,2822NULL, 1)2823|| !tls_parse_all_extensions(s,2824SSL_EXT_TLS1_3_NEW_SESSION_TICKET,2825exts, NULL, 0, 1)) {2826/* SSLfatal() already called */2827goto err;2828}2829}28302831/*2832* There are two ways to detect a resumed ticket session. One is to set2833* an appropriate session ID and then the server must return a match in2834* ServerHello. This allows the normal client session ID matching to work2835* and we know much earlier that the ticket has been accepted. The2836* other way is to set zero length session ID when the ticket is2837* presented and rely on the handshake to determine session resumption.2838* We choose the former approach because this fits in with assumptions2839* elsewhere in OpenSSL. The session ID is set to the SHA256 hash of the2840* ticket.2841*/2842sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq);2843if (sha256 == NULL) {2844/* Error is already recorded */2845SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);2846goto err;2847}2848/*2849* We use sess_len here because EVP_Digest expects an int2850* but s->session->session_id_length is a size_t2851*/2852if (!EVP_Digest(s->session->ext.tick, ticklen,2853s->session->session_id, &sess_len,2854sha256, NULL)) {2855SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2856goto err;2857}2858EVP_MD_free(sha256);2859sha256 = NULL;2860s->session->session_id_length = sess_len;2861s->session->not_resumable = 0;28622863/* This is a standalone message in TLSv1.3, so there is no more to read */2864if (SSL_CONNECTION_IS_TLS13(s)) {2865const EVP_MD *md = ssl_handshake_md(s);2866int hashleni = EVP_MD_get_size(md);2867size_t hashlen;2868/* ASCII: "resumption", in hex for EBCDIC compatibility */2869static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,28700x70, 0x74, 0x69, 0x6F, 0x6E };28712872/* Ensure cast to size_t is safe */2873if (!ossl_assert(hashleni > 0)) {2874SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2875goto err;2876}2877hashlen = (size_t)hashleni;28782879if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,2880nonce_label,2881sizeof(nonce_label),2882PACKET_data(&nonce),2883PACKET_remaining(&nonce),2884s->session->master_key,2885hashlen, 1)) {2886/* SSLfatal() already called */2887goto err;2888}2889s->session->master_key_length = hashlen;28902891OPENSSL_free(exts);2892ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);2893return MSG_PROCESS_FINISHED_READING;2894}28952896return MSG_PROCESS_CONTINUE_READING;2897err:2898EVP_MD_free(sha256);2899OPENSSL_free(exts);2900return MSG_PROCESS_ERROR;2901}29022903/*2904* In TLSv1.3 this is called from the extensions code, otherwise it is used to2905* parse a separate message. Returns 1 on success or 0 on failure2906*/2907int tls_process_cert_status_body(SSL_CONNECTION *s, PACKET *pkt)2908{2909size_t resplen;2910unsigned int type;29112912if (!PACKET_get_1(pkt, &type)2913|| type != TLSEXT_STATUSTYPE_ocsp) {2914SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_UNSUPPORTED_STATUS_TYPE);2915return 0;2916}2917if (!PACKET_get_net_3_len(pkt, &resplen)2918|| PACKET_remaining(pkt) != resplen) {2919SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2920return 0;2921}2922s->ext.ocsp.resp = OPENSSL_malloc(resplen);2923if (s->ext.ocsp.resp == NULL) {2924s->ext.ocsp.resp_len = 0;2925SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2926return 0;2927}2928s->ext.ocsp.resp_len = resplen;2929if (!PACKET_copy_bytes(pkt, s->ext.ocsp.resp, resplen)) {2930SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2931return 0;2932}29332934return 1;2935}29362937MSG_PROCESS_RETURN tls_process_cert_status(SSL_CONNECTION *s, PACKET *pkt)2938{2939if (!tls_process_cert_status_body(s, pkt)) {2940/* SSLfatal() already called */2941return MSG_PROCESS_ERROR;2942}29432944return MSG_PROCESS_CONTINUE_READING;2945}29462947/*2948* Perform miscellaneous checks and processing after we have received the2949* server's initial flight. In TLS1.3 this is after the Server Finished message.2950* In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 02951* on failure.2952*/2953int tls_process_initial_server_flight(SSL_CONNECTION *s)2954{2955SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);29562957/*2958* at this point we check that we have the required stuff from2959* the server2960*/2961if (!ssl3_check_cert_and_algorithm(s)) {2962/* SSLfatal() already called */2963return 0;2964}29652966/*2967* Call the ocsp status callback if needed. The |ext.ocsp.resp| and2968* |ext.ocsp.resp_len| values will be set if we actually received a status2969* message, or NULL and -1 otherwise2970*/2971if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing2972&& sctx->ext.status_cb != NULL) {2973int ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),2974sctx->ext.status_arg);29752976if (ret == 0) {2977SSLfatal(s, SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE,2978SSL_R_INVALID_STATUS_RESPONSE);2979return 0;2980}2981if (ret < 0) {2982SSLfatal(s, SSL_AD_INTERNAL_ERROR,2983SSL_R_OCSP_CALLBACK_FAILURE);2984return 0;2985}2986}2987#ifndef OPENSSL_NO_CT2988if (s->ct_validation_callback != NULL) {2989/* Note we validate the SCTs whether or not we abort on error */2990if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {2991/* SSLfatal() already called */2992return 0;2993}2994}2995#endif29962997return 1;2998}29993000MSG_PROCESS_RETURN tls_process_server_done(SSL_CONNECTION *s, PACKET *pkt)3001{3002if (PACKET_remaining(pkt) > 0) {3003/* should contain no data */3004SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3005return MSG_PROCESS_ERROR;3006}3007#ifndef OPENSSL_NO_SRP3008if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {3009if (ssl_srp_calc_a_param_intern(s) <= 0) {3010SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SRP_A_CALC);3011return MSG_PROCESS_ERROR;3012}3013}3014#endif30153016if (!tls_process_initial_server_flight(s)) {3017/* SSLfatal() already called */3018return MSG_PROCESS_ERROR;3019}30203021return MSG_PROCESS_FINISHED_READING;3022}30233024static int tls_construct_cke_psk_preamble(SSL_CONNECTION *s, WPACKET *pkt)3025{3026#ifndef OPENSSL_NO_PSK3027int ret = 0;3028/*3029* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a3030* \0-terminated identity. The last byte is for us for simulating3031* strnlen.3032*/3033char identity[PSK_MAX_IDENTITY_LEN + 1];3034size_t identitylen = 0;3035unsigned char psk[PSK_MAX_PSK_LEN];3036unsigned char *tmppsk = NULL;3037char *tmpidentity = NULL;3038size_t psklen = 0;30393040if (s->psk_client_callback == NULL) {3041SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_CLIENT_CB);3042goto err;3043}30443045memset(identity, 0, sizeof(identity));30463047psklen = s->psk_client_callback(SSL_CONNECTION_GET_USER_SSL(s),3048s->session->psk_identity_hint,3049identity, sizeof(identity) - 1,3050psk, sizeof(psk));30513052if (psklen > PSK_MAX_PSK_LEN) {3053SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);3054psklen = PSK_MAX_PSK_LEN; /* Avoid overrunning the array on cleanse */3055goto err;3056} else if (psklen == 0) {3057SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_PSK_IDENTITY_NOT_FOUND);3058goto err;3059}30603061identitylen = strlen(identity);3062if (identitylen > PSK_MAX_IDENTITY_LEN) {3063SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3064goto err;3065}30663067tmppsk = OPENSSL_memdup(psk, psklen);3068tmpidentity = OPENSSL_strdup(identity);3069if (tmppsk == NULL || tmpidentity == NULL) {3070SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3071goto err;3072}30733074OPENSSL_free(s->s3.tmp.psk);3075s->s3.tmp.psk = tmppsk;3076s->s3.tmp.psklen = psklen;3077tmppsk = NULL;3078OPENSSL_free(s->session->psk_identity);3079s->session->psk_identity = tmpidentity;3080tmpidentity = NULL;30813082if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen)) {3083SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3084goto err;3085}30863087ret = 1;30883089err:3090OPENSSL_cleanse(psk, psklen);3091OPENSSL_cleanse(identity, sizeof(identity));3092OPENSSL_clear_free(tmppsk, psklen);3093OPENSSL_clear_free(tmpidentity, identitylen);30943095return ret;3096#else3097SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3098return 0;3099#endif3100}31013102static int tls_construct_cke_rsa(SSL_CONNECTION *s, WPACKET *pkt)3103{3104unsigned char *encdata = NULL;3105EVP_PKEY *pkey = NULL;3106EVP_PKEY_CTX *pctx = NULL;3107size_t enclen;3108unsigned char *pms = NULL;3109size_t pmslen = 0;3110SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);31113112if (!received_server_cert(s)) {3113/*3114* We should always have a server certificate with SSL_kRSA.3115*/3116SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3117return 0;3118}31193120if ((pkey = tls_get_peer_pkey(s)) == NULL) {3121SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3122return 0;3123}31243125if (!EVP_PKEY_is_a(pkey, "RSA")) {3126SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3127return 0;3128}31293130pmslen = SSL_MAX_MASTER_KEY_LENGTH;3131pms = OPENSSL_malloc(pmslen);3132if (pms == NULL) {3133SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3134return 0;3135}31363137pms[0] = s->client_version >> 8;3138pms[1] = s->client_version & 0xff;3139if (RAND_bytes_ex(sctx->libctx, pms + 2, pmslen - 2, 0) <= 0) {3140SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_RAND_LIB);3141goto err;3142}31433144/* Fix buf for TLS and beyond */3145if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {3146SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3147goto err;3148}31493150pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pkey, sctx->propq);3151if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 03152|| EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {3153SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3154goto err;3155}3156if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)3157|| EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {3158SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_RSA_ENCRYPT);3159goto err;3160}3161EVP_PKEY_CTX_free(pctx);3162pctx = NULL;31633164/* Fix buf for TLS and beyond */3165if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {3166SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3167goto err;3168}31693170/* Log the premaster secret, if logging is enabled. */3171if (!ssl_log_rsa_client_key_exchange(s, encdata, enclen, pms, pmslen)) {3172/* SSLfatal() already called */3173goto err;3174}31753176s->s3.tmp.pms = pms;3177s->s3.tmp.pmslen = pmslen;31783179return 1;3180err:3181OPENSSL_clear_free(pms, pmslen);3182EVP_PKEY_CTX_free(pctx);31833184return 0;3185}31863187static int tls_construct_cke_dhe(SSL_CONNECTION *s, WPACKET *pkt)3188{3189EVP_PKEY *ckey = NULL, *skey = NULL;3190unsigned char *keybytes = NULL;3191int prime_len;3192unsigned char *encoded_pub = NULL;3193size_t encoded_pub_len, pad_len;3194int ret = 0;31953196skey = s->s3.peer_tmp;3197if (skey == NULL) {3198SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3199goto err;3200}32013202ckey = ssl_generate_pkey(s, skey);3203if (ckey == NULL) {3204SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3205goto err;3206}32073208if (ssl_derive(s, ckey, skey, 0) == 0) {3209/* SSLfatal() already called */3210goto err;3211}32123213/* send off the data */32143215/* Generate encoding of server key */3216encoded_pub_len = EVP_PKEY_get1_encoded_public_key(ckey, &encoded_pub);3217if (encoded_pub_len == 0) {3218SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3219EVP_PKEY_free(ckey);3220return EXT_RETURN_FAIL;3221}32223223/*3224* For interoperability with some versions of the Microsoft TLS3225* stack, we need to zero pad the DHE pub key to the same length3226* as the prime.3227*/3228prime_len = EVP_PKEY_get_size(ckey);3229pad_len = prime_len - encoded_pub_len;3230if (pad_len > 0) {3231if (!WPACKET_sub_allocate_bytes_u16(pkt, pad_len, &keybytes)) {3232SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3233goto err;3234}3235memset(keybytes, 0, pad_len);3236}32373238if (!WPACKET_sub_memcpy_u16(pkt, encoded_pub, encoded_pub_len)) {3239SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3240goto err;3241}32423243ret = 1;3244err:3245OPENSSL_free(encoded_pub);3246EVP_PKEY_free(ckey);3247return ret;3248}32493250static int tls_construct_cke_ecdhe(SSL_CONNECTION *s, WPACKET *pkt)3251{3252unsigned char *encodedPoint = NULL;3253size_t encoded_pt_len = 0;3254EVP_PKEY *ckey = NULL, *skey = NULL;3255int ret = 0;32563257skey = s->s3.peer_tmp;3258if (skey == NULL) {3259SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3260return 0;3261}32623263ckey = ssl_generate_pkey(s, skey);3264if (ckey == NULL) {3265SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);3266goto err;3267}32683269if (ssl_derive(s, ckey, skey, 0) == 0) {3270/* SSLfatal() already called */3271goto err;3272}32733274/* Generate encoding of client key */3275encoded_pt_len = EVP_PKEY_get1_encoded_public_key(ckey, &encodedPoint);32763277if (encoded_pt_len == 0) {3278SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);3279goto err;3280}32813282if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {3283SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3284goto err;3285}32863287ret = 1;3288err:3289OPENSSL_free(encodedPoint);3290EVP_PKEY_free(ckey);3291return ret;3292}32933294static int tls_construct_cke_gost(SSL_CONNECTION *s, WPACKET *pkt)3295{3296#ifndef OPENSSL_NO_GOST3297/* GOST key exchange message creation */3298EVP_PKEY_CTX *pkey_ctx = NULL;3299EVP_PKEY *pkey = NULL;3300size_t msglen;3301unsigned int md_len;3302unsigned char shared_ukm[32], tmp[256];3303EVP_MD_CTX *ukm_hash = NULL;3304int dgst_nid = NID_id_GostR3411_94;3305unsigned char *pms = NULL;3306size_t pmslen = 0;3307SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);33083309if ((s->s3.tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)3310dgst_nid = NID_id_GostR3411_2012_256;33113312/*3313* Get server certificate PKEY and create ctx from it3314*/3315if ((pkey = tls_get_peer_pkey(s)) == NULL) {3316SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3317SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);3318return 0;3319}33203321pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,3322pkey,3323sctx->propq);3324if (pkey_ctx == NULL) {3325SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3326return 0;3327}3328/*3329* If we have send a certificate, and certificate key3330* parameters match those of server certificate, use3331* certificate key for key exchange3332*/33333334/* Otherwise, generate ephemeral key pair */3335pmslen = 32;3336pms = OPENSSL_malloc(pmslen);3337if (pms == NULL) {3338SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3339goto err;3340}33413342if (EVP_PKEY_encrypt_init(pkey_ctx) <= 03343/* Generate session key3344*/3345|| RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {3346SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3347goto err;3348};3349/*3350* Compute shared IV and store it in algorithm-specific context3351* data3352*/3353ukm_hash = EVP_MD_CTX_new();3354if (ukm_hash == NULL3355|| EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 03356|| EVP_DigestUpdate(ukm_hash, s->s3.client_random,3357SSL3_RANDOM_SIZE)3358<= 03359|| EVP_DigestUpdate(ukm_hash, s->s3.server_random,3360SSL3_RANDOM_SIZE)3361<= 03362|| EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {3363SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3364goto err;3365}3366EVP_MD_CTX_free(ukm_hash);3367ukm_hash = NULL;3368if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3369EVP_PKEY_CTRL_SET_IV, 8, shared_ukm)3370<= 0) {3371SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3372goto err;3373}3374/* Make GOST keytransport blob message */3375/*3376* Encapsulate it into sequence3377*/3378msglen = 255;3379if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {3380SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3381goto err;3382}33833384if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)3385|| (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))3386|| !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {3387SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3388goto err;3389}33903391EVP_PKEY_CTX_free(pkey_ctx);3392s->s3.tmp.pms = pms;3393s->s3.tmp.pmslen = pmslen;33943395return 1;3396err:3397EVP_PKEY_CTX_free(pkey_ctx);3398OPENSSL_clear_free(pms, pmslen);3399EVP_MD_CTX_free(ukm_hash);3400return 0;3401#else3402SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3403return 0;3404#endif3405}34063407#ifndef OPENSSL_NO_GOST3408int ossl_gost18_cke_cipher_nid(const SSL_CONNECTION *s)3409{3410if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_MAGMA) != 0)3411return NID_magma_ctr;3412else if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_KUZNYECHIK) != 0)3413return NID_kuznyechik_ctr;34143415return NID_undef;3416}34173418int ossl_gost_ukm(const SSL_CONNECTION *s, unsigned char *dgst_buf)3419{3420EVP_MD_CTX *hash = NULL;3421unsigned int md_len;3422SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);3423const EVP_MD *md = ssl_evp_md_fetch(sctx->libctx, NID_id_GostR3411_2012_256,3424sctx->propq);34253426if (md == NULL)3427return 0;34283429if ((hash = EVP_MD_CTX_new()) == NULL3430|| EVP_DigestInit(hash, md) <= 03431|| EVP_DigestUpdate(hash, s->s3.client_random, SSL3_RANDOM_SIZE) <= 03432|| EVP_DigestUpdate(hash, s->s3.server_random, SSL3_RANDOM_SIZE) <= 03433|| EVP_DigestFinal_ex(hash, dgst_buf, &md_len) <= 0) {3434EVP_MD_CTX_free(hash);3435ssl_evp_md_free(md);3436return 0;3437}34383439EVP_MD_CTX_free(hash);3440ssl_evp_md_free(md);3441return 1;3442}3443#endif34443445static int tls_construct_cke_gost18(SSL_CONNECTION *s, WPACKET *pkt)3446{3447#ifndef OPENSSL_NO_GOST3448/* GOST 2018 key exchange message creation */3449unsigned char rnd_dgst[32];3450unsigned char *encdata = NULL;3451EVP_PKEY_CTX *pkey_ctx = NULL;3452EVP_PKEY *pkey;3453unsigned char *pms = NULL;3454size_t pmslen = 0;3455size_t msglen;3456int cipher_nid = ossl_gost18_cke_cipher_nid(s);3457SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);34583459if (cipher_nid == NID_undef) {3460SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3461return 0;3462}34633464if (ossl_gost_ukm(s, rnd_dgst) <= 0) {3465SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3466goto err;3467}34683469/* Pre-master secret - random bytes */3470pmslen = 32;3471pms = OPENSSL_malloc(pmslen);3472if (pms == NULL) {3473SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3474goto err;3475}34763477if (RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {3478SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3479goto err;3480}34813482/* Get server certificate PKEY and create ctx from it */3483if ((pkey = tls_get_peer_pkey(s)) == NULL) {3484SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3485SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);3486goto err;3487}34883489pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,3490pkey,3491sctx->propq);3492if (pkey_ctx == NULL) {3493SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3494goto err;3495}34963497if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0) {3498SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3499goto err;3500};35013502/* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code */3503if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3504EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)3505<= 0) {3506SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3507goto err;3508}35093510if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3511EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)3512<= 0) {3513SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3514goto err;3515}35163517if (EVP_PKEY_encrypt(pkey_ctx, NULL, &msglen, pms, pmslen) <= 0) {3518SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3519goto err;3520}35213522if (!WPACKET_allocate_bytes(pkt, msglen, &encdata)3523|| EVP_PKEY_encrypt(pkey_ctx, encdata, &msglen, pms, pmslen) <= 0) {3524SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3525goto err;3526}35273528EVP_PKEY_CTX_free(pkey_ctx);3529pkey_ctx = NULL;3530s->s3.tmp.pms = pms;3531s->s3.tmp.pmslen = pmslen;35323533return 1;3534err:3535EVP_PKEY_CTX_free(pkey_ctx);3536OPENSSL_clear_free(pms, pmslen);3537return 0;3538#else3539SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3540return 0;3541#endif3542}35433544static int tls_construct_cke_srp(SSL_CONNECTION *s, WPACKET *pkt)3545{3546#ifndef OPENSSL_NO_SRP3547unsigned char *abytes = NULL;35483549if (s->srp_ctx.A == NULL3550|| !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),3551&abytes)) {3552SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3553return 0;3554}3555BN_bn2bin(s->srp_ctx.A, abytes);35563557OPENSSL_free(s->session->srp_username);3558s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);3559if (s->session->srp_username == NULL) {3560SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3561return 0;3562}35633564return 1;3565#else3566SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3567return 0;3568#endif3569}35703571CON_FUNC_RETURN tls_construct_client_key_exchange(SSL_CONNECTION *s,3572WPACKET *pkt)3573{3574unsigned long alg_k;35753576alg_k = s->s3.tmp.new_cipher->algorithm_mkey;35773578/*3579* All of the construct functions below call SSLfatal() if necessary so3580* no need to do so here.3581*/3582if ((alg_k & SSL_PSK)3583&& !tls_construct_cke_psk_preamble(s, pkt))3584goto err;35853586if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {3587if (!tls_construct_cke_rsa(s, pkt))3588goto err;3589} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {3590if (!tls_construct_cke_dhe(s, pkt))3591goto err;3592} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {3593if (!tls_construct_cke_ecdhe(s, pkt))3594goto err;3595} else if (alg_k & SSL_kGOST) {3596if (!tls_construct_cke_gost(s, pkt))3597goto err;3598} else if (alg_k & SSL_kGOST18) {3599if (!tls_construct_cke_gost18(s, pkt))3600goto err;3601} else if (alg_k & SSL_kSRP) {3602if (!tls_construct_cke_srp(s, pkt))3603goto err;3604} else if (!(alg_k & SSL_kPSK)) {3605SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3606goto err;3607}36083609return CON_FUNC_SUCCESS;3610err:3611OPENSSL_clear_free(s->s3.tmp.pms, s->s3.tmp.pmslen);3612s->s3.tmp.pms = NULL;3613s->s3.tmp.pmslen = 0;3614#ifndef OPENSSL_NO_PSK3615OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);3616s->s3.tmp.psk = NULL;3617s->s3.tmp.psklen = 0;3618#endif3619return CON_FUNC_ERROR;3620}36213622int tls_client_key_exchange_post_work(SSL_CONNECTION *s)3623{3624unsigned char *pms = NULL;3625size_t pmslen = 0;36263627pms = s->s3.tmp.pms;3628pmslen = s->s3.tmp.pmslen;36293630#ifndef OPENSSL_NO_SRP3631/* Check for SRP */3632if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {3633if (!srp_generate_client_master_secret(s)) {3634/* SSLfatal() already called */3635goto err;3636}3637return 1;3638}3639#endif36403641if (pms == NULL && !(s->s3.tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {3642SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_PASSED_INVALID_ARGUMENT);3643goto err;3644}3645if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {3646/* SSLfatal() already called */3647/* ssl_generate_master_secret frees the pms even on error */3648pms = NULL;3649pmslen = 0;3650goto err;3651}3652pms = NULL;3653pmslen = 0;36543655#ifndef OPENSSL_NO_SCTP3656if (SSL_CONNECTION_IS_DTLS(s)) {3657unsigned char sctpauthkey[64];3658char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];3659size_t labellen;3660SSL *ssl = SSL_CONNECTION_GET_SSL(s);36613662/*3663* Add new shared key for SCTP-Auth, will be ignored if no SCTP3664* used.3665*/3666memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,3667sizeof(DTLS1_SCTP_AUTH_LABEL));36683669/* Don't include the terminating zero. */3670labellen = sizeof(labelbuffer) - 1;3671if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)3672labellen += 1;36733674if (SSL_export_keying_material(ssl, sctpauthkey,3675sizeof(sctpauthkey), labelbuffer,3676labellen, NULL, 0, 0)3677<= 0) {3678SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3679goto err;3680}36813682BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,3683sizeof(sctpauthkey), sctpauthkey);3684}3685#endif36863687return 1;3688err:3689OPENSSL_clear_free(pms, pmslen);3690s->s3.tmp.pms = NULL;3691s->s3.tmp.pmslen = 0;3692return 0;3693}36943695/*3696* Check a certificate can be used for client authentication. Currently check3697* cert exists, if we have a suitable digest for TLS 1.2 if static DH client3698* certificates can be used and optionally checks suitability for Suite B.3699*/3700static int ssl3_check_client_certificate(SSL_CONNECTION *s)3701{3702/* If no suitable signature algorithm can't use certificate */3703if (!tls_choose_sigalg(s, 0) || s->s3.tmp.sigalg == NULL)3704return 0;3705/*3706* If strict mode check suitability of chain before using it. This also3707* adjusts suite B digest if necessary.3708*/3709if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT && !tls1_check_chain(s, NULL, NULL, NULL, -2))3710return 0;3711return 1;3712}37133714WORK_STATE tls_prepare_client_certificate(SSL_CONNECTION *s, WORK_STATE wst)3715{3716X509 *x509 = NULL;3717EVP_PKEY *pkey = NULL;3718int i;3719SSL *ssl = SSL_CONNECTION_GET_SSL(s);37203721if (wst == WORK_MORE_A) {3722/* Let cert callback update client certificates if required */3723if (s->cert->cert_cb) {3724i = s->cert->cert_cb(ssl, s->cert->cert_cb_arg);3725if (i < 0) {3726s->rwstate = SSL_X509_LOOKUP;3727return WORK_MORE_A;3728}3729if (i == 0) {3730SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);3731return WORK_ERROR;3732}3733s->rwstate = SSL_NOTHING;3734}3735if (ssl3_check_client_certificate(s)) {3736if (s->post_handshake_auth == SSL_PHA_REQUESTED) {3737return WORK_FINISHED_STOP;3738}3739return WORK_FINISHED_CONTINUE;3740}37413742/* Fall through to WORK_MORE_B */3743wst = WORK_MORE_B;3744}37453746/* We need to get a client cert */3747if (wst == WORK_MORE_B) {3748/*3749* If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;3750* return(-1); We then get retied later3751*/3752i = ssl_do_client_cert_cb(s, &x509, &pkey);3753if (i < 0) {3754s->rwstate = SSL_X509_LOOKUP;3755return WORK_MORE_B;3756}3757s->rwstate = SSL_NOTHING;3758if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {3759if (!SSL_use_certificate(ssl, x509)3760|| !SSL_use_PrivateKey(ssl, pkey))3761i = 0;3762} else if (i == 1) {3763i = 0;3764ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);3765}37663767X509_free(x509);3768EVP_PKEY_free(pkey);3769if (i && !ssl3_check_client_certificate(s))3770i = 0;3771if (i == 0) {3772if (s->version == SSL3_VERSION) {3773s->s3.tmp.cert_req = 0;3774ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);3775return WORK_FINISHED_CONTINUE;3776} else {3777s->s3.tmp.cert_req = 2;3778s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;3779if (!ssl3_digest_cached_records(s, 0)) {3780/* SSLfatal() already called */3781return WORK_ERROR;3782}3783}3784}37853786if (!SSL_CONNECTION_IS_TLS13(s)3787|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)3788s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;37893790if (s->post_handshake_auth == SSL_PHA_REQUESTED)3791return WORK_FINISHED_STOP;3792return WORK_FINISHED_CONTINUE;3793}37943795/* Shouldn't ever get here */3796SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3797return WORK_ERROR;3798}37993800CON_FUNC_RETURN tls_construct_client_certificate(SSL_CONNECTION *s,3801WPACKET *pkt)3802{3803CERT_PKEY *cpk = NULL;3804SSL *ssl = SSL_CONNECTION_GET_SSL(s);38053806if (SSL_CONNECTION_IS_TLS13(s)) {3807if (s->pha_context == NULL) {3808/* no context available, add 0-length context */3809if (!WPACKET_put_bytes_u8(pkt, 0)) {3810SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3811return CON_FUNC_ERROR;3812}3813} else if (!WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {3814SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3815return CON_FUNC_ERROR;3816}3817}3818if (s->s3.tmp.cert_req != 2)3819cpk = s->cert->key;3820switch (s->ext.client_cert_type) {3821case TLSEXT_cert_type_rpk:3822if (!tls_output_rpk(s, pkt, cpk)) {3823/* SSLfatal() already called */3824return CON_FUNC_ERROR;3825}3826break;3827case TLSEXT_cert_type_x509:3828if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {3829/* SSLfatal() already called */3830return CON_FUNC_ERROR;3831}3832break;3833default:3834SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3835return CON_FUNC_ERROR;3836}38373838/*3839* If we attempted to write early data or we're in middlebox compat mode3840* then we deferred changing the handshake write keys to the last possible3841* moment. We need to do it now.3842*/3843if (SSL_CONNECTION_IS_TLS13(s)3844&& !SSL_IS_QUIC_HANDSHAKE(s)3845&& SSL_IS_FIRST_HANDSHAKE(s)3846&& (s->early_data_state != SSL_EARLY_DATA_NONE3847|| (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)3848&& (!ssl->method->ssl3_enc->change_cipher_state(s,3849SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {3850/*3851* This is a fatal error, which leaves enc_write_ctx in an inconsistent3852* state and thus ssl3_send_alert may crash.3853*/3854SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);3855return CON_FUNC_ERROR;3856}38573858return CON_FUNC_SUCCESS;3859}38603861#ifndef OPENSSL_NO_COMP_ALG3862CON_FUNC_RETURN tls_construct_client_compressed_certificate(SSL_CONNECTION *sc,3863WPACKET *pkt)3864{3865SSL *ssl = SSL_CONNECTION_GET_SSL(sc);3866WPACKET tmppkt;3867BUF_MEM *buf = NULL;3868size_t length;3869size_t max_length;3870COMP_METHOD *method;3871COMP_CTX *comp = NULL;3872int comp_len;3873int ret = 0;3874int alg = sc->ext.compress_certificate_from_peer[0];38753876/* Note that sc->s3.tmp.cert_req == 2 is checked in write transition */38773878if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init(&tmppkt, buf))3879goto err;38803881/* Use the |tmppkt| for the to-be-compressed data */3882if (sc->pha_context == NULL) {3883/* no context available, add 0-length context */3884if (!WPACKET_put_bytes_u8(&tmppkt, 0))3885goto err;3886} else if (!WPACKET_sub_memcpy_u8(&tmppkt, sc->pha_context, sc->pha_context_len))3887goto err;38883889if (!ssl3_output_cert_chain(sc, &tmppkt, sc->cert->key, 0)) {3890/* SSLfatal() already called */3891goto out;3892}38933894/* continue with the real |pkt| */3895if (!WPACKET_put_bytes_u16(pkt, alg)3896|| !WPACKET_get_total_written(&tmppkt, &length)3897|| !WPACKET_put_bytes_u24(pkt, length))3898goto err;38993900switch (alg) {3901case TLSEXT_comp_cert_zlib:3902method = COMP_zlib_oneshot();3903break;3904case TLSEXT_comp_cert_brotli:3905method = COMP_brotli_oneshot();3906break;3907case TLSEXT_comp_cert_zstd:3908method = COMP_zstd_oneshot();3909break;3910default:3911goto err;3912}3913max_length = ossl_calculate_comp_expansion(alg, length);39143915if ((comp = COMP_CTX_new(method)) == NULL3916|| !WPACKET_start_sub_packet_u24(pkt)3917|| !WPACKET_reserve_bytes(pkt, max_length, NULL))3918goto err;39193920comp_len = COMP_compress_block(comp, WPACKET_get_curr(pkt), max_length,3921(unsigned char *)buf->data, length);3922if (comp_len <= 0)3923goto err;39243925if (!WPACKET_allocate_bytes(pkt, comp_len, NULL)3926|| !WPACKET_close(pkt))3927goto err;39283929/*3930* If we attempted to write early data or we're in middlebox compat mode3931* then we deferred changing the handshake write keys to the last possible3932* moment. We need to do it now.3933*/3934if (SSL_IS_FIRST_HANDSHAKE(sc)3935&& !SSL_IS_QUIC_HANDSHAKE(sc)3936&& (sc->early_data_state != SSL_EARLY_DATA_NONE3937|| (sc->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)3938&& (!ssl->method->ssl3_enc->change_cipher_state(sc,3939SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {3940/*3941* This is a fatal error, which leaves sc->enc_write_ctx in an3942* inconsistent state and thus ssl3_send_alert may crash.3943*/3944SSLfatal(sc, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);3945goto out;3946}3947ret = 1;3948goto out;39493950err:3951SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3952out:3953if (buf != NULL) {3954/* If |buf| is NULL, then |tmppkt| could not have been initialized */3955WPACKET_cleanup(&tmppkt);3956}3957BUF_MEM_free(buf);3958COMP_CTX_free(comp);3959return ret;3960}3961#endif39623963int ssl3_check_cert_and_algorithm(SSL_CONNECTION *s)3964{3965const SSL_CERT_LOOKUP *clu;3966size_t idx;3967long alg_k, alg_a;3968EVP_PKEY *pkey;39693970alg_k = s->s3.tmp.new_cipher->algorithm_mkey;3971alg_a = s->s3.tmp.new_cipher->algorithm_auth;39723973/* we don't have a certificate */3974if (!(alg_a & SSL_aCERT))3975return 1;39763977/* This is the passed certificate */3978pkey = tls_get_peer_pkey(s);3979clu = ssl_cert_lookup_by_pkey(pkey, &idx, SSL_CONNECTION_GET_CTX(s));39803981/* Check certificate is recognised and suitable for cipher */3982if (clu == NULL || (alg_a & clu->amask) == 0) {3983SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_SIGNING_CERT);3984return 0;3985}39863987if (alg_k & (SSL_kRSA | SSL_kRSAPSK) && idx != SSL_PKEY_RSA) {3988SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3989SSL_R_MISSING_RSA_ENCRYPTING_CERT);3990return 0;3991}39923993if ((alg_k & SSL_kDHE) && (s->s3.peer_tmp == NULL)) {3994SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3995return 0;3996}39973998/* Early out to skip the checks below */3999if (s->session->peer_rpk != NULL)4000return 1;40014002if (clu->amask & SSL_aECDSA) {4003if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s))4004return 1;4005SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_ECC_CERT);4006return 0;4007}40084009return 1;4010}40114012#ifndef OPENSSL_NO_NEXTPROTONEG4013CON_FUNC_RETURN tls_construct_next_proto(SSL_CONNECTION *s, WPACKET *pkt)4014{4015size_t len, padding_len;4016unsigned char *padding = NULL;40174018len = s->ext.npn_len;4019padding_len = 32 - ((len + 2) % 32);40204021if (!WPACKET_sub_memcpy_u8(pkt, s->ext.npn, len)4022|| !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {4023SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4024return CON_FUNC_ERROR;4025}40264027memset(padding, 0, padding_len);40284029return CON_FUNC_SUCCESS;4030}4031#endif40324033MSG_PROCESS_RETURN tls_process_hello_req(SSL_CONNECTION *s, PACKET *pkt)4034{4035SSL *ssl = SSL_CONNECTION_GET_SSL(s);40364037if (PACKET_remaining(pkt) > 0) {4038/* should contain no data */4039SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4040return MSG_PROCESS_ERROR;4041}40424043if ((s->options & SSL_OP_NO_RENEGOTIATION)) {4044ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);4045return MSG_PROCESS_FINISHED_READING;4046}40474048/*4049* This is a historical discrepancy (not in the RFC) maintained for4050* compatibility reasons. If a TLS client receives a HelloRequest it will4051* attempt an abbreviated handshake. However if a DTLS client receives a4052* HelloRequest it will do a full handshake. Either behaviour is reasonable4053* but doing one for TLS and another for DTLS is odd.4054*/4055if (SSL_CONNECTION_IS_DTLS(s))4056SSL_renegotiate(ssl);4057else4058SSL_renegotiate_abbreviated(ssl);40594060return MSG_PROCESS_FINISHED_READING;4061}40624063static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,4064PACKET *pkt)4065{4066PACKET extensions;4067RAW_EXTENSION *rawexts = NULL;40684069if (!PACKET_as_length_prefixed_2(pkt, &extensions)4070|| PACKET_remaining(pkt) != 0) {4071SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4072goto err;4073}40744075if (!tls_collect_extensions(s, &extensions,4076SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, &rawexts,4077NULL, 1)4078|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,4079rawexts, NULL, 0, 1)) {4080/* SSLfatal() already called */4081goto err;4082}40834084OPENSSL_free(rawexts);4085return MSG_PROCESS_CONTINUE_READING;40864087err:4088OPENSSL_free(rawexts);4089return MSG_PROCESS_ERROR;4090}40914092int ssl_do_client_cert_cb(SSL_CONNECTION *s, X509 **px509, EVP_PKEY **ppkey)4093{4094int i = 0;4095SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);40964097#ifndef OPENSSL_NO_ENGINE4098if (sctx->client_cert_engine) {4099i = tls_engine_load_ssl_client_cert(s, px509, ppkey);4100if (i != 0)4101return i;4102}4103#endif4104if (sctx->client_cert_cb)4105i = sctx->client_cert_cb(SSL_CONNECTION_GET_USER_SSL(s), px509, ppkey);4106return i;4107}41084109int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,4110WPACKET *pkt)4111{4112int i;4113size_t totlen = 0, len, maxlen, maxverok = 0;4114int empty_reneg_info_scsv = !s->renegotiate4115&& !SSL_CONNECTION_IS_DTLS(s)4116&& ssl_security(s, SSL_SECOP_VERSION, 0, TLS1_VERSION, NULL)4117&& s->min_proto_version <= TLS1_VERSION;4118SSL *ssl = SSL_CONNECTION_GET_SSL(s);41194120/* Set disabled masks for this session */4121if (!ssl_set_client_disabled(s)) {4122SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_PROTOCOLS_AVAILABLE);4123return 0;4124}41254126if (sk == NULL) {4127SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4128return 0;4129}41304131#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH4132#if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 64133#error Max cipher length too short4134#endif4135/*4136* Some servers hang if client hello > 256 bytes as hack workaround4137* chop number of supported ciphers to keep it well below this if we4138* use TLS v1.24139*/4140if (TLS1_get_version(ssl) >= TLS1_2_VERSION)4141maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;4142else4143#endif4144/* Maximum length that can be stored in 2 bytes. Length must be even */4145maxlen = 0xfffe;41464147if (empty_reneg_info_scsv)4148maxlen -= 2;4149if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)4150maxlen -= 2;41514152for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {4153const SSL_CIPHER *c;41544155c = sk_SSL_CIPHER_value(sk, i);4156/* Skip disabled ciphers */4157if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))4158continue;41594160if (!ssl->method->put_cipher_by_char(c, pkt, &len)) {4161SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4162return 0;4163}41644165/* Sanity check that the maximum version we offer has ciphers enabled */4166if (!maxverok) {4167int minproto = SSL_CONNECTION_IS_DTLS(s) ? c->min_dtls : c->min_tls;4168int maxproto = SSL_CONNECTION_IS_DTLS(s) ? c->max_dtls : c->max_tls;41694170if (ssl_version_cmp(s, maxproto, s->s3.tmp.max_ver) >= 04171&& ssl_version_cmp(s, minproto, s->s3.tmp.max_ver) <= 0)4172maxverok = 1;4173}41744175totlen += len;4176}41774178if (totlen == 0 || !maxverok) {4179const char *maxvertext = !maxverok4180? "No ciphers enabled for max supported SSL/TLS version"4181: NULL;41824183SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_CIPHERS_AVAILABLE,4184maxvertext);4185return 0;4186}41874188if (totlen != 0) {4189if (empty_reneg_info_scsv) {4190static const SSL_CIPHER scsv = {41910, NULL, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 04192};4193if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {4194SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4195return 0;4196}4197}4198if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {4199static const SSL_CIPHER scsv = {42000, NULL, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 04201};4202if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {4203SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4204return 0;4205}4206}4207}42084209return 1;4210}42114212CON_FUNC_RETURN tls_construct_end_of_early_data(SSL_CONNECTION *s, WPACKET *pkt)4213{4214if (s->early_data_state != SSL_EARLY_DATA_WRITE_RETRY4215&& s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING) {4216SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);4217return CON_FUNC_ERROR;4218}42194220s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;4221return CON_FUNC_SUCCESS;4222}422342244225