Path: blob/main/crypto/openssl/ssl/statem/statem_clnt.c
48266 views
/*1* Copyright 1995-2025 The OpenSSL Project Authors. All Rights Reserved.2* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved3* Copyright 2005 Nokia. All rights reserved.4*5* Licensed under the Apache License 2.0 (the "License"). You may not use6* this file except in compliance with the License. You can obtain a copy7* in the file LICENSE in the source distribution or at8* https://www.openssl.org/source/license.html9*/1011#include <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_kECDHEPSK81| SSL_kSRP)) {82return 1;83}8485return 0;86}8788/*89* ossl_statem_client_read_transition() encapsulates the logic for the allowed90* handshake state transitions when a TLS1.3 client is reading messages from the91* server. The message type that the server has sent is provided in |mt|. The92* current state is in |s->statem.hand_state|.93*94* Return values are 1 for success (transition allowed) and 0 on error95* (transition not allowed)96*/97static int ossl_statem_client13_read_transition(SSL_CONNECTION *s, int mt)98{99OSSL_STATEM *st = &s->statem;100101/*102* Note: There is no case for TLS_ST_CW_CLNT_HELLO, because we haven't103* yet negotiated TLSv1.3 at that point so that is handled by104* ossl_statem_client_read_transition()105*/106107switch (st->hand_state) {108default:109break;110111case TLS_ST_CW_CLNT_HELLO:112/*113* This must a ClientHello following a HelloRetryRequest, so the only114* thing we can get now is a ServerHello.115*/116if (mt == SSL3_MT_SERVER_HELLO) {117st->hand_state = TLS_ST_CR_SRVR_HELLO;118return 1;119}120break;121122case TLS_ST_CR_SRVR_HELLO:123if (mt == SSL3_MT_ENCRYPTED_EXTENSIONS) {124st->hand_state = TLS_ST_CR_ENCRYPTED_EXTENSIONS;125return 1;126}127break;128129case TLS_ST_CR_ENCRYPTED_EXTENSIONS:130if (s->hit) {131if (mt == SSL3_MT_FINISHED) {132st->hand_state = TLS_ST_CR_FINISHED;133return 1;134}135} else {136if (mt == SSL3_MT_CERTIFICATE_REQUEST) {137st->hand_state = TLS_ST_CR_CERT_REQ;138return 1;139}140if (mt == SSL3_MT_CERTIFICATE) {141st->hand_state = TLS_ST_CR_CERT;142return 1;143}144#ifndef OPENSSL_NO_COMP_ALG145if (mt == SSL3_MT_COMPRESSED_CERTIFICATE146&& s->ext.compress_certificate_sent) {147st->hand_state = TLS_ST_CR_COMP_CERT;148return 1;149}150#endif151}152break;153154case TLS_ST_CR_CERT_REQ:155if (mt == SSL3_MT_CERTIFICATE) {156st->hand_state = TLS_ST_CR_CERT;157return 1;158}159#ifndef OPENSSL_NO_COMP_ALG160if (mt == SSL3_MT_COMPRESSED_CERTIFICATE161&& s->ext.compress_certificate_sent) {162st->hand_state = TLS_ST_CR_COMP_CERT;163return 1;164}165#endif166break;167168case TLS_ST_CR_CERT:169case TLS_ST_CR_COMP_CERT:170if (mt == SSL3_MT_CERTIFICATE_VERIFY) {171st->hand_state = TLS_ST_CR_CERT_VRFY;172return 1;173}174break;175176case TLS_ST_CR_CERT_VRFY:177if (mt == SSL3_MT_FINISHED) {178st->hand_state = TLS_ST_CR_FINISHED;179return 1;180}181break;182183case TLS_ST_OK:184if (mt == SSL3_MT_NEWSESSION_TICKET) {185st->hand_state = TLS_ST_CR_SESSION_TICKET;186return 1;187}188if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {189st->hand_state = TLS_ST_CR_KEY_UPDATE;190return 1;191}192if (mt == SSL3_MT_CERTIFICATE_REQUEST) {193#if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION194/* Restore digest for PHA before adding message.*/195# error Internal DTLS version error196#endif197if (!SSL_CONNECTION_IS_DTLS(s)198&& s->post_handshake_auth == SSL_PHA_EXT_SENT) {199s->post_handshake_auth = SSL_PHA_REQUESTED;200/*201* In TLS, this is called before the message is added to the202* digest. In DTLS, this is expected to be called after adding203* to the digest. Either move the digest restore, or add the204* message here after the swap, or do it after the clientFinished?205*/206if (!tls13_restore_handshake_digest_for_pha(s)) {207/* SSLfatal() already called */208return 0;209}210st->hand_state = TLS_ST_CR_CERT_REQ;211return 1;212}213}214break;215}216217/* No valid transition found */218return 0;219}220221/*222* ossl_statem_client_read_transition() encapsulates the logic for the allowed223* handshake state transitions when the client is reading messages from the224* server. The message type that the server has sent is provided in |mt|. The225* current state is in |s->statem.hand_state|.226*227* Return values are 1 for success (transition allowed) and 0 on error228* (transition not allowed)229*/230int ossl_statem_client_read_transition(SSL_CONNECTION *s, int mt)231{232OSSL_STATEM *st = &s->statem;233int ske_expected;234235/*236* Note that after writing the first ClientHello we don't know what version237* we are going to negotiate yet, so we don't take this branch until later.238*/239if (SSL_CONNECTION_IS_TLS13(s)) {240if (!ossl_statem_client13_read_transition(s, mt))241goto err;242return 1;243}244245switch (st->hand_state) {246default:247break;248249case TLS_ST_CW_CLNT_HELLO:250if (mt == SSL3_MT_SERVER_HELLO) {251st->hand_state = TLS_ST_CR_SRVR_HELLO;252return 1;253}254255if (SSL_CONNECTION_IS_DTLS(s)) {256if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {257st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;258return 1;259}260}261break;262263case TLS_ST_EARLY_DATA:264/*265* We've not actually selected TLSv1.3 yet, but we have sent early266* data. The only thing allowed now is a ServerHello or a267* HelloRetryRequest.268*/269if (mt == SSL3_MT_SERVER_HELLO) {270st->hand_state = TLS_ST_CR_SRVR_HELLO;271return 1;272}273break;274275case TLS_ST_CR_SRVR_HELLO:276if (s->hit) {277if (s->ext.ticket_expected) {278if (mt == SSL3_MT_NEWSESSION_TICKET) {279st->hand_state = TLS_ST_CR_SESSION_TICKET;280return 1;281}282} else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {283st->hand_state = TLS_ST_CR_CHANGE;284return 1;285}286} else {287if (SSL_CONNECTION_IS_DTLS(s)288&& mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {289st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;290return 1;291} else if (s->version >= TLS1_VERSION292&& s->ext.session_secret_cb != NULL293&& s->session->ext.tick != NULL294&& mt == SSL3_MT_CHANGE_CIPHER_SPEC) {295/*296* Normally, we can tell if the server is resuming the session297* from the session ID. EAP-FAST (RFC 4851), however, relies on298* the next server message after the ServerHello to determine if299* the server is resuming.300*/301s->hit = 1;302st->hand_state = TLS_ST_CR_CHANGE;303return 1;304} else if (!(s->s3.tmp.new_cipher->algorithm_auth305& (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {306if (mt == SSL3_MT_CERTIFICATE) {307st->hand_state = TLS_ST_CR_CERT;308return 1;309}310} else {311ske_expected = key_exchange_expected(s);312/* SKE is optional for some PSK ciphersuites */313if (ske_expected314|| ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)315&& mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {316if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {317st->hand_state = TLS_ST_CR_KEY_EXCH;318return 1;319}320} else if (mt == SSL3_MT_CERTIFICATE_REQUEST321&& cert_req_allowed(s)) {322st->hand_state = TLS_ST_CR_CERT_REQ;323return 1;324} else if (mt == SSL3_MT_SERVER_DONE) {325st->hand_state = TLS_ST_CR_SRVR_DONE;326return 1;327}328}329}330break;331332case TLS_ST_CR_CERT:333case TLS_ST_CR_COMP_CERT:334/*335* The CertificateStatus message is optional even if336* |ext.status_expected| is set337*/338if (s->ext.status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {339st->hand_state = TLS_ST_CR_CERT_STATUS;340return 1;341}342/* Fall through */343344case TLS_ST_CR_CERT_STATUS:345ske_expected = key_exchange_expected(s);346/* SKE is optional for some PSK ciphersuites */347if (ske_expected || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)348&& mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {349if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {350st->hand_state = TLS_ST_CR_KEY_EXCH;351return 1;352}353goto err;354}355/* Fall through */356357case TLS_ST_CR_KEY_EXCH:358if (mt == SSL3_MT_CERTIFICATE_REQUEST) {359if (cert_req_allowed(s)) {360st->hand_state = TLS_ST_CR_CERT_REQ;361return 1;362}363goto err;364}365/* Fall through */366367case TLS_ST_CR_CERT_REQ:368if (mt == SSL3_MT_SERVER_DONE) {369st->hand_state = TLS_ST_CR_SRVR_DONE;370return 1;371}372break;373374case TLS_ST_CW_FINISHED:375if (s->ext.ticket_expected) {376if (mt == SSL3_MT_NEWSESSION_TICKET) {377st->hand_state = TLS_ST_CR_SESSION_TICKET;378return 1;379}380} else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {381st->hand_state = TLS_ST_CR_CHANGE;382return 1;383}384break;385386case TLS_ST_CR_SESSION_TICKET:387if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {388st->hand_state = TLS_ST_CR_CHANGE;389return 1;390}391break;392393case TLS_ST_CR_CHANGE:394if (mt == SSL3_MT_FINISHED) {395st->hand_state = TLS_ST_CR_FINISHED;396return 1;397}398break;399400case TLS_ST_OK:401if (mt == SSL3_MT_HELLO_REQUEST) {402st->hand_state = TLS_ST_CR_HELLO_REQ;403return 1;404}405break;406}407408err:409/* No valid transition found */410if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {411BIO *rbio;412413/*414* CCS messages don't have a message sequence number so this is probably415* because of an out-of-order CCS. We'll just drop it.416*/417s->init_num = 0;418s->rwstate = SSL_READING;419rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));420BIO_clear_retry_flags(rbio);421BIO_set_retry_read(rbio);422return 0;423}424SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);425return 0;426}427428static int do_compressed_cert(SSL_CONNECTION *sc)429{430/* If we negotiated RPK, we won't try to compress it */431return sc->ext.client_cert_type == TLSEXT_cert_type_x509432&& sc->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none;433}434435/*436* ossl_statem_client13_write_transition() works out what handshake state to437* move to next when the TLSv1.3 client is writing messages to be sent to the438* server.439*/440static WRITE_TRAN ossl_statem_client13_write_transition(SSL_CONNECTION *s)441{442OSSL_STATEM *st = &s->statem;443444/*445* Note: There are no cases for TLS_ST_BEFORE because we haven't negotiated446* TLSv1.3 yet at that point. They are handled by447* ossl_statem_client_write_transition().448*/449switch (st->hand_state) {450default:451/* Shouldn't happen */452SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);453return WRITE_TRAN_ERROR;454455case TLS_ST_CR_CERT_REQ:456if (s->post_handshake_auth == SSL_PHA_REQUESTED) {457if (do_compressed_cert(s))458st->hand_state = TLS_ST_CW_COMP_CERT;459else460st->hand_state = TLS_ST_CW_CERT;461return WRITE_TRAN_CONTINUE;462}463/*464* We should only get here if we received a CertificateRequest after465* we already sent close_notify466*/467if (!ossl_assert((s->shutdown & SSL_SENT_SHUTDOWN) != 0)) {468/* Shouldn't happen - same as default case */469SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);470return WRITE_TRAN_ERROR;471}472st->hand_state = TLS_ST_OK;473return WRITE_TRAN_CONTINUE;474475case TLS_ST_CR_FINISHED:476if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY477|| s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING)478st->hand_state = TLS_ST_PENDING_EARLY_DATA_END;479else if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0480&& s->hello_retry_request == SSL_HRR_NONE)481st->hand_state = TLS_ST_CW_CHANGE;482else if (s->s3.tmp.cert_req == 0)483st->hand_state = TLS_ST_CW_FINISHED;484else if (do_compressed_cert(s))485st->hand_state = TLS_ST_CW_COMP_CERT;486else487st->hand_state = TLS_ST_CW_CERT;488489s->ts_msg_read = ossl_time_now();490return WRITE_TRAN_CONTINUE;491492case TLS_ST_PENDING_EARLY_DATA_END:493if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED && !SSL_NO_EOED(s)) {494st->hand_state = TLS_ST_CW_END_OF_EARLY_DATA;495return WRITE_TRAN_CONTINUE;496}497/* Fall through */498499case TLS_ST_CW_END_OF_EARLY_DATA:500case TLS_ST_CW_CHANGE:501if (s->s3.tmp.cert_req == 0)502st->hand_state = TLS_ST_CW_FINISHED;503else if (do_compressed_cert(s))504st->hand_state = TLS_ST_CW_COMP_CERT;505else506st->hand_state = TLS_ST_CW_CERT;507return WRITE_TRAN_CONTINUE;508509case TLS_ST_CW_COMP_CERT:510case TLS_ST_CW_CERT:511/* If a non-empty Certificate we also send CertificateVerify */512st->hand_state = (s->s3.tmp.cert_req == 1) ? TLS_ST_CW_CERT_VRFY513: TLS_ST_CW_FINISHED;514return WRITE_TRAN_CONTINUE;515516case TLS_ST_CW_CERT_VRFY:517st->hand_state = TLS_ST_CW_FINISHED;518return WRITE_TRAN_CONTINUE;519520case TLS_ST_CR_KEY_UPDATE:521case TLS_ST_CW_KEY_UPDATE:522case TLS_ST_CR_SESSION_TICKET:523case TLS_ST_CW_FINISHED:524st->hand_state = TLS_ST_OK;525return WRITE_TRAN_CONTINUE;526527case TLS_ST_OK:528if (s->key_update != SSL_KEY_UPDATE_NONE) {529st->hand_state = TLS_ST_CW_KEY_UPDATE;530return WRITE_TRAN_CONTINUE;531}532533/* Try to read from the server instead */534return WRITE_TRAN_FINISHED;535}536}537538/*539* ossl_statem_client_write_transition() works out what handshake state to540* move to next when the client is writing messages to be sent to the server.541*/542WRITE_TRAN ossl_statem_client_write_transition(SSL_CONNECTION *s)543{544OSSL_STATEM *st = &s->statem;545546/*547* Note that immediately before/after a ClientHello we don't know what548* version we are going to negotiate yet, so we don't take this branch until549* later550*/551if (SSL_CONNECTION_IS_TLS13(s))552return ossl_statem_client13_write_transition(s);553554switch (st->hand_state) {555default:556/* Shouldn't happen */557SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);558return WRITE_TRAN_ERROR;559560case TLS_ST_OK:561if (!s->renegotiate) {562/*563* We haven't requested a renegotiation ourselves so we must have564* received a message from the server. Better read it.565*/566return WRITE_TRAN_FINISHED;567}568/* Renegotiation */569/* fall thru */570case TLS_ST_BEFORE:571st->hand_state = TLS_ST_CW_CLNT_HELLO;572return WRITE_TRAN_CONTINUE;573574case TLS_ST_CW_CLNT_HELLO:575if (s->early_data_state == SSL_EARLY_DATA_CONNECTING576&& !SSL_IS_QUIC_HANDSHAKE(s)) {577/*578* We are assuming this is a TLSv1.3 connection, although we haven't579* actually selected a version yet.580*/581if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)582st->hand_state = TLS_ST_CW_CHANGE;583else584st->hand_state = TLS_ST_EARLY_DATA;585return WRITE_TRAN_CONTINUE;586}587/*588* No transition at the end of writing because we don't know what589* we will be sent590*/591s->ts_msg_write = ossl_time_now();592return WRITE_TRAN_FINISHED;593594case TLS_ST_CR_SRVR_HELLO:595/*596* We only get here in TLSv1.3. We just received an HRR, so issue a597* CCS unless middlebox compat mode is off, or we already issued one598* because we did early data.599*/600if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0601&& s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING)602st->hand_state = TLS_ST_CW_CHANGE;603else604st->hand_state = TLS_ST_CW_CLNT_HELLO;605return WRITE_TRAN_CONTINUE;606607case TLS_ST_EARLY_DATA:608s->ts_msg_write = ossl_time_now();609return WRITE_TRAN_FINISHED;610611case DTLS_ST_CR_HELLO_VERIFY_REQUEST:612st->hand_state = TLS_ST_CW_CLNT_HELLO;613return WRITE_TRAN_CONTINUE;614615case TLS_ST_CR_SRVR_DONE:616s->ts_msg_read = ossl_time_now();617if (s->s3.tmp.cert_req)618st->hand_state = TLS_ST_CW_CERT;619else620st->hand_state = TLS_ST_CW_KEY_EXCH;621return WRITE_TRAN_CONTINUE;622623case TLS_ST_CW_CERT:624st->hand_state = TLS_ST_CW_KEY_EXCH;625return WRITE_TRAN_CONTINUE;626627case TLS_ST_CW_KEY_EXCH:628/*629* For TLS, cert_req is set to 2, so a cert chain of nothing is630* sent, but no verify packet is sent631*/632/*633* XXX: For now, we do not support client authentication in ECDH634* cipher suites with ECDH (rather than ECDSA) certificates. We635* need to skip the certificate verify message when client's636* ECDH public key is sent inside the client certificate.637*/638if (s->s3.tmp.cert_req == 1) {639st->hand_state = TLS_ST_CW_CERT_VRFY;640} else {641st->hand_state = TLS_ST_CW_CHANGE;642}643if (s->s3.flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {644st->hand_state = TLS_ST_CW_CHANGE;645}646return WRITE_TRAN_CONTINUE;647648case TLS_ST_CW_CERT_VRFY:649st->hand_state = TLS_ST_CW_CHANGE;650return WRITE_TRAN_CONTINUE;651652case TLS_ST_CW_CHANGE:653if (s->hello_retry_request == SSL_HRR_PENDING) {654st->hand_state = TLS_ST_CW_CLNT_HELLO;655} else if (s->early_data_state == SSL_EARLY_DATA_CONNECTING) {656st->hand_state = TLS_ST_EARLY_DATA;657} else {658#if defined(OPENSSL_NO_NEXTPROTONEG)659st->hand_state = TLS_ST_CW_FINISHED;660#else661if (!SSL_CONNECTION_IS_DTLS(s) && s->s3.npn_seen)662st->hand_state = TLS_ST_CW_NEXT_PROTO;663else664st->hand_state = TLS_ST_CW_FINISHED;665#endif666}667return WRITE_TRAN_CONTINUE;668669#if !defined(OPENSSL_NO_NEXTPROTONEG)670case TLS_ST_CW_NEXT_PROTO:671st->hand_state = TLS_ST_CW_FINISHED;672return WRITE_TRAN_CONTINUE;673#endif674675case TLS_ST_CW_FINISHED:676if (s->hit) {677st->hand_state = TLS_ST_OK;678return WRITE_TRAN_CONTINUE;679} else {680return WRITE_TRAN_FINISHED;681}682683case TLS_ST_CR_FINISHED:684if (s->hit) {685st->hand_state = TLS_ST_CW_CHANGE;686return WRITE_TRAN_CONTINUE;687} else {688st->hand_state = TLS_ST_OK;689return WRITE_TRAN_CONTINUE;690}691692case TLS_ST_CR_HELLO_REQ:693/*694* If we can renegotiate now then do so, otherwise wait for a more695* convenient time.696*/697if (ssl3_renegotiate_check(SSL_CONNECTION_GET_SSL(s), 1)) {698if (!tls_setup_handshake(s)) {699/* SSLfatal() already called */700return WRITE_TRAN_ERROR;701}702st->hand_state = TLS_ST_CW_CLNT_HELLO;703return WRITE_TRAN_CONTINUE;704}705st->hand_state = TLS_ST_OK;706return WRITE_TRAN_CONTINUE;707}708}709710/*711* Perform any pre work that needs to be done prior to sending a message from712* the client to the server.713*/714WORK_STATE ossl_statem_client_pre_work(SSL_CONNECTION *s, WORK_STATE wst)715{716OSSL_STATEM *st = &s->statem;717718switch (st->hand_state) {719default:720/* No pre work to be done */721break;722723case TLS_ST_CW_CLNT_HELLO:724s->shutdown = 0;725if (SSL_CONNECTION_IS_DTLS(s)) {726/* every DTLS ClientHello resets Finished MAC */727if (!ssl3_init_finished_mac(s)) {728/* SSLfatal() already called */729return WORK_ERROR;730}731} else if (s->ext.early_data == SSL_EARLY_DATA_REJECTED) {732/*733* This must be a second ClientHello after an HRR following an734* earlier rejected attempt to send early data. Since we were735* previously encrypting the early data we now need to reset the736* write record layer in order to write in plaintext again.737*/738if (!ssl_set_new_record_layer(s,739TLS_ANY_VERSION,740OSSL_RECORD_DIRECTION_WRITE,741OSSL_RECORD_PROTECTION_LEVEL_NONE,742NULL, 0, NULL, 0, NULL, 0, NULL, 0,743NULL, 0, NID_undef, NULL, NULL,744NULL)) {745/* SSLfatal already called */746return WORK_ERROR;747}748}749break;750751case TLS_ST_CW_CHANGE:752if (SSL_CONNECTION_IS_DTLS(s)) {753if (s->hit) {754/*755* We're into the last flight so we don't retransmit these756* messages unless we need to.757*/758st->use_timer = 0;759}760#ifndef OPENSSL_NO_SCTP761if (BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))) {762/* Calls SSLfatal() as required */763return dtls_wait_for_dry(s);764}765#endif766}767break;768769case TLS_ST_PENDING_EARLY_DATA_END:770/*771* If we've been called by SSL_do_handshake()/SSL_write(), or we did not772* attempt to write early data before calling SSL_read() then we press773* on with the handshake. Otherwise we pause here.774*/775if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING776|| s->early_data_state == SSL_EARLY_DATA_NONE)777return WORK_FINISHED_CONTINUE;778/* Fall through */779780case TLS_ST_EARLY_DATA:781return tls_finish_handshake(s, wst, 0, 1);782783case TLS_ST_OK:784/* Calls SSLfatal() as required */785return tls_finish_handshake(s, wst, 1, 1);786}787788return WORK_FINISHED_CONTINUE;789}790791/*792* Perform any work that needs to be done after sending a message from the793* client to the server.794*/795WORK_STATE ossl_statem_client_post_work(SSL_CONNECTION *s, WORK_STATE wst)796{797OSSL_STATEM *st = &s->statem;798SSL *ssl = SSL_CONNECTION_GET_SSL(s);799800s->init_num = 0;801802switch (st->hand_state) {803default:804/* No post work to be done */805break;806807case TLS_ST_CW_CLNT_HELLO:808if (s->early_data_state == SSL_EARLY_DATA_CONNECTING809&& s->max_early_data > 0) {810/*811* We haven't selected TLSv1.3 yet so we don't call the change812* cipher state function associated with the SSL_METHOD. Instead813* we call tls13_change_cipher_state() directly.814*/815if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0) {816if (!tls13_change_cipher_state(s,817SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {818/* SSLfatal() already called */819return WORK_ERROR;820}821}822/* else we're in compat mode so we delay flushing until after CCS */823} else if (!statem_flush(s)) {824return WORK_MORE_A;825}826827if (SSL_CONNECTION_IS_DTLS(s)) {828/* Treat the next message as the first packet */829s->first_packet = 1;830}831break;832833case TLS_ST_CW_KEY_EXCH:834if (tls_client_key_exchange_post_work(s) == 0) {835/* SSLfatal() already called */836return WORK_ERROR;837}838break;839840case TLS_ST_CW_CHANGE:841if (SSL_CONNECTION_IS_TLS13(s)842|| s->hello_retry_request == SSL_HRR_PENDING)843break;844if (s->early_data_state == SSL_EARLY_DATA_CONNECTING845&& s->max_early_data > 0) {846/*847* We haven't selected TLSv1.3 yet so we don't call the change848* cipher state function associated with the SSL_METHOD. Instead849* we call tls13_change_cipher_state() directly.850*/851if (!tls13_change_cipher_state(s,852SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE))853return WORK_ERROR;854break;855}856s->session->cipher = s->s3.tmp.new_cipher;857#ifdef OPENSSL_NO_COMP858s->session->compress_meth = 0;859#else860if (s->s3.tmp.new_compression == NULL)861s->session->compress_meth = 0;862else863s->session->compress_meth = s->s3.tmp.new_compression->id;864#endif865if (!ssl->method->ssl3_enc->setup_key_block(s)) {866/* SSLfatal() already called */867return WORK_ERROR;868}869870if (!ssl->method->ssl3_enc->change_cipher_state(s,871SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {872/* SSLfatal() already called */873return WORK_ERROR;874}875876#ifndef OPENSSL_NO_SCTP877if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {878/*879* Change to new shared key of SCTP-Auth, will be ignored if880* no SCTP used.881*/882BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,8830, NULL);884}885#endif886break;887888case TLS_ST_CW_FINISHED:889#ifndef OPENSSL_NO_SCTP890if (wst == WORK_MORE_A && SSL_CONNECTION_IS_DTLS(s) && s->hit == 0) {891/*892* Change to new shared key of SCTP-Auth, will be ignored if893* no SCTP used.894*/895BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,8960, NULL);897}898#endif899if (statem_flush(s) != 1)900return WORK_MORE_B;901902if (SSL_CONNECTION_IS_TLS13(s)) {903if (!tls13_save_handshake_digest_for_pha(s)) {904/* SSLfatal() already called */905return WORK_ERROR;906}907if (s->post_handshake_auth != SSL_PHA_REQUESTED) {908if (!ssl->method->ssl3_enc->change_cipher_state(s,909SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {910/* SSLfatal() already called */911return WORK_ERROR;912}913/*914* For QUIC we deferred setting up these keys until now so915* that we can ensure write keys are always set up before read916* keys.917*/918if (SSL_IS_QUIC_HANDSHAKE(s)919&& !ssl->method->ssl3_enc->change_cipher_state(s,920SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {921/* SSLfatal() already called */922return WORK_ERROR;923}924}925}926break;927928case TLS_ST_CW_KEY_UPDATE:929if (statem_flush(s) != 1)930return WORK_MORE_A;931if (!tls13_update_key(s, 1)) {932/* SSLfatal() already called */933return WORK_ERROR;934}935break;936}937938return WORK_FINISHED_CONTINUE;939}940941/*942* Get the message construction function and message type for sending from the943* client944*945* Valid return values are:946* 1: Success947* 0: Error948*/949int ossl_statem_client_construct_message(SSL_CONNECTION *s,950confunc_f *confunc, int *mt)951{952OSSL_STATEM *st = &s->statem;953954switch (st->hand_state) {955default:956/* Shouldn't happen */957SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);958return 0;959960case TLS_ST_CW_CHANGE:961if (SSL_CONNECTION_IS_DTLS(s))962*confunc = dtls_construct_change_cipher_spec;963else964*confunc = tls_construct_change_cipher_spec;965*mt = SSL3_MT_CHANGE_CIPHER_SPEC;966break;967968case TLS_ST_CW_CLNT_HELLO:969*confunc = tls_construct_client_hello;970*mt = SSL3_MT_CLIENT_HELLO;971break;972973case TLS_ST_CW_END_OF_EARLY_DATA:974*confunc = tls_construct_end_of_early_data;975*mt = SSL3_MT_END_OF_EARLY_DATA;976break;977978case TLS_ST_PENDING_EARLY_DATA_END:979*confunc = NULL;980*mt = SSL3_MT_DUMMY;981break;982983case TLS_ST_CW_CERT:984*confunc = tls_construct_client_certificate;985*mt = SSL3_MT_CERTIFICATE;986break;987988#ifndef OPENSSL_NO_COMP_ALG989case TLS_ST_CW_COMP_CERT:990*confunc = tls_construct_client_compressed_certificate;991*mt = SSL3_MT_COMPRESSED_CERTIFICATE;992break;993#endif994995case TLS_ST_CW_KEY_EXCH:996*confunc = tls_construct_client_key_exchange;997*mt = SSL3_MT_CLIENT_KEY_EXCHANGE;998break;9991000case TLS_ST_CW_CERT_VRFY:1001*confunc = tls_construct_cert_verify;1002*mt = SSL3_MT_CERTIFICATE_VERIFY;1003break;10041005#if !defined(OPENSSL_NO_NEXTPROTONEG)1006case TLS_ST_CW_NEXT_PROTO:1007*confunc = tls_construct_next_proto;1008*mt = SSL3_MT_NEXT_PROTO;1009break;1010#endif1011case TLS_ST_CW_FINISHED:1012*confunc = tls_construct_finished;1013*mt = SSL3_MT_FINISHED;1014break;10151016case TLS_ST_CW_KEY_UPDATE:1017*confunc = tls_construct_key_update;1018*mt = SSL3_MT_KEY_UPDATE;1019break;1020}10211022return 1;1023}10241025/*1026* Returns the maximum allowed length for the current message that we are1027* reading. Excludes the message header.1028*/1029size_t ossl_statem_client_max_message_size(SSL_CONNECTION *s)1030{1031OSSL_STATEM *st = &s->statem;10321033switch (st->hand_state) {1034default:1035/* Shouldn't happen */1036return 0;10371038case TLS_ST_CR_SRVR_HELLO:1039return SERVER_HELLO_MAX_LENGTH;10401041case DTLS_ST_CR_HELLO_VERIFY_REQUEST:1042return HELLO_VERIFY_REQUEST_MAX_LENGTH;10431044case TLS_ST_CR_COMP_CERT:1045case TLS_ST_CR_CERT:1046return s->max_cert_list;10471048case TLS_ST_CR_CERT_VRFY:1049return CERTIFICATE_VERIFY_MAX_LENGTH;10501051case TLS_ST_CR_CERT_STATUS:1052return SSL3_RT_MAX_PLAIN_LENGTH;10531054case TLS_ST_CR_KEY_EXCH:1055return SERVER_KEY_EXCH_MAX_LENGTH;10561057case TLS_ST_CR_CERT_REQ:1058/*1059* Set to s->max_cert_list for compatibility with previous releases. In1060* practice these messages can get quite long if servers are configured1061* to provide a long list of acceptable CAs1062*/1063return s->max_cert_list;10641065case TLS_ST_CR_SRVR_DONE:1066return SERVER_HELLO_DONE_MAX_LENGTH;10671068case TLS_ST_CR_CHANGE:1069if (s->version == DTLS1_BAD_VER)1070return 3;1071return CCS_MAX_LENGTH;10721073case TLS_ST_CR_SESSION_TICKET:1074return (SSL_CONNECTION_IS_TLS13(s)) ? SESSION_TICKET_MAX_LENGTH_TLS131075: SESSION_TICKET_MAX_LENGTH_TLS12;10761077case TLS_ST_CR_FINISHED:1078return FINISHED_MAX_LENGTH;10791080case TLS_ST_CR_ENCRYPTED_EXTENSIONS:1081return ENCRYPTED_EXTENSIONS_MAX_LENGTH;10821083case TLS_ST_CR_KEY_UPDATE:1084return KEY_UPDATE_MAX_LENGTH;1085}1086}10871088/*1089* Process a message that the client has received from the server.1090*/1091MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL_CONNECTION *s,1092PACKET *pkt)1093{1094OSSL_STATEM *st = &s->statem;10951096switch (st->hand_state) {1097default:1098/* Shouldn't happen */1099SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1100return MSG_PROCESS_ERROR;11011102case TLS_ST_CR_SRVR_HELLO:1103return tls_process_server_hello(s, pkt);11041105case DTLS_ST_CR_HELLO_VERIFY_REQUEST:1106return dtls_process_hello_verify(s, pkt);11071108case TLS_ST_CR_CERT:1109return tls_process_server_certificate(s, pkt);11101111#ifndef OPENSSL_NO_COMP_ALG1112case TLS_ST_CR_COMP_CERT:1113return tls_process_server_compressed_certificate(s, pkt);1114#endif11151116case TLS_ST_CR_CERT_VRFY:1117return tls_process_cert_verify(s, pkt);11181119case TLS_ST_CR_CERT_STATUS:1120return tls_process_cert_status(s, pkt);11211122case TLS_ST_CR_KEY_EXCH:1123return tls_process_key_exchange(s, pkt);11241125case TLS_ST_CR_CERT_REQ:1126return tls_process_certificate_request(s, pkt);11271128case TLS_ST_CR_SRVR_DONE:1129return tls_process_server_done(s, pkt);11301131case TLS_ST_CR_CHANGE:1132return tls_process_change_cipher_spec(s, pkt);11331134case TLS_ST_CR_SESSION_TICKET:1135return tls_process_new_session_ticket(s, pkt);11361137case TLS_ST_CR_FINISHED:1138return tls_process_finished(s, pkt);11391140case TLS_ST_CR_HELLO_REQ:1141return tls_process_hello_req(s, pkt);11421143case TLS_ST_CR_ENCRYPTED_EXTENSIONS:1144return tls_process_encrypted_extensions(s, pkt);11451146case TLS_ST_CR_KEY_UPDATE:1147return tls_process_key_update(s, pkt);1148}1149}11501151/*1152* Perform any further processing required following the receipt of a message1153* from the server1154*/1155WORK_STATE ossl_statem_client_post_process_message(SSL_CONNECTION *s,1156WORK_STATE wst)1157{1158OSSL_STATEM *st = &s->statem;11591160switch (st->hand_state) {1161default:1162/* Shouldn't happen */1163SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1164return WORK_ERROR;11651166case TLS_ST_CR_CERT:1167case TLS_ST_CR_COMP_CERT:1168return tls_post_process_server_certificate(s, wst);11691170case TLS_ST_CR_CERT_VRFY:1171case TLS_ST_CR_CERT_REQ:1172return tls_prepare_client_certificate(s, wst);1173}1174}11751176CON_FUNC_RETURN tls_construct_client_hello(SSL_CONNECTION *s, WPACKET *pkt)1177{1178unsigned char *p;1179size_t sess_id_len;1180int i, protverr;1181#ifndef OPENSSL_NO_COMP1182SSL_COMP *comp;1183#endif1184SSL_SESSION *sess = s->session;1185unsigned char *session_id;1186SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);11871188/* Work out what SSL/TLS/DTLS version to use */1189protverr = ssl_set_client_hello_version(s);1190if (protverr != 0) {1191SSLfatal(s, SSL_AD_INTERNAL_ERROR, protverr);1192return CON_FUNC_ERROR;1193}11941195if (sess == NULL1196|| !ssl_version_supported(s, sess->ssl_version, NULL)1197|| !SSL_SESSION_is_resumable(sess)) {1198if (s->hello_retry_request == SSL_HRR_NONE1199&& !ssl_get_new_session(s, 0)) {1200/* SSLfatal() already called */1201return CON_FUNC_ERROR;1202}1203}1204/* else use the pre-loaded session */12051206p = s->s3.client_random;12071208/*1209* for DTLS if client_random is initialized, reuse it, we are1210* required to use same upon reply to HelloVerify1211*/1212if (SSL_CONNECTION_IS_DTLS(s)) {1213size_t idx;1214i = 1;1215for (idx = 0; idx < sizeof(s->s3.client_random); idx++) {1216if (p[idx]) {1217i = 0;1218break;1219}1220}1221} else {1222i = (s->hello_retry_request == SSL_HRR_NONE);1223}12241225if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3.client_random),1226DOWNGRADE_NONE) <= 0) {1227SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1228return CON_FUNC_ERROR;1229}12301231/*-1232* version indicates the negotiated version: for example from1233* an SSLv2/v3 compatible client hello). The client_version1234* field is the maximum version we permit and it is also1235* used in RSA encrypted premaster secrets. Some servers can1236* choke if we initially report a higher version then1237* renegotiate to a lower one in the premaster secret. This1238* didn't happen with TLS 1.0 as most servers supported it1239* but it can with TLS 1.1 or later if the server only supports1240* 1.0.1241*1242* Possible scenario with previous logic:1243* 1. Client hello indicates TLS 1.21244* 2. Server hello says TLS 1.01245* 3. RSA encrypted premaster secret uses 1.2.1246* 4. Handshake proceeds using TLS 1.0.1247* 5. Server sends hello request to renegotiate.1248* 6. Client hello indicates TLS v1.0 as we now1249* know that is maximum server supports.1250* 7. Server chokes on RSA encrypted premaster secret1251* containing version 1.0.1252*1253* For interoperability it should be OK to always use the1254* maximum version we support in client hello and then rely1255* on the checking of version to ensure the servers isn't1256* being inconsistent: for example initially negotiating with1257* TLS 1.0 and renegotiating with TLS 1.2. We do this by using1258* client_version in client hello and not resetting it to1259* the negotiated version.1260*1261* For TLS 1.3 we always set the ClientHello version to 1.2 and rely on the1262* supported_versions extension for the real supported versions.1263*/1264if (!WPACKET_put_bytes_u16(pkt, s->client_version)1265|| !WPACKET_memcpy(pkt, s->s3.client_random, SSL3_RANDOM_SIZE)) {1266SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1267return CON_FUNC_ERROR;1268}12691270/* Session ID */1271session_id = s->session->session_id;1272if (s->new_session || s->session->ssl_version == TLS1_3_VERSION) {1273if (s->version == TLS1_3_VERSION1274&& (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0) {1275sess_id_len = sizeof(s->tmp_session_id);1276s->tmp_session_id_len = sess_id_len;1277session_id = s->tmp_session_id;1278if (s->hello_retry_request == SSL_HRR_NONE1279&& RAND_bytes_ex(sctx->libctx, s->tmp_session_id,1280sess_id_len, 0) <= 0) {1281SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1282return CON_FUNC_ERROR;1283}1284} else {1285sess_id_len = 0;1286}1287} else {1288assert(s->session->session_id_length <= sizeof(s->session->session_id));1289sess_id_len = s->session->session_id_length;1290if (s->version == TLS1_3_VERSION) {1291s->tmp_session_id_len = sess_id_len;1292memcpy(s->tmp_session_id, s->session->session_id, sess_id_len);1293}1294}1295if (!WPACKET_start_sub_packet_u8(pkt)1296|| (sess_id_len != 0 && !WPACKET_memcpy(pkt, session_id,1297sess_id_len))1298|| !WPACKET_close(pkt)) {1299SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1300return CON_FUNC_ERROR;1301}13021303/* cookie stuff for DTLS */1304if (SSL_CONNECTION_IS_DTLS(s)) {1305if (s->d1->cookie_len > sizeof(s->d1->cookie)1306|| !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,1307s->d1->cookie_len)) {1308SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1309return CON_FUNC_ERROR;1310}1311}13121313/* Ciphers supported */1314if (!WPACKET_start_sub_packet_u16(pkt)) {1315SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1316return CON_FUNC_ERROR;1317}13181319if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(SSL_CONNECTION_GET_SSL(s)),1320pkt)) {1321/* SSLfatal() already called */1322return CON_FUNC_ERROR;1323}1324if (!WPACKET_close(pkt)) {1325SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1326return CON_FUNC_ERROR;1327}13281329/* COMPRESSION */1330if (!WPACKET_start_sub_packet_u8(pkt)) {1331SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1332return CON_FUNC_ERROR;1333}1334#ifndef OPENSSL_NO_COMP1335if (ssl_allow_compression(s)1336&& sctx->comp_methods1337&& (SSL_CONNECTION_IS_DTLS(s)1338|| s->s3.tmp.max_ver < TLS1_3_VERSION)) {1339int compnum = sk_SSL_COMP_num(sctx->comp_methods);1340for (i = 0; i < compnum; i++) {1341comp = sk_SSL_COMP_value(sctx->comp_methods, i);1342if (!WPACKET_put_bytes_u8(pkt, comp->id)) {1343SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1344return CON_FUNC_ERROR;1345}1346}1347}1348#endif1349/* Add the NULL method */1350if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {1351SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1352return CON_FUNC_ERROR;1353}13541355/* TLS extensions */1356if (!tls_construct_extensions(s, pkt, SSL_EXT_CLIENT_HELLO, NULL, 0)) {1357/* SSLfatal() already called */1358return CON_FUNC_ERROR;1359}13601361return CON_FUNC_SUCCESS;1362}13631364MSG_PROCESS_RETURN dtls_process_hello_verify(SSL_CONNECTION *s, PACKET *pkt)1365{1366size_t cookie_len;1367PACKET cookiepkt;13681369if (!PACKET_forward(pkt, 2)1370|| !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {1371SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1372return MSG_PROCESS_ERROR;1373}13741375cookie_len = PACKET_remaining(&cookiepkt);1376if (cookie_len > sizeof(s->d1->cookie)) {1377SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);1378return MSG_PROCESS_ERROR;1379}13801381if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {1382SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1383return MSG_PROCESS_ERROR;1384}1385s->d1->cookie_len = cookie_len;13861387return MSG_PROCESS_FINISHED_READING;1388}13891390static int set_client_ciphersuite(SSL_CONNECTION *s,1391const unsigned char *cipherchars)1392{1393STACK_OF(SSL_CIPHER) *sk;1394const SSL_CIPHER *c;1395int i;1396SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);13971398c = ssl_get_cipher_by_char(s, cipherchars, 0);1399if (c == NULL) {1400/* unknown cipher */1401SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CIPHER_RETURNED);1402return 0;1403}1404/*1405* If it is a disabled cipher we either didn't send it in client hello,1406* or it's not allowed for the selected protocol. So we return an error.1407*/1408if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK, 1)) {1409SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1410return 0;1411}14121413sk = ssl_get_ciphers_by_id(s);1414i = sk_SSL_CIPHER_find(sk, c);1415if (i < 0) {1416/* we did not say we would use this cipher */1417SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1418return 0;1419}14201421if (SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.new_cipher != NULL1422&& s->s3.tmp.new_cipher->id != c->id) {1423/* ServerHello selected a different ciphersuite to that in the HRR */1424SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);1425return 0;1426}14271428/*1429* Depending on the session caching (internal/external), the cipher1430* and/or cipher_id values may not be set. Make sure that cipher_id is1431* set and use it for comparison.1432*/1433if (s->session->cipher != NULL)1434s->session->cipher_id = s->session->cipher->id;1435if (s->hit && (s->session->cipher_id != c->id)) {1436if (SSL_CONNECTION_IS_TLS13(s)) {1437const EVP_MD *md = ssl_md(sctx, c->algorithm2);14381439if (!ossl_assert(s->session->cipher != NULL)) {1440SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1441return 0;1442}1443/*1444* In TLSv1.3 it is valid for the server to select a different1445* ciphersuite as long as the hash is the same.1446*/1447if (md == NULL1448|| md != ssl_md(sctx, s->session->cipher->algorithm2)) {1449SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1450SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED);1451return 0;1452}1453} else {1454/*1455* Prior to TLSv1.3 resuming a session always meant using the same1456* ciphersuite.1457*/1458SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1459SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);1460return 0;1461}1462}1463s->s3.tmp.new_cipher = c;14641465return 1;1466}14671468MSG_PROCESS_RETURN tls_process_server_hello(SSL_CONNECTION *s, PACKET *pkt)1469{1470PACKET session_id, extpkt;1471size_t session_id_len;1472const unsigned char *cipherchars;1473int hrr = 0;1474unsigned int compression;1475unsigned int sversion;1476unsigned int context;1477RAW_EXTENSION *extensions = NULL;1478SSL *ssl = SSL_CONNECTION_GET_SSL(s);1479SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);1480#ifndef OPENSSL_NO_COMP1481SSL_COMP *comp;1482#endif14831484if (!PACKET_get_net_2(pkt, &sversion)) {1485SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1486goto err;1487}14881489/* load the server random */1490if (s->version == TLS1_3_VERSION1491&& sversion == TLS1_2_VERSION1492&& PACKET_remaining(pkt) >= SSL3_RANDOM_SIZE1493&& memcmp(hrrrandom, PACKET_data(pkt), SSL3_RANDOM_SIZE) == 0) {1494if (s->hello_retry_request != SSL_HRR_NONE) {1495SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);1496goto err;1497}1498s->hello_retry_request = SSL_HRR_PENDING;1499/* Tell the record layer that we know we're going to get TLSv1.3 */1500if (!ssl_set_record_protocol_version(s, s->version)) {1501SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1502goto err;1503}1504hrr = 1;1505if (!PACKET_forward(pkt, SSL3_RANDOM_SIZE)) {1506SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1507goto err;1508}1509} else {1510if (!PACKET_copy_bytes(pkt, s->s3.server_random, SSL3_RANDOM_SIZE)) {1511SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1512goto err;1513}1514}15151516/* Get the session-id. */1517if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {1518SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1519goto err;1520}1521session_id_len = PACKET_remaining(&session_id);1522if (session_id_len > sizeof(s->session->session_id)1523|| session_id_len > SSL3_SESSION_ID_SIZE) {1524SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_SSL3_SESSION_ID_TOO_LONG);1525goto err;1526}15271528if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {1529SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1530goto err;1531}15321533if (!PACKET_get_1(pkt, &compression)) {1534SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);1535goto err;1536}15371538/* TLS extensions */1539if (PACKET_remaining(pkt) == 0 && !hrr) {1540PACKET_null_init(&extpkt);1541} else if (!PACKET_as_length_prefixed_2(pkt, &extpkt)1542|| PACKET_remaining(pkt) != 0) {1543SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);1544goto err;1545}15461547if (!hrr) {1548if (!tls_collect_extensions(s, &extpkt,1549SSL_EXT_TLS1_2_SERVER_HELLO1550| SSL_EXT_TLS1_3_SERVER_HELLO,1551&extensions, NULL, 1)) {1552/* SSLfatal() already called */1553goto err;1554}15551556if (!ssl_choose_client_version(s, sversion, extensions)) {1557/* SSLfatal() already called */1558goto err;1559}1560}15611562if (SSL_CONNECTION_IS_TLS13(s) || hrr) {1563if (compression != 0) {1564SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1565SSL_R_INVALID_COMPRESSION_ALGORITHM);1566goto err;1567}15681569if (session_id_len != s->tmp_session_id_len1570|| memcmp(PACKET_data(&session_id), s->tmp_session_id,1571session_id_len) != 0) {1572SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_INVALID_SESSION_ID);1573goto err;1574}1575}15761577if (hrr) {1578if (!set_client_ciphersuite(s, cipherchars)) {1579/* SSLfatal() already called */1580goto err;1581}15821583return tls_process_as_hello_retry_request(s, &extpkt);1584}15851586/*1587* Now we have chosen the version we need to check again that the extensions1588* are appropriate for this version.1589*/1590context = SSL_CONNECTION_IS_TLS13(s) ? SSL_EXT_TLS1_3_SERVER_HELLO1591: SSL_EXT_TLS1_2_SERVER_HELLO;1592if (!tls_validate_all_contexts(s, context, extensions)) {1593SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);1594goto err;1595}15961597s->hit = 0;15981599if (SSL_CONNECTION_IS_TLS13(s)) {1600/*1601* In TLSv1.3 a ServerHello message signals a key change so the end of1602* the message must be on a record boundary.1603*/1604if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {1605SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,1606SSL_R_NOT_ON_RECORD_BOUNDARY);1607goto err;1608}16091610/* This will set s->hit if we are resuming */1611if (!tls_parse_extension(s, TLSEXT_IDX_psk,1612SSL_EXT_TLS1_3_SERVER_HELLO,1613extensions, NULL, 0)) {1614/* SSLfatal() already called */1615goto err;1616}1617} else {1618/*1619* Check if we can resume the session based on external pre-shared1620* secret. EAP-FAST (RFC 4851) supports two types of session resumption.1621* Resumption based on server-side state works with session IDs.1622* Resumption based on pre-shared Protected Access Credentials (PACs)1623* works by overriding the SessionTicket extension at the application1624* layer, and does not send a session ID. (We do not know whether1625* EAP-FAST servers would honour the session ID.) Therefore, the session1626* ID alone is not a reliable indicator of session resumption, so we1627* first check if we can resume, and later peek at the next handshake1628* message to see if the server wants to resume.1629*/1630if (s->version >= TLS1_VERSION1631&& s->ext.session_secret_cb != NULL && s->session->ext.tick) {1632const SSL_CIPHER *pref_cipher = NULL;1633/*1634* s->session->master_key_length is a size_t, but this is an int for1635* backwards compat reasons1636*/1637int master_key_length;16381639master_key_length = sizeof(s->session->master_key);1640if (s->ext.session_secret_cb(ussl, s->session->master_key,1641&master_key_length,1642NULL, &pref_cipher,1643s->ext.session_secret_cb_arg)1644&& master_key_length > 0) {1645s->session->master_key_length = master_key_length;1646s->session->cipher = pref_cipher ?1647pref_cipher : ssl_get_cipher_by_char(s, cipherchars, 0);1648} else {1649SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1650goto err;1651}1652}16531654if (session_id_len != 01655&& session_id_len == s->session->session_id_length1656&& memcmp(PACKET_data(&session_id), s->session->session_id,1657session_id_len) == 0)1658s->hit = 1;1659}16601661if (s->hit) {1662if (s->sid_ctx_length != s->session->sid_ctx_length1663|| memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {1664/* actually a client application bug */1665SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1666SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);1667goto err;1668}1669} else {1670/*1671* If we were trying for session-id reuse but the server1672* didn't resume, make a new SSL_SESSION.1673* In the case of EAP-FAST and PAC, we do not send a session ID,1674* so the PAC-based session secret is always preserved. It'll be1675* overwritten if the server refuses resumption.1676*/1677if (s->session->session_id_length > 0) {1678ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);1679if (!ssl_get_new_session(s, 0)) {1680/* SSLfatal() already called */1681goto err;1682}1683}16841685s->session->ssl_version = s->version;1686/*1687* In TLSv1.2 and below we save the session id we were sent so we can1688* resume it later. In TLSv1.3 the session id we were sent is just an1689* echo of what we originally sent in the ClientHello and should not be1690* used for resumption.1691*/1692if (!SSL_CONNECTION_IS_TLS13(s)) {1693s->session->session_id_length = session_id_len;1694/* session_id_len could be 0 */1695if (session_id_len > 0)1696memcpy(s->session->session_id, PACKET_data(&session_id),1697session_id_len);1698}1699}17001701/* Session version and negotiated protocol version should match */1702if (s->version != s->session->ssl_version) {1703SSLfatal(s, SSL_AD_PROTOCOL_VERSION,1704SSL_R_SSL_SESSION_VERSION_MISMATCH);1705goto err;1706}1707/*1708* Now that we know the version, update the check to see if it's an allowed1709* version.1710*/1711s->s3.tmp.min_ver = s->version;1712s->s3.tmp.max_ver = s->version;17131714if (!set_client_ciphersuite(s, cipherchars)) {1715/* SSLfatal() already called */1716goto err;1717}17181719#ifdef OPENSSL_NO_COMP1720if (compression != 0) {1721SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1722SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);1723goto err;1724}1725/*1726* If compression is disabled we'd better not try to resume a session1727* using compression.1728*/1729if (s->session->compress_meth != 0) {1730SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);1731goto err;1732}1733#else1734if (s->hit && compression != s->session->compress_meth) {1735SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1736SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);1737goto err;1738}1739if (compression == 0)1740comp = NULL;1741else if (!ssl_allow_compression(s)) {1742SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COMPRESSION_DISABLED);1743goto err;1744} else {1745comp = ssl3_comp_find(SSL_CONNECTION_GET_CTX(s)->comp_methods,1746compression);1747}17481749if (compression != 0 && comp == NULL) {1750SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,1751SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);1752goto err;1753} else {1754s->s3.tmp.new_compression = comp;1755}1756#endif17571758if (!tls_parse_all_extensions(s, context, extensions, NULL, 0, 1)) {1759/* SSLfatal() already called */1760goto err;1761}17621763#ifndef OPENSSL_NO_SCTP1764if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {1765unsigned char sctpauthkey[64];1766char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];1767size_t labellen;17681769/*1770* Add new shared key for SCTP-Auth, will be ignored if1771* no SCTP used.1772*/1773memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,1774sizeof(DTLS1_SCTP_AUTH_LABEL));17751776/* Don't include the terminating zero. */1777labellen = sizeof(labelbuffer) - 1;1778if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)1779labellen += 1;17801781if (SSL_export_keying_material(ssl, sctpauthkey,1782sizeof(sctpauthkey),1783labelbuffer,1784labellen, NULL, 0, 0) <= 0) {1785SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1786goto err;1787}17881789BIO_ctrl(SSL_get_wbio(ssl),1790BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,1791sizeof(sctpauthkey), sctpauthkey);1792}1793#endif17941795/*1796* In TLSv1.3 we have some post-processing to change cipher state, otherwise1797* we're done with this message1798*/1799if (SSL_CONNECTION_IS_TLS13(s)) {1800if (!ssl->method->ssl3_enc->setup_key_block(s)1801|| !tls13_store_handshake_traffic_hash(s)) {1802/* SSLfatal() already called */1803goto err;1804}1805/*1806* If we're not doing early-data and we're not going to send a dummy CCS1807* (i.e. no middlebox compat mode) then we can change the write keys1808* immediately. Otherwise we have to defer this until after all possible1809* early data is written. We could just always defer until the last1810* moment except QUIC needs it done at the same time as the read keys1811* are changed. Since QUIC doesn't do TLS early data or need middlebox1812* compat this doesn't cause a problem.1813*/1814if (SSL_IS_QUIC_HANDSHAKE(s)1815|| (s->early_data_state == SSL_EARLY_DATA_NONE1816&& (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0)) {1817if (!ssl->method->ssl3_enc->change_cipher_state(s,1818SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {1819/* SSLfatal() already called */1820goto err;1821}1822}1823if (!ssl->method->ssl3_enc->change_cipher_state(s,1824SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ)) {1825/* SSLfatal() already called */1826goto err;1827}1828}18291830OPENSSL_free(extensions);1831return MSG_PROCESS_CONTINUE_READING;1832err:1833OPENSSL_free(extensions);1834return MSG_PROCESS_ERROR;1835}18361837static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,1838PACKET *extpkt)1839{1840RAW_EXTENSION *extensions = NULL;18411842/*1843* If we were sending early_data then any alerts should not be sent using1844* the old wrlmethod.1845*/1846if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING1847&& !ssl_set_new_record_layer(s,1848TLS_ANY_VERSION,1849OSSL_RECORD_DIRECTION_WRITE,1850OSSL_RECORD_PROTECTION_LEVEL_NONE,1851NULL, 0, NULL, 0, NULL, 0, NULL, 0,1852NULL, 0, NID_undef, NULL, NULL, NULL)) {1853/* SSLfatal already called */1854goto err;1855}1856/* We are definitely going to be using TLSv1.3 */1857s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, TLS1_3_VERSION);18581859if (!tls_collect_extensions(s, extpkt, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,1860&extensions, NULL, 1)1861|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,1862extensions, NULL, 0, 1)) {1863/* SSLfatal() already called */1864goto err;1865}18661867OPENSSL_free(extensions);1868extensions = NULL;18691870if (s->ext.tls13_cookie_len == 0 && s->s3.tmp.pkey != NULL) {1871/*1872* We didn't receive a cookie or a new key_share so the next1873* ClientHello will not change1874*/1875SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CHANGE_FOLLOWING_HRR);1876goto err;1877}18781879/*1880* Re-initialise the Transcript Hash. We're going to prepopulate it with1881* a synthetic message_hash in place of ClientHello1.1882*/1883if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {1884/* SSLfatal() already called */1885goto err;1886}18871888/*1889* Add this message to the Transcript Hash. Normally this is done1890* automatically prior to the message processing stage. However due to the1891* need to create the synthetic message hash, we defer that step until now1892* for HRR messages.1893*/1894if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,1895s->init_num + SSL3_HM_HEADER_LENGTH)) {1896/* SSLfatal() already called */1897goto err;1898}18991900return MSG_PROCESS_FINISHED_READING;1901err:1902OPENSSL_free(extensions);1903return MSG_PROCESS_ERROR;1904}19051906MSG_PROCESS_RETURN tls_process_server_rpk(SSL_CONNECTION *sc, PACKET *pkt)1907{1908EVP_PKEY *peer_rpk = NULL;19091910if (!tls_process_rpk(sc, pkt, &peer_rpk)) {1911/* SSLfatal() already called */1912return MSG_PROCESS_ERROR;1913}19141915if (peer_rpk == NULL) {1916SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_CERTIFICATE);1917return MSG_PROCESS_ERROR;1918}19191920EVP_PKEY_free(sc->session->peer_rpk);1921sc->session->peer_rpk = peer_rpk;19221923return MSG_PROCESS_CONTINUE_PROCESSING;1924}19251926static WORK_STATE tls_post_process_server_rpk(SSL_CONNECTION *sc,1927WORK_STATE wst)1928{1929size_t certidx;1930const SSL_CERT_LOOKUP *clu;1931int v_ok;19321933if (sc->session->peer_rpk == NULL) {1934SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER,1935SSL_R_INVALID_RAW_PUBLIC_KEY);1936return WORK_ERROR;1937}19381939if (sc->rwstate == SSL_RETRY_VERIFY)1940sc->rwstate = SSL_NOTHING;19411942ERR_set_mark();1943v_ok = ssl_verify_rpk(sc, sc->session->peer_rpk);1944if (v_ok <= 0 && sc->verify_mode != SSL_VERIFY_NONE) {1945ERR_clear_last_mark();1946SSLfatal(sc, ssl_x509err2alert(sc->verify_result),1947SSL_R_CERTIFICATE_VERIFY_FAILED);1948return WORK_ERROR;1949}1950ERR_pop_to_mark(); /* but we keep s->verify_result */1951if (v_ok > 0 && sc->rwstate == SSL_RETRY_VERIFY) {1952return WORK_MORE_A;1953}19541955if ((clu = ssl_cert_lookup_by_pkey(sc->session->peer_rpk, &certidx,1956SSL_CONNECTION_GET_CTX(sc))) == 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) == NULL) {2039SSLfatal(s, SSL_AD_BAD_CERTIFICATE, ERR_R_ASN1_LIB);2040goto err;2041}20422043if (certbytes != (certstart + cert_len)) {2044SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);2045goto err;2046}20472048if (SSL_CONNECTION_IS_TLS13(s)) {2049RAW_EXTENSION *rawexts = NULL;2050PACKET extensions;20512052if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {2053SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);2054goto err;2055}2056if (!tls_collect_extensions(s, &extensions,2057SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,2058NULL, chainidx == 0)2059|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,2060rawexts, x, chainidx,2061PACKET_remaining(pkt) == 0)) {2062OPENSSL_free(rawexts);2063/* SSLfatal already called */2064goto err;2065}2066OPENSSL_free(rawexts);2067}20682069if (!sk_X509_push(s->session->peer_chain, x)) {2070SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2071goto err;2072}2073x = NULL;2074}2075return MSG_PROCESS_CONTINUE_PROCESSING;20762077err:2078X509_free(x);2079OSSL_STACK_OF_X509_free(s->session->peer_chain);2080s->session->peer_chain = NULL;2081return MSG_PROCESS_ERROR;2082}20832084/*2085* Verify the s->session->peer_chain and check server cert type.2086* On success set s->session->peer and s->session->verify_result.2087* Else the peer certificate verification callback may request retry.2088*/2089WORK_STATE tls_post_process_server_certificate(SSL_CONNECTION *s,2090WORK_STATE wst)2091{2092X509 *x;2093EVP_PKEY *pkey = NULL;2094const SSL_CERT_LOOKUP *clu;2095size_t certidx;2096int i;20972098if (s->ext.server_cert_type == TLSEXT_cert_type_rpk)2099return tls_post_process_server_rpk(s, wst);21002101if (s->rwstate == SSL_RETRY_VERIFY)2102s->rwstate = SSL_NOTHING;21032104/*2105* The documented interface is that SSL_VERIFY_PEER should be set in order2106* for client side verification of the server certificate to take place.2107* However, historically the code has only checked that *any* flag is set2108* to cause server verification to take place. Use of the other flags makes2109* no sense in client mode. An attempt to clean up the semantics was2110* reverted because at least one application *only* set2111* SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused2112* server verification to take place, after the clean up it silently did2113* nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags2114* sent to them because they are void functions. Therefore, we now use the2115* (less clean) historic behaviour of performing validation if any flag is2116* set. The *documented* interface remains the same.2117*/2118ERR_set_mark();2119i = ssl_verify_cert_chain(s, s->session->peer_chain);2120if (i <= 0 && s->verify_mode != SSL_VERIFY_NONE) {2121ERR_clear_last_mark();2122SSLfatal(s, ssl_x509err2alert(s->verify_result),2123SSL_R_CERTIFICATE_VERIFY_FAILED);2124return WORK_ERROR;2125}2126ERR_pop_to_mark(); /* but we keep s->verify_result */2127if (i > 0 && s->rwstate == SSL_RETRY_VERIFY)2128return WORK_MORE_A;21292130/*2131* Inconsistency alert: cert_chain does include the peer's certificate,2132* which we don't include in statem_srvr.c2133*/2134x = sk_X509_value(s->session->peer_chain, 0);21352136pkey = X509_get0_pubkey(x);21372138if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {2139SSLfatal(s, SSL_AD_INTERNAL_ERROR,2140SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);2141return WORK_ERROR;2142}21432144if ((clu = ssl_cert_lookup_by_pkey(pkey, &certidx,2145SSL_CONNECTION_GET_CTX(s))) == NULL) {2146SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);2147return WORK_ERROR;2148}2149/*2150* Check certificate type is consistent with ciphersuite. For TLS 1.32151* skip check since TLS 1.3 ciphersuites can be used with any certificate2152* type.2153*/2154if (!SSL_CONNECTION_IS_TLS13(s)) {2155if ((clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0) {2156SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CERTIFICATE_TYPE);2157return WORK_ERROR;2158}2159}21602161if (!X509_up_ref(x)) {2162SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2163return WORK_ERROR;2164}21652166X509_free(s->session->peer);2167s->session->peer = x;2168s->session->verify_result = s->verify_result;2169/* Ensure there is no RPK */2170EVP_PKEY_free(s->session->peer_rpk);2171s->session->peer_rpk = NULL;21722173/* Save the current hash state for when we receive the CertificateVerify */2174if (SSL_CONNECTION_IS_TLS13(s)2175&& !ssl_handshake_hash(s, s->cert_verify_hash,2176sizeof(s->cert_verify_hash),2177&s->cert_verify_hash_len)) {2178/* SSLfatal() already called */;2179return WORK_ERROR;2180}2181return WORK_FINISHED_CONTINUE;2182}21832184#ifndef OPENSSL_NO_COMP_ALG2185MSG_PROCESS_RETURN tls_process_server_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)2186{2187MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;2188PACKET tmppkt;2189BUF_MEM *buf = BUF_MEM_new();21902191if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)2192ret = tls_process_server_certificate(sc, &tmppkt);21932194BUF_MEM_free(buf);2195return ret;2196}2197#endif21982199static int tls_process_ske_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)2200{2201#ifndef OPENSSL_NO_PSK2202PACKET psk_identity_hint;22032204/* PSK ciphersuites are preceded by an identity hint */22052206if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {2207SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2208return 0;2209}22102211/*2212* Store PSK identity hint for later use, hint is used in2213* tls_construct_client_key_exchange. Assume that the maximum length of2214* a PSK identity hint can be as long as the maximum length of a PSK2215* identity.2216*/2217if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {2218SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DATA_LENGTH_TOO_LONG);2219return 0;2220}22212222if (PACKET_remaining(&psk_identity_hint) == 0) {2223OPENSSL_free(s->session->psk_identity_hint);2224s->session->psk_identity_hint = NULL;2225} else if (!PACKET_strndup(&psk_identity_hint,2226&s->session->psk_identity_hint)) {2227SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2228return 0;2229}22302231return 1;2232#else2233SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2234return 0;2235#endif2236}22372238static int tls_process_ske_srp(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2239{2240#ifndef OPENSSL_NO_SRP2241PACKET prime, generator, salt, server_pub;22422243if (!PACKET_get_length_prefixed_2(pkt, &prime)2244|| !PACKET_get_length_prefixed_2(pkt, &generator)2245|| !PACKET_get_length_prefixed_1(pkt, &salt)2246|| !PACKET_get_length_prefixed_2(pkt, &server_pub)) {2247SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2248return 0;2249}22502251if ((s->srp_ctx.N =2252BN_bin2bn(PACKET_data(&prime),2253(int)PACKET_remaining(&prime), NULL)) == NULL2254|| (s->srp_ctx.g =2255BN_bin2bn(PACKET_data(&generator),2256(int)PACKET_remaining(&generator), NULL)) == NULL2257|| (s->srp_ctx.s =2258BN_bin2bn(PACKET_data(&salt),2259(int)PACKET_remaining(&salt), NULL)) == NULL2260|| (s->srp_ctx.B =2261BN_bin2bn(PACKET_data(&server_pub),2262(int)PACKET_remaining(&server_pub), NULL)) == NULL) {2263SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);2264return 0;2265}22662267if (!srp_verify_server_param(s)) {2268/* SSLfatal() already called */2269return 0;2270}22712272/* We must check if there is a certificate */2273if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))2274*pkey = tls_get_peer_pkey(s);22752276return 1;2277#else2278SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2279return 0;2280#endif2281}22822283static int tls_process_ske_dhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2284{2285PACKET prime, generator, pub_key;2286EVP_PKEY *peer_tmp = NULL;2287BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;2288EVP_PKEY_CTX *pctx = NULL;2289OSSL_PARAM *params = NULL;2290OSSL_PARAM_BLD *tmpl = NULL;2291SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);2292int ret = 0;22932294if (!PACKET_get_length_prefixed_2(pkt, &prime)2295|| !PACKET_get_length_prefixed_2(pkt, &generator)2296|| !PACKET_get_length_prefixed_2(pkt, &pub_key)) {2297SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2298return 0;2299}23002301p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);2302g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),2303NULL);2304bnpub_key = BN_bin2bn(PACKET_data(&pub_key),2305(int)PACKET_remaining(&pub_key), NULL);2306if (p == NULL || g == NULL || bnpub_key == NULL) {2307SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);2308goto err;2309}23102311tmpl = OSSL_PARAM_BLD_new();2312if (tmpl == NULL2313|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)2314|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)2315|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY,2316bnpub_key)2317|| (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {2318SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2319goto err;2320}23212322pctx = EVP_PKEY_CTX_new_from_name(sctx->libctx, "DH", sctx->propq);2323if (pctx == NULL) {2324SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2325goto err;2326}2327if (EVP_PKEY_fromdata_init(pctx) <= 02328|| EVP_PKEY_fromdata(pctx, &peer_tmp, EVP_PKEY_KEYPAIR, params) <= 0) {2329SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_DH_VALUE);2330goto err;2331}23322333EVP_PKEY_CTX_free(pctx);2334pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, peer_tmp, sctx->propq);2335if (pctx == NULL2336/*2337* EVP_PKEY_param_check() will verify that the DH params are using2338* a safe prime. In this context, because we're using ephemeral DH,2339* we're ok with it not being a safe prime.2340* EVP_PKEY_param_check_quick() skips the safe prime check.2341*/2342|| EVP_PKEY_param_check_quick(pctx) != 12343|| EVP_PKEY_public_check(pctx) != 1) {2344SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_DH_VALUE);2345goto err;2346}23472348if (!ssl_security(s, SSL_SECOP_TMP_DH,2349EVP_PKEY_get_security_bits(peer_tmp),23500, peer_tmp)) {2351SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);2352goto err;2353}23542355s->s3.peer_tmp = peer_tmp;2356peer_tmp = NULL;23572358/*2359* FIXME: This makes assumptions about which ciphersuites come with2360* public keys. We should have a less ad-hoc way of doing this2361*/2362if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))2363*pkey = tls_get_peer_pkey(s);2364/* else anonymous DH, so no certificate or pkey. */23652366ret = 1;23672368err:2369OSSL_PARAM_BLD_free(tmpl);2370OSSL_PARAM_free(params);2371EVP_PKEY_free(peer_tmp);2372EVP_PKEY_CTX_free(pctx);2373BN_free(p);2374BN_free(g);2375BN_free(bnpub_key);23762377return ret;2378}23792380static int tls_process_ske_ecdhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)2381{2382PACKET encoded_pt;2383unsigned int curve_type, curve_id;23842385/*2386* Extract elliptic curve parameters and the server's ephemeral ECDH2387* public key. We only support named (not generic) curves and2388* ECParameters in this case is just three bytes.2389*/2390if (!PACKET_get_1(pkt, &curve_type) || !PACKET_get_net_2(pkt, &curve_id)) {2391SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);2392return 0;2393}2394/*2395* Check curve is named curve type and one of our preferences, if not2396* server has sent an invalid curve.2397*/2398if (curve_type != NAMED_CURVE_TYPE2399|| !tls1_check_group_id(s, curve_id, 1)) {2400SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);2401return 0;2402}24032404if ((s->s3.peer_tmp = ssl_generate_param_group(s, curve_id)) == NULL) {2405SSLfatal(s, SSL_AD_INTERNAL_ERROR,2406SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);2407return 0;2408}24092410if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {2411SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2412return 0;2413}24142415if (EVP_PKEY_set1_encoded_public_key(s->s3.peer_tmp,2416PACKET_data(&encoded_pt),2417PACKET_remaining(&encoded_pt)) <= 0) {2418SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);2419return 0;2420}24212422/*2423* The ECC/TLS specification does not mention the use of DSA to sign2424* ECParameters in the server key exchange message. We do support RSA2425* and ECDSA.2426*/2427if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA)2428*pkey = tls_get_peer_pkey(s);2429else if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aRSA)2430*pkey = tls_get_peer_pkey(s);2431/* else anonymous ECDH, so no certificate or pkey. */24322433/* Cache the agreed upon group in the SSL_SESSION */2434s->session->kex_group = curve_id;2435return 1;2436}24372438MSG_PROCESS_RETURN tls_process_key_exchange(SSL_CONNECTION *s, PACKET *pkt)2439{2440long alg_k;2441EVP_PKEY *pkey = NULL;2442EVP_MD_CTX *md_ctx = NULL;2443EVP_PKEY_CTX *pctx = NULL;2444PACKET save_param_start, signature;2445SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);24462447alg_k = s->s3.tmp.new_cipher->algorithm_mkey;24482449save_param_start = *pkt;24502451EVP_PKEY_free(s->s3.peer_tmp);2452s->s3.peer_tmp = NULL;24532454if (alg_k & SSL_PSK) {2455if (!tls_process_ske_psk_preamble(s, pkt)) {2456/* SSLfatal() already called */2457goto err;2458}2459}24602461/* Nothing else to do for plain PSK or RSAPSK */2462if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {2463} else if (alg_k & SSL_kSRP) {2464if (!tls_process_ske_srp(s, pkt, &pkey)) {2465/* SSLfatal() already called */2466goto err;2467}2468} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {2469if (!tls_process_ske_dhe(s, pkt, &pkey)) {2470/* SSLfatal() already called */2471goto err;2472}2473} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {2474if (!tls_process_ske_ecdhe(s, pkt, &pkey)) {2475/* SSLfatal() already called */2476goto err;2477}2478} else if (alg_k) {2479SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);2480goto err;2481}24822483/* if it was signed, check the signature */2484if (pkey != NULL) {2485PACKET params;2486const EVP_MD *md = NULL;2487unsigned char *tbs;2488size_t tbslen;2489int rv;24902491/*2492* |pkt| now points to the beginning of the signature, so the difference2493* equals the length of the parameters.2494*/2495if (!PACKET_get_sub_packet(&save_param_start, ¶ms,2496PACKET_remaining(&save_param_start) -2497PACKET_remaining(pkt))) {2498SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);2499goto err;2500}25012502if (SSL_USE_SIGALGS(s)) {2503unsigned int sigalg;25042505if (!PACKET_get_net_2(pkt, &sigalg)) {2506SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);2507goto err;2508}2509if (tls12_check_peer_sigalg(s, sigalg, pkey) <=0) {2510/* SSLfatal() already called */2511goto err;2512}2513} else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {2514SSLfatal(s, SSL_AD_INTERNAL_ERROR,2515SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);2516goto err;2517}25182519if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {2520SSLfatal(s, SSL_AD_INTERNAL_ERROR,2521SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);2522goto err;2523}2524if (SSL_USE_SIGALGS(s))2525OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",2526md == NULL ? "n/a" : EVP_MD_get0_name(md));25272528if (!PACKET_get_length_prefixed_2(pkt, &signature)2529|| PACKET_remaining(pkt) != 0) {2530SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2531goto err;2532}25332534md_ctx = EVP_MD_CTX_new();2535if (md_ctx == NULL) {2536SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2537goto err;2538}25392540if (EVP_DigestVerifyInit_ex(md_ctx, &pctx,2541md == NULL ? NULL : EVP_MD_get0_name(md),2542sctx->libctx, sctx->propq, pkey,2543NULL) <= 0) {2544SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2545goto err;2546}2547if (SSL_USE_PSS(s)) {2548if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 02549|| EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,2550RSA_PSS_SALTLEN_DIGEST) <= 0) {2551SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2552goto err;2553}2554}2555tbslen = construct_key_exchange_tbs(s, &tbs, PACKET_data(¶ms),2556PACKET_remaining(¶ms));2557if (tbslen == 0) {2558/* SSLfatal() already called */2559goto err;2560}25612562rv = EVP_DigestVerify(md_ctx, PACKET_data(&signature),2563PACKET_remaining(&signature), tbs, tbslen);2564OPENSSL_free(tbs);2565if (rv <= 0) {2566SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);2567goto err;2568}2569EVP_MD_CTX_free(md_ctx);2570md_ctx = NULL;2571} else {2572/* aNULL, aSRP or PSK do not need public keys */2573if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))2574&& !(alg_k & SSL_PSK)) {2575/* Might be wrong key type, check it */2576if (ssl3_check_cert_and_algorithm(s)) {2577SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DATA);2578}2579/* else this shouldn't happen, SSLfatal() already called */2580goto err;2581}2582/* still data left over */2583if (PACKET_remaining(pkt) != 0) {2584SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_EXTRA_DATA_IN_MESSAGE);2585goto err;2586}2587}25882589return MSG_PROCESS_CONTINUE_READING;2590err:2591EVP_MD_CTX_free(md_ctx);2592return MSG_PROCESS_ERROR;2593}25942595MSG_PROCESS_RETURN tls_process_certificate_request(SSL_CONNECTION *s,2596PACKET *pkt)2597{2598/* Clear certificate validity flags */2599if (s->s3.tmp.valid_flags != NULL)2600memset(s->s3.tmp.valid_flags, 0, s->ssl_pkey_num * sizeof(uint32_t));2601else2602s->s3.tmp.valid_flags = OPENSSL_zalloc(s->ssl_pkey_num * sizeof(uint32_t));26032604/* Give up for good if allocation didn't work */2605if (s->s3.tmp.valid_flags == NULL)2606return 0;26072608if (SSL_CONNECTION_IS_TLS13(s)) {2609PACKET reqctx, extensions;2610RAW_EXTENSION *rawexts = NULL;26112612if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {2613/*2614* We already sent close_notify. This can only happen in TLSv1.32615* post-handshake messages. We can't reasonably respond to this, so2616* we just ignore it2617*/2618return MSG_PROCESS_FINISHED_READING;2619}26202621/* Free and zero certificate types: it is not present in TLS 1.3 */2622OPENSSL_free(s->s3.tmp.ctype);2623s->s3.tmp.ctype = NULL;2624s->s3.tmp.ctype_len = 0;2625OPENSSL_free(s->pha_context);2626s->pha_context = NULL;2627s->pha_context_len = 0;26282629if (!PACKET_get_length_prefixed_1(pkt, &reqctx) ||2630!PACKET_memdup(&reqctx, &s->pha_context, &s->pha_context_len)) {2631SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2632return MSG_PROCESS_ERROR;2633}26342635if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {2636SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);2637return MSG_PROCESS_ERROR;2638}2639if (!tls_collect_extensions(s, &extensions,2640SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,2641&rawexts, NULL, 1)2642|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,2643rawexts, NULL, 0, 1)) {2644/* SSLfatal() already called */2645OPENSSL_free(rawexts);2646return MSG_PROCESS_ERROR;2647}2648OPENSSL_free(rawexts);2649if (!tls1_process_sigalgs(s)) {2650SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);2651return MSG_PROCESS_ERROR;2652}2653} else {2654PACKET ctypes;26552656/* get the certificate types */2657if (!PACKET_get_length_prefixed_1(pkt, &ctypes)) {2658SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2659return MSG_PROCESS_ERROR;2660}26612662if (!PACKET_memdup(&ctypes, &s->s3.tmp.ctype, &s->s3.tmp.ctype_len)) {2663SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2664return MSG_PROCESS_ERROR;2665}26662667if (SSL_USE_SIGALGS(s)) {2668PACKET sigalgs;26692670if (!PACKET_get_length_prefixed_2(pkt, &sigalgs)) {2671SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2672return MSG_PROCESS_ERROR;2673}26742675/*2676* Despite this being for certificates, preserve compatibility2677* with pre-TLS 1.3 and use the regular sigalgs field.2678*/2679if (!tls1_save_sigalgs(s, &sigalgs, 0)) {2680SSLfatal(s, SSL_AD_INTERNAL_ERROR,2681SSL_R_SIGNATURE_ALGORITHMS_ERROR);2682return MSG_PROCESS_ERROR;2683}2684if (!tls1_process_sigalgs(s)) {2685SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);2686return MSG_PROCESS_ERROR;2687}2688}26892690/* get the CA RDNs */2691if (!parse_ca_names(s, pkt)) {2692/* SSLfatal() already called */2693return MSG_PROCESS_ERROR;2694}2695}26962697if (PACKET_remaining(pkt) != 0) {2698SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2699return MSG_PROCESS_ERROR;2700}27012702/* we should setup a certificate to return.... */2703s->s3.tmp.cert_req = 1;27042705/*2706* In TLSv1.3 we don't prepare the client certificate yet. We wait until2707* after the CertificateVerify message has been received. This is because2708* in TLSv1.3 the CertificateRequest arrives before the Certificate message2709* but in TLSv1.2 it is the other way around. We want to make sure that2710* SSL_get1_peer_certificate() returns something sensible in2711* client_cert_cb.2712*/2713if (SSL_CONNECTION_IS_TLS13(s)2714&& s->post_handshake_auth != SSL_PHA_REQUESTED)2715return MSG_PROCESS_CONTINUE_READING;27162717return MSG_PROCESS_CONTINUE_PROCESSING;2718}27192720MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL_CONNECTION *s,2721PACKET *pkt)2722{2723unsigned int ticklen;2724unsigned long ticket_lifetime_hint, age_add = 0;2725unsigned int sess_len;2726RAW_EXTENSION *exts = NULL;2727PACKET nonce;2728EVP_MD *sha256 = NULL;2729SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);27302731PACKET_null_init(&nonce);27322733if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)2734|| (SSL_CONNECTION_IS_TLS13(s)2735&& (!PACKET_get_net_4(pkt, &age_add)2736|| !PACKET_get_length_prefixed_1(pkt, &nonce)))2737|| !PACKET_get_net_2(pkt, &ticklen)2738|| (SSL_CONNECTION_IS_TLS13(s) ? (ticklen == 02739|| PACKET_remaining(pkt) < ticklen)2740: PACKET_remaining(pkt) != ticklen)) {2741SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2742goto err;2743}27442745/*2746* Server is allowed to change its mind (in <=TLSv1.2) and send an empty2747* ticket. We already checked this TLSv1.3 case above, so it should never2748* be 0 here in that instance2749*/2750if (ticklen == 0)2751return MSG_PROCESS_CONTINUE_READING;27522753/*2754* Sessions must be immutable once they go into the session cache. Otherwise2755* we can get multi-thread problems. Therefore we don't "update" sessions,2756* we replace them with a duplicate. In TLSv1.3 we need to do this every2757* time a NewSessionTicket arrives because those messages arrive2758* post-handshake and the session may have already gone into the session2759* cache.2760*/2761if (SSL_CONNECTION_IS_TLS13(s) || s->session->session_id_length > 0) {2762SSL_SESSION *new_sess;27632764/*2765* We reused an existing session, so we need to replace it with a new2766* one2767*/2768if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {2769SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);2770goto err;2771}27722773if ((s->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) != 02774&& !SSL_CONNECTION_IS_TLS13(s)) {2775/*2776* In TLSv1.2 and below the arrival of a new tickets signals that2777* any old ticket we were using is now out of date, so we remove the2778* old session from the cache. We carry on if this fails2779*/2780SSL_CTX_remove_session(s->session_ctx, s->session);2781}27822783SSL_SESSION_free(s->session);2784s->session = new_sess;2785}27862787s->session->time = ossl_time_now();2788ssl_session_calculate_timeout(s->session);27892790OPENSSL_free(s->session->ext.tick);2791s->session->ext.tick = NULL;2792s->session->ext.ticklen = 0;27932794s->session->ext.tick = OPENSSL_malloc(ticklen);2795if (s->session->ext.tick == NULL) {2796SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2797goto err;2798}2799if (!PACKET_copy_bytes(pkt, s->session->ext.tick, ticklen)) {2800SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2801goto err;2802}28032804s->session->ext.tick_lifetime_hint = ticket_lifetime_hint;2805s->session->ext.tick_age_add = age_add;2806s->session->ext.ticklen = ticklen;28072808if (SSL_CONNECTION_IS_TLS13(s)) {2809PACKET extpkt;28102811if (!PACKET_as_length_prefixed_2(pkt, &extpkt)2812|| PACKET_remaining(pkt) != 0) {2813SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2814goto err;2815}28162817if (!tls_collect_extensions(s, &extpkt,2818SSL_EXT_TLS1_3_NEW_SESSION_TICKET, &exts,2819NULL, 1)2820|| !tls_parse_all_extensions(s,2821SSL_EXT_TLS1_3_NEW_SESSION_TICKET,2822exts, NULL, 0, 1)) {2823/* SSLfatal() already called */2824goto err;2825}2826}28272828/*2829* There are two ways to detect a resumed ticket session. One is to set2830* an appropriate session ID and then the server must return a match in2831* ServerHello. This allows the normal client session ID matching to work2832* and we know much earlier that the ticket has been accepted. The2833* other way is to set zero length session ID when the ticket is2834* presented and rely on the handshake to determine session resumption.2835* We choose the former approach because this fits in with assumptions2836* elsewhere in OpenSSL. The session ID is set to the SHA256 hash of the2837* ticket.2838*/2839sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq);2840if (sha256 == NULL) {2841/* Error is already recorded */2842SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);2843goto err;2844}2845/*2846* We use sess_len here because EVP_Digest expects an int2847* but s->session->session_id_length is a size_t2848*/2849if (!EVP_Digest(s->session->ext.tick, ticklen,2850s->session->session_id, &sess_len,2851sha256, NULL)) {2852SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);2853goto err;2854}2855EVP_MD_free(sha256);2856sha256 = NULL;2857s->session->session_id_length = sess_len;2858s->session->not_resumable = 0;28592860/* This is a standalone message in TLSv1.3, so there is no more to read */2861if (SSL_CONNECTION_IS_TLS13(s)) {2862const EVP_MD *md = ssl_handshake_md(s);2863int hashleni = EVP_MD_get_size(md);2864size_t hashlen;2865static const unsigned char nonce_label[] = "resumption";28662867/* Ensure cast to size_t is safe */2868if (!ossl_assert(hashleni > 0)) {2869SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);2870goto err;2871}2872hashlen = (size_t)hashleni;28732874if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,2875nonce_label,2876sizeof(nonce_label) - 1,2877PACKET_data(&nonce),2878PACKET_remaining(&nonce),2879s->session->master_key,2880hashlen, 1)) {2881/* SSLfatal() already called */2882goto err;2883}2884s->session->master_key_length = hashlen;28852886OPENSSL_free(exts);2887ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);2888return MSG_PROCESS_FINISHED_READING;2889}28902891return MSG_PROCESS_CONTINUE_READING;2892err:2893EVP_MD_free(sha256);2894OPENSSL_free(exts);2895return MSG_PROCESS_ERROR;2896}28972898/*2899* In TLSv1.3 this is called from the extensions code, otherwise it is used to2900* parse a separate message. Returns 1 on success or 0 on failure2901*/2902int tls_process_cert_status_body(SSL_CONNECTION *s, PACKET *pkt)2903{2904size_t resplen;2905unsigned int type;29062907if (!PACKET_get_1(pkt, &type)2908|| type != TLSEXT_STATUSTYPE_ocsp) {2909SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_UNSUPPORTED_STATUS_TYPE);2910return 0;2911}2912if (!PACKET_get_net_3_len(pkt, &resplen)2913|| PACKET_remaining(pkt) != resplen) {2914SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2915return 0;2916}2917s->ext.ocsp.resp = OPENSSL_malloc(resplen);2918if (s->ext.ocsp.resp == NULL) {2919s->ext.ocsp.resp_len = 0;2920SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);2921return 0;2922}2923s->ext.ocsp.resp_len = resplen;2924if (!PACKET_copy_bytes(pkt, s->ext.ocsp.resp, resplen)) {2925SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);2926return 0;2927}29282929return 1;2930}293129322933MSG_PROCESS_RETURN tls_process_cert_status(SSL_CONNECTION *s, PACKET *pkt)2934{2935if (!tls_process_cert_status_body(s, pkt)) {2936/* SSLfatal() already called */2937return MSG_PROCESS_ERROR;2938}29392940return MSG_PROCESS_CONTINUE_READING;2941}29422943/*2944* Perform miscellaneous checks and processing after we have received the2945* server's initial flight. In TLS1.3 this is after the Server Finished message.2946* In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 02947* on failure.2948*/2949int tls_process_initial_server_flight(SSL_CONNECTION *s)2950{2951SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);29522953/*2954* at this point we check that we have the required stuff from2955* the server2956*/2957if (!ssl3_check_cert_and_algorithm(s)) {2958/* SSLfatal() already called */2959return 0;2960}29612962/*2963* Call the ocsp status callback if needed. The |ext.ocsp.resp| and2964* |ext.ocsp.resp_len| values will be set if we actually received a status2965* message, or NULL and -1 otherwise2966*/2967if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing2968&& sctx->ext.status_cb != NULL) {2969int ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),2970sctx->ext.status_arg);29712972if (ret == 0) {2973SSLfatal(s, SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE,2974SSL_R_INVALID_STATUS_RESPONSE);2975return 0;2976}2977if (ret < 0) {2978SSLfatal(s, SSL_AD_INTERNAL_ERROR,2979SSL_R_OCSP_CALLBACK_FAILURE);2980return 0;2981}2982}2983#ifndef OPENSSL_NO_CT2984if (s->ct_validation_callback != NULL) {2985/* Note we validate the SCTs whether or not we abort on error */2986if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {2987/* SSLfatal() already called */2988return 0;2989}2990}2991#endif29922993return 1;2994}29952996MSG_PROCESS_RETURN tls_process_server_done(SSL_CONNECTION *s, PACKET *pkt)2997{2998if (PACKET_remaining(pkt) > 0) {2999/* should contain no data */3000SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);3001return MSG_PROCESS_ERROR;3002}3003#ifndef OPENSSL_NO_SRP3004if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {3005if (ssl_srp_calc_a_param_intern(s) <= 0) {3006SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SRP_A_CALC);3007return MSG_PROCESS_ERROR;3008}3009}3010#endif30113012if (!tls_process_initial_server_flight(s)) {3013/* SSLfatal() already called */3014return MSG_PROCESS_ERROR;3015}30163017return MSG_PROCESS_FINISHED_READING;3018}30193020static int tls_construct_cke_psk_preamble(SSL_CONNECTION *s, WPACKET *pkt)3021{3022#ifndef OPENSSL_NO_PSK3023int ret = 0;3024/*3025* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a3026* \0-terminated identity. The last byte is for us for simulating3027* strnlen.3028*/3029char identity[PSK_MAX_IDENTITY_LEN + 1];3030size_t identitylen = 0;3031unsigned char psk[PSK_MAX_PSK_LEN];3032unsigned char *tmppsk = NULL;3033char *tmpidentity = NULL;3034size_t psklen = 0;30353036if (s->psk_client_callback == NULL) {3037SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_CLIENT_CB);3038goto err;3039}30403041memset(identity, 0, sizeof(identity));30423043psklen = s->psk_client_callback(SSL_CONNECTION_GET_USER_SSL(s),3044s->session->psk_identity_hint,3045identity, sizeof(identity) - 1,3046psk, sizeof(psk));30473048if (psklen > PSK_MAX_PSK_LEN) {3049SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);3050psklen = PSK_MAX_PSK_LEN; /* Avoid overrunning the array on cleanse */3051goto err;3052} else if (psklen == 0) {3053SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_PSK_IDENTITY_NOT_FOUND);3054goto err;3055}30563057identitylen = strlen(identity);3058if (identitylen > PSK_MAX_IDENTITY_LEN) {3059SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3060goto err;3061}30623063tmppsk = OPENSSL_memdup(psk, psklen);3064tmpidentity = OPENSSL_strdup(identity);3065if (tmppsk == NULL || tmpidentity == NULL) {3066SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3067goto err;3068}30693070OPENSSL_free(s->s3.tmp.psk);3071s->s3.tmp.psk = tmppsk;3072s->s3.tmp.psklen = psklen;3073tmppsk = NULL;3074OPENSSL_free(s->session->psk_identity);3075s->session->psk_identity = tmpidentity;3076tmpidentity = NULL;30773078if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen)) {3079SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3080goto err;3081}30823083ret = 1;30843085err:3086OPENSSL_cleanse(psk, psklen);3087OPENSSL_cleanse(identity, sizeof(identity));3088OPENSSL_clear_free(tmppsk, psklen);3089OPENSSL_clear_free(tmpidentity, identitylen);30903091return ret;3092#else3093SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3094return 0;3095#endif3096}30973098static int tls_construct_cke_rsa(SSL_CONNECTION *s, WPACKET *pkt)3099{3100unsigned char *encdata = NULL;3101EVP_PKEY *pkey = NULL;3102EVP_PKEY_CTX *pctx = NULL;3103size_t enclen;3104unsigned char *pms = NULL;3105size_t pmslen = 0;3106SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);31073108if (!received_server_cert(s)) {3109/*3110* We should always have a server certificate with SSL_kRSA.3111*/3112SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3113return 0;3114}31153116if ((pkey = tls_get_peer_pkey(s)) == NULL) {3117SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3118return 0;3119}31203121if (!EVP_PKEY_is_a(pkey, "RSA")) {3122SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3123return 0;3124}31253126pmslen = SSL_MAX_MASTER_KEY_LENGTH;3127pms = OPENSSL_malloc(pmslen);3128if (pms == NULL) {3129SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3130return 0;3131}31323133pms[0] = s->client_version >> 8;3134pms[1] = s->client_version & 0xff;3135if (RAND_bytes_ex(sctx->libctx, pms + 2, pmslen - 2, 0) <= 0) {3136SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_RAND_LIB);3137goto err;3138}31393140/* Fix buf for TLS and beyond */3141if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {3142SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3143goto err;3144}31453146pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pkey, sctx->propq);3147if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 03148|| EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {3149SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3150goto err;3151}3152if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)3153|| EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {3154SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_RSA_ENCRYPT);3155goto err;3156}3157EVP_PKEY_CTX_free(pctx);3158pctx = NULL;31593160/* Fix buf for TLS and beyond */3161if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {3162SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3163goto err;3164}31653166/* Log the premaster secret, if logging is enabled. */3167if (!ssl_log_rsa_client_key_exchange(s, encdata, enclen, pms, pmslen)) {3168/* SSLfatal() already called */3169goto err;3170}31713172s->s3.tmp.pms = pms;3173s->s3.tmp.pmslen = pmslen;31743175return 1;3176err:3177OPENSSL_clear_free(pms, pmslen);3178EVP_PKEY_CTX_free(pctx);31793180return 0;3181}31823183static int tls_construct_cke_dhe(SSL_CONNECTION *s, WPACKET *pkt)3184{3185EVP_PKEY *ckey = NULL, *skey = NULL;3186unsigned char *keybytes = NULL;3187int prime_len;3188unsigned char *encoded_pub = NULL;3189size_t encoded_pub_len, pad_len;3190int ret = 0;31913192skey = s->s3.peer_tmp;3193if (skey == NULL) {3194SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3195goto err;3196}31973198ckey = ssl_generate_pkey(s, skey);3199if (ckey == NULL) {3200SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3201goto err;3202}32033204if (ssl_derive(s, ckey, skey, 0) == 0) {3205/* SSLfatal() already called */3206goto err;3207}32083209/* send off the data */32103211/* Generate encoding of server key */3212encoded_pub_len = EVP_PKEY_get1_encoded_public_key(ckey, &encoded_pub);3213if (encoded_pub_len == 0) {3214SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3215EVP_PKEY_free(ckey);3216return EXT_RETURN_FAIL;3217}32183219/*3220* For interoperability with some versions of the Microsoft TLS3221* stack, we need to zero pad the DHE pub key to the same length3222* as the prime.3223*/3224prime_len = EVP_PKEY_get_size(ckey);3225pad_len = prime_len - encoded_pub_len;3226if (pad_len > 0) {3227if (!WPACKET_sub_allocate_bytes_u16(pkt, pad_len, &keybytes)) {3228SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3229goto err;3230}3231memset(keybytes, 0, pad_len);3232}32333234if (!WPACKET_sub_memcpy_u16(pkt, encoded_pub, encoded_pub_len)) {3235SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3236goto err;3237}32383239ret = 1;3240err:3241OPENSSL_free(encoded_pub);3242EVP_PKEY_free(ckey);3243return ret;3244}32453246static int tls_construct_cke_ecdhe(SSL_CONNECTION *s, WPACKET *pkt)3247{3248unsigned char *encodedPoint = NULL;3249size_t encoded_pt_len = 0;3250EVP_PKEY *ckey = NULL, *skey = NULL;3251int ret = 0;32523253skey = s->s3.peer_tmp;3254if (skey == NULL) {3255SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3256return 0;3257}32583259ckey = ssl_generate_pkey(s, skey);3260if (ckey == NULL) {3261SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);3262goto err;3263}32643265if (ssl_derive(s, ckey, skey, 0) == 0) {3266/* SSLfatal() already called */3267goto err;3268}32693270/* Generate encoding of client key */3271encoded_pt_len = EVP_PKEY_get1_encoded_public_key(ckey, &encodedPoint);32723273if (encoded_pt_len == 0) {3274SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);3275goto err;3276}32773278if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {3279SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3280goto err;3281}32823283ret = 1;3284err:3285OPENSSL_free(encodedPoint);3286EVP_PKEY_free(ckey);3287return ret;3288}32893290static int tls_construct_cke_gost(SSL_CONNECTION *s, WPACKET *pkt)3291{3292#ifndef OPENSSL_NO_GOST3293/* GOST key exchange message creation */3294EVP_PKEY_CTX *pkey_ctx = NULL;3295EVP_PKEY *pkey = NULL;3296size_t msglen;3297unsigned int md_len;3298unsigned char shared_ukm[32], tmp[256];3299EVP_MD_CTX *ukm_hash = NULL;3300int dgst_nid = NID_id_GostR3411_94;3301unsigned char *pms = NULL;3302size_t pmslen = 0;3303SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);33043305if ((s->s3.tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)3306dgst_nid = NID_id_GostR3411_2012_256;33073308/*3309* Get server certificate PKEY and create ctx from it3310*/3311if ((pkey = tls_get_peer_pkey(s)) == NULL) {3312SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3313SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);3314return 0;3315}33163317pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,3318pkey,3319sctx->propq);3320if (pkey_ctx == NULL) {3321SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3322return 0;3323}3324/*3325* If we have send a certificate, and certificate key3326* parameters match those of server certificate, use3327* certificate key for key exchange3328*/33293330/* Otherwise, generate ephemeral key pair */3331pmslen = 32;3332pms = OPENSSL_malloc(pmslen);3333if (pms == NULL) {3334SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3335goto err;3336}33373338if (EVP_PKEY_encrypt_init(pkey_ctx) <= 03339/* Generate session key3340*/3341|| RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {3342SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3343goto err;3344};3345/*3346* Compute shared IV and store it in algorithm-specific context3347* data3348*/3349ukm_hash = EVP_MD_CTX_new();3350if (ukm_hash == NULL3351|| EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 03352|| EVP_DigestUpdate(ukm_hash, s->s3.client_random,3353SSL3_RANDOM_SIZE) <= 03354|| EVP_DigestUpdate(ukm_hash, s->s3.server_random,3355SSL3_RANDOM_SIZE) <= 03356|| EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {3357SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3358goto err;3359}3360EVP_MD_CTX_free(ukm_hash);3361ukm_hash = NULL;3362if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3363EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) <= 0) {3364SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3365goto err;3366}3367/* Make GOST keytransport blob message */3368/*3369* Encapsulate it into sequence3370*/3371msglen = 255;3372if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {3373SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3374goto err;3375}33763377if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)3378|| (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))3379|| !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {3380SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3381goto err;3382}33833384EVP_PKEY_CTX_free(pkey_ctx);3385s->s3.tmp.pms = pms;3386s->s3.tmp.pmslen = pmslen;33873388return 1;3389err:3390EVP_PKEY_CTX_free(pkey_ctx);3391OPENSSL_clear_free(pms, pmslen);3392EVP_MD_CTX_free(ukm_hash);3393return 0;3394#else3395SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3396return 0;3397#endif3398}33993400#ifndef OPENSSL_NO_GOST3401int ossl_gost18_cke_cipher_nid(const SSL_CONNECTION *s)3402{3403if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_MAGMA) != 0)3404return NID_magma_ctr;3405else if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_KUZNYECHIK) != 0)3406return NID_kuznyechik_ctr;34073408return NID_undef;3409}34103411int ossl_gost_ukm(const SSL_CONNECTION *s, unsigned char *dgst_buf)3412{3413EVP_MD_CTX *hash = NULL;3414unsigned int md_len;3415SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);3416const EVP_MD *md = ssl_evp_md_fetch(sctx->libctx, NID_id_GostR3411_2012_256,3417sctx->propq);34183419if (md == NULL)3420return 0;34213422if ((hash = EVP_MD_CTX_new()) == NULL3423|| EVP_DigestInit(hash, md) <= 03424|| EVP_DigestUpdate(hash, s->s3.client_random, SSL3_RANDOM_SIZE) <= 03425|| EVP_DigestUpdate(hash, s->s3.server_random, SSL3_RANDOM_SIZE) <= 03426|| EVP_DigestFinal_ex(hash, dgst_buf, &md_len) <= 0) {3427EVP_MD_CTX_free(hash);3428ssl_evp_md_free(md);3429return 0;3430}34313432EVP_MD_CTX_free(hash);3433ssl_evp_md_free(md);3434return 1;3435}3436#endif34373438static int tls_construct_cke_gost18(SSL_CONNECTION *s, WPACKET *pkt)3439{3440#ifndef OPENSSL_NO_GOST3441/* GOST 2018 key exchange message creation */3442unsigned char rnd_dgst[32];3443unsigned char *encdata = NULL;3444EVP_PKEY_CTX *pkey_ctx = NULL;3445EVP_PKEY *pkey;3446unsigned char *pms = NULL;3447size_t pmslen = 0;3448size_t msglen;3449int cipher_nid = ossl_gost18_cke_cipher_nid(s);3450SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);34513452if (cipher_nid == NID_undef) {3453SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3454return 0;3455}34563457if (ossl_gost_ukm(s, rnd_dgst) <= 0) {3458SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3459goto err;3460}34613462/* Pre-master secret - random bytes */3463pmslen = 32;3464pms = OPENSSL_malloc(pmslen);3465if (pms == NULL) {3466SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3467goto err;3468}34693470if (RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {3471SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3472goto err;3473}34743475/* Get server certificate PKEY and create ctx from it */3476if ((pkey = tls_get_peer_pkey(s)) == NULL) {3477SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3478SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);3479goto err;3480}34813482pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,3483pkey,3484sctx->propq);3485if (pkey_ctx == NULL) {3486SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3487goto err;3488}34893490if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0) {3491SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3492goto err;3493};34943495/* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code */3496if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3497EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) <= 0) {3498SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3499goto err;3500}35013502if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,3503EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) <= 0) {3504SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);3505goto err;3506}35073508if (EVP_PKEY_encrypt(pkey_ctx, NULL, &msglen, pms, pmslen) <= 0) {3509SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3510goto err;3511}35123513if (!WPACKET_allocate_bytes(pkt, msglen, &encdata)3514|| EVP_PKEY_encrypt(pkey_ctx, encdata, &msglen, pms, pmslen) <= 0) {3515SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);3516goto err;3517}35183519EVP_PKEY_CTX_free(pkey_ctx);3520pkey_ctx = NULL;3521s->s3.tmp.pms = pms;3522s->s3.tmp.pmslen = pmslen;35233524return 1;3525err:3526EVP_PKEY_CTX_free(pkey_ctx);3527OPENSSL_clear_free(pms, pmslen);3528return 0;3529#else3530SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3531return 0;3532#endif3533}35343535static int tls_construct_cke_srp(SSL_CONNECTION *s, WPACKET *pkt)3536{3537#ifndef OPENSSL_NO_SRP3538unsigned char *abytes = NULL;35393540if (s->srp_ctx.A == NULL3541|| !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),3542&abytes)) {3543SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3544return 0;3545}3546BN_bn2bin(s->srp_ctx.A, abytes);35473548OPENSSL_free(s->session->srp_username);3549s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);3550if (s->session->srp_username == NULL) {3551SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);3552return 0;3553}35543555return 1;3556#else3557SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3558return 0;3559#endif3560}35613562CON_FUNC_RETURN tls_construct_client_key_exchange(SSL_CONNECTION *s,3563WPACKET *pkt)3564{3565unsigned long alg_k;35663567alg_k = s->s3.tmp.new_cipher->algorithm_mkey;35683569/*3570* All of the construct functions below call SSLfatal() if necessary so3571* no need to do so here.3572*/3573if ((alg_k & SSL_PSK)3574&& !tls_construct_cke_psk_preamble(s, pkt))3575goto err;35763577if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {3578if (!tls_construct_cke_rsa(s, pkt))3579goto err;3580} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {3581if (!tls_construct_cke_dhe(s, pkt))3582goto err;3583} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {3584if (!tls_construct_cke_ecdhe(s, pkt))3585goto err;3586} else if (alg_k & SSL_kGOST) {3587if (!tls_construct_cke_gost(s, pkt))3588goto err;3589} else if (alg_k & SSL_kGOST18) {3590if (!tls_construct_cke_gost18(s, pkt))3591goto err;3592} else if (alg_k & SSL_kSRP) {3593if (!tls_construct_cke_srp(s, pkt))3594goto err;3595} else if (!(alg_k & SSL_kPSK)) {3596SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3597goto err;3598}35993600return CON_FUNC_SUCCESS;3601err:3602OPENSSL_clear_free(s->s3.tmp.pms, s->s3.tmp.pmslen);3603s->s3.tmp.pms = NULL;3604s->s3.tmp.pmslen = 0;3605#ifndef OPENSSL_NO_PSK3606OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);3607s->s3.tmp.psk = NULL;3608s->s3.tmp.psklen = 0;3609#endif3610return CON_FUNC_ERROR;3611}36123613int tls_client_key_exchange_post_work(SSL_CONNECTION *s)3614{3615unsigned char *pms = NULL;3616size_t pmslen = 0;36173618pms = s->s3.tmp.pms;3619pmslen = s->s3.tmp.pmslen;36203621#ifndef OPENSSL_NO_SRP3622/* Check for SRP */3623if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {3624if (!srp_generate_client_master_secret(s)) {3625/* SSLfatal() already called */3626goto err;3627}3628return 1;3629}3630#endif36313632if (pms == NULL && !(s->s3.tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {3633SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_PASSED_INVALID_ARGUMENT);3634goto err;3635}3636if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {3637/* SSLfatal() already called */3638/* ssl_generate_master_secret frees the pms even on error */3639pms = NULL;3640pmslen = 0;3641goto err;3642}3643pms = NULL;3644pmslen = 0;36453646#ifndef OPENSSL_NO_SCTP3647if (SSL_CONNECTION_IS_DTLS(s)) {3648unsigned char sctpauthkey[64];3649char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];3650size_t labellen;3651SSL *ssl = SSL_CONNECTION_GET_SSL(s);36523653/*3654* Add new shared key for SCTP-Auth, will be ignored if no SCTP3655* used.3656*/3657memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,3658sizeof(DTLS1_SCTP_AUTH_LABEL));36593660/* Don't include the terminating zero. */3661labellen = sizeof(labelbuffer) - 1;3662if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)3663labellen += 1;36643665if (SSL_export_keying_material(ssl, sctpauthkey,3666sizeof(sctpauthkey), labelbuffer,3667labellen, NULL, 0, 0) <= 0) {3668SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3669goto err;3670}36713672BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,3673sizeof(sctpauthkey), sctpauthkey);3674}3675#endif36763677return 1;3678err:3679OPENSSL_clear_free(pms, pmslen);3680s->s3.tmp.pms = NULL;3681s->s3.tmp.pmslen = 0;3682return 0;3683}36843685/*3686* Check a certificate can be used for client authentication. Currently check3687* cert exists, if we have a suitable digest for TLS 1.2 if static DH client3688* certificates can be used and optionally checks suitability for Suite B.3689*/3690static int ssl3_check_client_certificate(SSL_CONNECTION *s)3691{3692/* If no suitable signature algorithm can't use certificate */3693if (!tls_choose_sigalg(s, 0) || s->s3.tmp.sigalg == NULL)3694return 0;3695/*3696* If strict mode check suitability of chain before using it. This also3697* adjusts suite B digest if necessary.3698*/3699if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&3700!tls1_check_chain(s, NULL, NULL, NULL, -2))3701return 0;3702return 1;3703}37043705WORK_STATE tls_prepare_client_certificate(SSL_CONNECTION *s, WORK_STATE wst)3706{3707X509 *x509 = NULL;3708EVP_PKEY *pkey = NULL;3709int i;3710SSL *ssl = SSL_CONNECTION_GET_SSL(s);37113712if (wst == WORK_MORE_A) {3713/* Let cert callback update client certificates if required */3714if (s->cert->cert_cb) {3715i = s->cert->cert_cb(ssl, s->cert->cert_cb_arg);3716if (i < 0) {3717s->rwstate = SSL_X509_LOOKUP;3718return WORK_MORE_A;3719}3720if (i == 0) {3721SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);3722return WORK_ERROR;3723}3724s->rwstate = SSL_NOTHING;3725}3726if (ssl3_check_client_certificate(s)) {3727if (s->post_handshake_auth == SSL_PHA_REQUESTED) {3728return WORK_FINISHED_STOP;3729}3730return WORK_FINISHED_CONTINUE;3731}37323733/* Fall through to WORK_MORE_B */3734wst = WORK_MORE_B;3735}37363737/* We need to get a client cert */3738if (wst == WORK_MORE_B) {3739/*3740* If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;3741* return(-1); We then get retied later3742*/3743i = ssl_do_client_cert_cb(s, &x509, &pkey);3744if (i < 0) {3745s->rwstate = SSL_X509_LOOKUP;3746return WORK_MORE_B;3747}3748s->rwstate = SSL_NOTHING;3749if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {3750if (!SSL_use_certificate(ssl, x509)3751|| !SSL_use_PrivateKey(ssl, pkey))3752i = 0;3753} else if (i == 1) {3754i = 0;3755ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);3756}37573758X509_free(x509);3759EVP_PKEY_free(pkey);3760if (i && !ssl3_check_client_certificate(s))3761i = 0;3762if (i == 0) {3763if (s->version == SSL3_VERSION) {3764s->s3.tmp.cert_req = 0;3765ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);3766return WORK_FINISHED_CONTINUE;3767} else {3768s->s3.tmp.cert_req = 2;3769s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;3770if (!ssl3_digest_cached_records(s, 0)) {3771/* SSLfatal() already called */3772return WORK_ERROR;3773}3774}3775}37763777if (!SSL_CONNECTION_IS_TLS13(s)3778|| (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)3779s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;37803781if (s->post_handshake_auth == SSL_PHA_REQUESTED)3782return WORK_FINISHED_STOP;3783return WORK_FINISHED_CONTINUE;3784}37853786/* Shouldn't ever get here */3787SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3788return WORK_ERROR;3789}37903791CON_FUNC_RETURN tls_construct_client_certificate(SSL_CONNECTION *s,3792WPACKET *pkt)3793{3794CERT_PKEY *cpk = NULL;3795SSL *ssl = SSL_CONNECTION_GET_SSL(s);37963797if (SSL_CONNECTION_IS_TLS13(s)) {3798if (s->pha_context == NULL) {3799/* no context available, add 0-length context */3800if (!WPACKET_put_bytes_u8(pkt, 0)) {3801SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3802return CON_FUNC_ERROR;3803}3804} else if (!WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {3805SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3806return CON_FUNC_ERROR;3807}3808}3809if (s->s3.tmp.cert_req != 2)3810cpk = s->cert->key;3811switch (s->ext.client_cert_type) {3812case TLSEXT_cert_type_rpk:3813if (!tls_output_rpk(s, pkt, cpk)) {3814/* SSLfatal() already called */3815return CON_FUNC_ERROR;3816}3817break;3818case TLSEXT_cert_type_x509:3819if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {3820/* SSLfatal() already called */3821return CON_FUNC_ERROR;3822}3823break;3824default:3825SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3826return CON_FUNC_ERROR;3827}38283829/*3830* If we attempted to write early data or we're in middlebox compat mode3831* then we deferred changing the handshake write keys to the last possible3832* moment. We need to do it now.3833*/3834if (SSL_CONNECTION_IS_TLS13(s)3835&& !SSL_IS_QUIC_HANDSHAKE(s)3836&& SSL_IS_FIRST_HANDSHAKE(s)3837&& (s->early_data_state != SSL_EARLY_DATA_NONE3838|| (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)3839&& (!ssl->method->ssl3_enc->change_cipher_state(s,3840SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {3841/*3842* This is a fatal error, which leaves enc_write_ctx in an inconsistent3843* state and thus ssl3_send_alert may crash.3844*/3845SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);3846return CON_FUNC_ERROR;3847}38483849return CON_FUNC_SUCCESS;3850}38513852#ifndef OPENSSL_NO_COMP_ALG3853CON_FUNC_RETURN tls_construct_client_compressed_certificate(SSL_CONNECTION *sc,3854WPACKET *pkt)3855{3856SSL *ssl = SSL_CONNECTION_GET_SSL(sc);3857WPACKET tmppkt;3858BUF_MEM *buf = NULL;3859size_t length;3860size_t max_length;3861COMP_METHOD *method;3862COMP_CTX *comp = NULL;3863int comp_len;3864int ret = 0;3865int alg = sc->ext.compress_certificate_from_peer[0];38663867/* Note that sc->s3.tmp.cert_req == 2 is checked in write transition */38683869if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init(&tmppkt, buf))3870goto err;38713872/* Use the |tmppkt| for the to-be-compressed data */3873if (sc->pha_context == NULL) {3874/* no context available, add 0-length context */3875if (!WPACKET_put_bytes_u8(&tmppkt, 0))3876goto err;3877} else if (!WPACKET_sub_memcpy_u8(&tmppkt, sc->pha_context, sc->pha_context_len))3878goto err;38793880if (!ssl3_output_cert_chain(sc, &tmppkt, sc->cert->key, 0)) {3881/* SSLfatal() already called */3882goto out;3883}38843885/* continue with the real |pkt| */3886if (!WPACKET_put_bytes_u16(pkt, alg)3887|| !WPACKET_get_total_written(&tmppkt, &length)3888|| !WPACKET_put_bytes_u24(pkt, length))3889goto err;38903891switch (alg) {3892case TLSEXT_comp_cert_zlib:3893method = COMP_zlib_oneshot();3894break;3895case TLSEXT_comp_cert_brotli:3896method = COMP_brotli_oneshot();3897break;3898case TLSEXT_comp_cert_zstd:3899method = COMP_zstd_oneshot();3900break;3901default:3902goto err;3903}3904max_length = ossl_calculate_comp_expansion(alg, length);39053906if ((comp = COMP_CTX_new(method)) == NULL3907|| !WPACKET_start_sub_packet_u24(pkt)3908|| !WPACKET_reserve_bytes(pkt, max_length, NULL))3909goto err;39103911comp_len = COMP_compress_block(comp, WPACKET_get_curr(pkt), max_length,3912(unsigned char *)buf->data, length);3913if (comp_len <= 0)3914goto err;39153916if (!WPACKET_allocate_bytes(pkt, comp_len, NULL)3917|| !WPACKET_close(pkt))3918goto err;39193920/*3921* If we attempted to write early data or we're in middlebox compat mode3922* then we deferred changing the handshake write keys to the last possible3923* moment. We need to do it now.3924*/3925if (SSL_IS_FIRST_HANDSHAKE(sc)3926&& !SSL_IS_QUIC_HANDSHAKE(sc)3927&& (sc->early_data_state != SSL_EARLY_DATA_NONE3928|| (sc->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)3929&& (!ssl->method->ssl3_enc->change_cipher_state(sc,3930SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {3931/*3932* This is a fatal error, which leaves sc->enc_write_ctx in an3933* inconsistent state and thus ssl3_send_alert may crash.3934*/3935SSLfatal(sc, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);3936goto out;3937}3938ret = 1;3939goto out;39403941err:3942SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3943out:3944if (buf != NULL) {3945/* If |buf| is NULL, then |tmppkt| could not have been initialized */3946WPACKET_cleanup(&tmppkt);3947}3948BUF_MEM_free(buf);3949COMP_CTX_free(comp);3950return ret;3951}3952#endif39533954int ssl3_check_cert_and_algorithm(SSL_CONNECTION *s)3955{3956const SSL_CERT_LOOKUP *clu;3957size_t idx;3958long alg_k, alg_a;3959EVP_PKEY *pkey;39603961alg_k = s->s3.tmp.new_cipher->algorithm_mkey;3962alg_a = s->s3.tmp.new_cipher->algorithm_auth;39633964/* we don't have a certificate */3965if (!(alg_a & SSL_aCERT))3966return 1;39673968/* This is the passed certificate */3969pkey = tls_get_peer_pkey(s);3970clu = ssl_cert_lookup_by_pkey(pkey, &idx, SSL_CONNECTION_GET_CTX(s));39713972/* Check certificate is recognised and suitable for cipher */3973if (clu == NULL || (alg_a & clu->amask) == 0) {3974SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_SIGNING_CERT);3975return 0;3976}39773978if (alg_k & (SSL_kRSA | SSL_kRSAPSK) && idx != SSL_PKEY_RSA) {3979SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,3980SSL_R_MISSING_RSA_ENCRYPTING_CERT);3981return 0;3982}39833984if ((alg_k & SSL_kDHE) && (s->s3.peer_tmp == NULL)) {3985SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);3986return 0;3987}39883989/* Early out to skip the checks below */3990if (s->session->peer_rpk != NULL)3991return 1;39923993if (clu->amask & SSL_aECDSA) {3994if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s))3995return 1;3996SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_ECC_CERT);3997return 0;3998}39994000return 1;4001}40024003#ifndef OPENSSL_NO_NEXTPROTONEG4004CON_FUNC_RETURN tls_construct_next_proto(SSL_CONNECTION *s, WPACKET *pkt)4005{4006size_t len, padding_len;4007unsigned char *padding = NULL;40084009len = s->ext.npn_len;4010padding_len = 32 - ((len + 2) % 32);40114012if (!WPACKET_sub_memcpy_u8(pkt, s->ext.npn, len)4013|| !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {4014SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4015return CON_FUNC_ERROR;4016}40174018memset(padding, 0, padding_len);40194020return CON_FUNC_SUCCESS;4021}4022#endif40234024MSG_PROCESS_RETURN tls_process_hello_req(SSL_CONNECTION *s, PACKET *pkt)4025{4026SSL *ssl = SSL_CONNECTION_GET_SSL(s);40274028if (PACKET_remaining(pkt) > 0) {4029/* should contain no data */4030SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4031return MSG_PROCESS_ERROR;4032}40334034if ((s->options & SSL_OP_NO_RENEGOTIATION)) {4035ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);4036return MSG_PROCESS_FINISHED_READING;4037}40384039/*4040* This is a historical discrepancy (not in the RFC) maintained for4041* compatibility reasons. If a TLS client receives a HelloRequest it will4042* attempt an abbreviated handshake. However if a DTLS client receives a4043* HelloRequest it will do a full handshake. Either behaviour is reasonable4044* but doing one for TLS and another for DTLS is odd.4045*/4046if (SSL_CONNECTION_IS_DTLS(s))4047SSL_renegotiate(ssl);4048else4049SSL_renegotiate_abbreviated(ssl);40504051return MSG_PROCESS_FINISHED_READING;4052}40534054static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,4055PACKET *pkt)4056{4057PACKET extensions;4058RAW_EXTENSION *rawexts = NULL;40594060if (!PACKET_as_length_prefixed_2(pkt, &extensions)4061|| PACKET_remaining(pkt) != 0) {4062SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);4063goto err;4064}40654066if (!tls_collect_extensions(s, &extensions,4067SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, &rawexts,4068NULL, 1)4069|| !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,4070rawexts, NULL, 0, 1)) {4071/* SSLfatal() already called */4072goto err;4073}40744075OPENSSL_free(rawexts);4076return MSG_PROCESS_CONTINUE_READING;40774078err:4079OPENSSL_free(rawexts);4080return MSG_PROCESS_ERROR;4081}40824083int ssl_do_client_cert_cb(SSL_CONNECTION *s, X509 **px509, EVP_PKEY **ppkey)4084{4085int i = 0;4086SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);40874088#ifndef OPENSSL_NO_ENGINE4089if (sctx->client_cert_engine) {4090i = tls_engine_load_ssl_client_cert(s, px509, ppkey);4091if (i != 0)4092return i;4093}4094#endif4095if (sctx->client_cert_cb)4096i = sctx->client_cert_cb(SSL_CONNECTION_GET_USER_SSL(s), px509, ppkey);4097return i;4098}40994100int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,4101WPACKET *pkt)4102{4103int i;4104size_t totlen = 0, len, maxlen, maxverok = 0;4105int empty_reneg_info_scsv = !s->renegotiate4106&& !SSL_CONNECTION_IS_DTLS(s)4107&& ssl_security(s, SSL_SECOP_VERSION, 0, TLS1_VERSION, NULL)4108&& s->min_proto_version <= TLS1_VERSION;4109SSL *ssl = SSL_CONNECTION_GET_SSL(s);41104111/* Set disabled masks for this session */4112if (!ssl_set_client_disabled(s)) {4113SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_PROTOCOLS_AVAILABLE);4114return 0;4115}41164117if (sk == NULL) {4118SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4119return 0;4120}41214122#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH4123# if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 64124# error Max cipher length too short4125# endif4126/*4127* Some servers hang if client hello > 256 bytes as hack workaround4128* chop number of supported ciphers to keep it well below this if we4129* use TLS v1.24130*/4131if (TLS1_get_version(ssl) >= TLS1_2_VERSION)4132maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;4133else4134#endif4135/* Maximum length that can be stored in 2 bytes. Length must be even */4136maxlen = 0xfffe;41374138if (empty_reneg_info_scsv)4139maxlen -= 2;4140if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)4141maxlen -= 2;41424143for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {4144const SSL_CIPHER *c;41454146c = sk_SSL_CIPHER_value(sk, i);4147/* Skip disabled ciphers */4148if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))4149continue;41504151if (!ssl->method->put_cipher_by_char(c, pkt, &len)) {4152SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4153return 0;4154}41554156/* Sanity check that the maximum version we offer has ciphers enabled */4157if (!maxverok) {4158int minproto = SSL_CONNECTION_IS_DTLS(s) ? c->min_dtls : c->min_tls;4159int maxproto = SSL_CONNECTION_IS_DTLS(s) ? c->max_dtls : c->max_tls;41604161if (ssl_version_cmp(s, maxproto, s->s3.tmp.max_ver) >= 04162&& ssl_version_cmp(s, minproto, s->s3.tmp.max_ver) <= 0)4163maxverok = 1;4164}41654166totlen += len;4167}41684169if (totlen == 0 || !maxverok) {4170const char *maxvertext =4171!maxverok4172? "No ciphers enabled for max supported SSL/TLS version"4173: NULL;41744175SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_CIPHERS_AVAILABLE,4176maxvertext);4177return 0;4178}41794180if (totlen != 0) {4181if (empty_reneg_info_scsv) {4182static const SSL_CIPHER scsv = {41830, NULL, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 04184};4185if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {4186SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4187return 0;4188}4189}4190if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {4191static const SSL_CIPHER scsv = {41920, NULL, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 04193};4194if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {4195SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);4196return 0;4197}4198}4199}42004201return 1;4202}42034204CON_FUNC_RETURN tls_construct_end_of_early_data(SSL_CONNECTION *s, WPACKET *pkt)4205{4206if (s->early_data_state != SSL_EARLY_DATA_WRITE_RETRY4207&& s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING) {4208SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);4209return CON_FUNC_ERROR;4210}42114212s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;4213return CON_FUNC_SUCCESS;4214}421542164217