10#include <botan/internal/tls_client_impl_12.h>
12#include <botan/exceptn.h>
13#include <botan/ocsp.h>
14#include <botan/tls_callbacks.h>
15#include <botan/tls_messages_12.h>
16#include <botan/tls_policy.h>
17#include <botan/internal/stl_util.h>
18#include <botan/internal/tls_handshake_state.h>
30 Client_Handshake_State_12(std::unique_ptr<Handshake_IO> io, Callbacks& cb) :
31 Handshake_State(std::move(io), cb), m_is_reneg(false) {}
33 const Public_Key& server_public_key()
const {
34 BOTAN_ASSERT(m_server_public_key,
"Server sent us a certificate");
35 return *m_server_public_key;
38 const Public_Key* maybe_server_public_key()
const {
return m_server_public_key.get(); }
40 void record_server_public_key(std::unique_ptr<Public_Key> spk) {
42 m_server_public_key = std::move(spk);
45 bool is_a_resumption()
const {
return m_resumed_session.has_value(); }
47 void discard_resumption_state() { m_resumed_session.reset(); }
49 void record_resumption_info(std::optional<Session> session_info) {
51 m_resumed_session = std::move(session_info);
54 bool is_a_renegotiation()
const {
return m_is_reneg; }
56 void mark_as_renegotiation() { m_is_reneg =
true; }
58 size_t note_hello_verify_request() {
return ++m_hello_verify_requests; }
62 return m_resumed_session->master_secret();
65 const std::vector<X509_Certificate>& resume_peer_certs()
const {
67 return m_resumed_session->peer_certs();
70 bool resumed_session_supports_extended_master_secret()
const {
72 return m_resumed_session->supports_extended_master_secret();
75 uint16_t resumed_session_ciphersuite_code()
const {
77 return m_resumed_session->ciphersuite_code();
80 bool resumed_session_supports_encrypt_then_mac()
const {
82 return m_resumed_session->supports_encrypt_then_mac();
85 uint16_t resumed_session_dtls_srtp_profile()
const {
87 return m_resumed_session->dtls_srtp_profile();
90 std::vector<X509_Certificate> peer_cert_chain()
const override {
91 if(is_a_resumption()) {
92 return resume_peer_certs();
94 if(has_server_certs()) {
95 return server_certs().cert_chain();
101 std::unique_ptr<Public_Key> m_server_public_key;
104 std::optional<Session> m_resumed_session;
105 bool m_is_reneg =
false;
106 size_t m_hello_verify_requests = 0;
113 const std::shared_ptr<Credentials_Manager>& creds,
114 const std::shared_ptr<const Policy>&
policy,
115 const std::shared_ptr<RandomNumberGenerator>&
rng,
118 const std::vector<std::string>& next_protocols,
119 size_t reserved_io_buffer_size) {
120 auto self = std::make_shared<Client_Impl_12>(
Private{},
126 std::move(server_info),
128 reserved_io_buffer_size);
131 const auto version = (
flavor ==
TLS_Flavor::DTLS) ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
133 self->send_client_hello(state,
false, version, std::nullopt , next_protocols);
138#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
140std::shared_ptr<Client_Impl_12> Client_Impl_12::create_for_downgrade(
141 Channel_Impl::Downgrade_Information& downgrade_info) {
142 auto self = std::make_shared<Client_Impl_12>(
Private{}, downgrade_info);
147 if(downgrade_info.client_hello.has_value()) {
155 downgrade_info.epoch0_sequence_numbers.has_value(),
156 "downgrading DTLS requires transferring the record sequence numbers");
159 const auto seqno_read = [](
const std::optional<Epoch0_SequenceNumbers>& seq) -> std::optional<uint64_t> {
160 if(seq.has_value()) {
165 const auto seqno_write = [](
const std::optional<Epoch0_SequenceNumbers>& seq) -> std::optional<uint64_t> {
166 if(seq.has_value()) {
172 auto& state = self->create_handshake_state(version,
174 seqno_read(downgrade_info.epoch0_sequence_numbers),
175 seqno_write(downgrade_info.epoch0_sequence_numbers));
177 state.client_hello(std::make_unique<Client_Hello_12>(
178 std::exchange(downgrade_info.client_hello, {}).value(), state.handshake_io(), state.hash()));
180 self->secure_renegotiation_check(state.maybe_client_hello());
189 downgrade_info.tls12_session->session.version().is_pre_tls_13());
190 BOTAN_ASSERT_NOMSG(downgrade_info.tls12_session->session.version().is_datagram_protocol() ==
196 auto& state = self->create_handshake_state(version);
197 self->send_client_hello(state,
199 downgrade_info.tls12_session->session.version(),
200 downgrade_info.tls12_session,
201 downgrade_info.next_protocols);
209std::unique_ptr<Handshake_State> Client_Impl_12::new_handshake_state(std::unique_ptr<Handshake_IO> io) {
210 return std::make_unique<Client_Handshake_State_12>(std::move(io),
callbacks());
216void Client_Impl_12::initiate_handshake(
Handshake_State& state,
bool force_full_renegotiation) {
218 const auto version = state.version().is_datagram_protocol() ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
219 send_client_hello(state, force_full_renegotiation, version);
223 bool force_full_renegotiation,
225 std::optional<Session_with_Handle> session_and_handle,
226 const std::vector<std::string>& next_protocols) {
227 Client_Handshake_State_12& state =
dynamic_cast<Client_Handshake_State_12&
>(state_base);
229 if(state.version().is_datagram_protocol()) {
234 if(!force_full_renegotiation) {
236 if(!session_and_handle.has_value() && !m_info.empty()) {
238 session_and_handle = std::move(sessions.front());
242 if(session_and_handle.has_value()) {
247 auto& session_info = session_and_handle->session;
248 const bool exact_version = session_info.version() == version;
249 const bool ok_version = (session_info.version().is_datagram_protocol() == version.is_datagram_protocol()) &&
256 const bool session_suite_ok =
257 session_version_ok &&
258 value_exists(
policy().ciphersuite_list(session_info.version()), session_info.ciphersuite_code());
261 const bool session_srtp_ok = session_info.dtls_srtp_profile() == 0 ||
264 if(session_suite_ok && session_srtp_ok) {
266 state.client_hello(std::make_unique<Client_Hello_12>(state.handshake_io(),
272 session_and_handle.value(),
275 state.record_resumption_info(std::move(session_info));
285 }
catch(Encoding_Error&) {
295 if(!state.has_client_hello()) {
297 const Client_Hello_12::Settings client_settings(version, m_info.hostname());
298 state.client_hello(std::make_unique<Client_Hello_12>(state.handshake_io(),
324bool key_usage_matches_ciphersuite(Key_Constraints usage,
const Ciphersuite& suite) {
343 const std::vector<uint8_t>& contents,
344 bool epoch0_restart) {
347 Client_Handshake_State_12& state =
dynamic_cast<Client_Handshake_State_12&
>(state_base);
350 const Hello_Request hello_request(contents);
355 if(state.has_client_hello()) {
359 if(
policy().allow_server_initiated_renegotiation()) {
361 state.mark_as_renegotiation();
362 initiate_handshake(state,
true );
364 throw TLS_Exception(Alert::HandshakeFailure,
"Client policy prohibits insecure renegotiation");
367 if(
policy().abort_connection_on_undesired_renegotiation()) {
368 throw TLS_Exception(Alert::NoRenegotiation,
"Client policy prohibits renegotiation");
378 state.confirm_transition_to(type);
382 state.hash().update(state.handshake_io().format(contents, type));
395 const size_t hello_verify_requests = state.note_hello_verify_request();
398 if(max_hello_verify_requests.has_value() && hello_verify_requests > max_hello_verify_requests.value()) {
399 throw TLS_Exception(Alert::UnexpectedMessage,
"Too many DTLS HelloVerifyRequest messages");
405 const Hello_Verify_Request hello_verify_request(contents);
406 state.hello_verify_request(hello_verify_request);
411 state.server_hello(std::make_unique<Server_Hello_12>(contents));
413 if(!state.server_hello().legacy_version().valid()) {
414 throw TLS_Exception(Alert::ProtocolVersion,
"Server replied with an invalid version");
417 if(state.client_hello().legacy_version().is_datagram_protocol() !=
418 state.server_hello().legacy_version().is_datagram_protocol()) {
419 throw TLS_Exception(Alert::ProtocolVersion,
"Server replied with different protocol type than we offered");
422 if(!state.client_hello().offered_suite(state.server_hello().ciphersuite())) {
423 throw TLS_Exception(Alert::HandshakeFailure,
"Server replied with ciphersuite we didn't send");
427 if(!suite || !suite->usable_in_version(state.server_hello().legacy_version())) {
428 throw TLS_Exception(Alert::HandshakeFailure,
429 "Server replied using a ciphersuite not allowed in version it offered");
437 if(!suite->cbc_ciphersuite() && state.server_hello().supports_encrypt_then_mac()) {
438 throw TLS_Exception(Alert::IllegalParameter,
439 "Server replied using a non-CBC ciphersuite and an encrypt-then-MAC response extension");
443 throw TLS_Exception(Alert::HandshakeFailure,
"Server replied with a signaling ciphersuite");
446 if(state.server_hello().compression_method() != 0) {
447 throw TLS_Exception(Alert::IllegalParameter,
"Server replied with non-null compression method");
450 const auto downgrade_signal = state.server_hello().random_signals_downgrade();
451 if(downgrade_signal.has_value()) {
459 if(state.client_hello().offered_tls13()) {
460 throw TLS_Exception(Alert::IllegalParameter,
"Downgrade attack detected");
471 if(state.client_hello().legacy_version() > state.server_hello().legacy_version() &&
472 downgrade_signal.value() <= Protocol_Version::TLS_V11) {
473 throw TLS_Exception(Alert::IllegalParameter,
"Downgrade attack detected");
477 const auto client_extn = state.client_hello().extension_types();
478 const auto server_extn = state.server_hello().extension_types();
480 std::vector<Extension_Code> diff;
483 server_extn.begin(), server_extn.end(), client_extn.begin(), client_extn.end(), std::back_inserter(diff));
488 std::ostringstream msg;
489 msg <<
"Server replied with unsupported extensions:";
490 for(
auto&& d : diff) {
491 msg <<
" " <<
static_cast<int>(d);
493 throw TLS_Exception(Alert::UnsupportedExtension, msg.str());
496 if(
const uint16_t srtp = state.server_hello().srtp_profile()) {
497 if(!
value_exists(state.client_hello().srtp_profiles(), srtp)) {
498 throw TLS_Exception(Alert::HandshakeFailure,
"Server replied with DTLS-SRTP alg we did not send");
505 state.set_version(state.server_hello().legacy_version());
507 if(state.server_hello().extensions().has<Application_Layer_Protocol_Notification>()) {
508 const auto* server_alpn = state.server_hello().extensions().get<Application_Layer_Protocol_Notification>();
509 const auto selected = server_alpn->single_protocol();
510 const auto* client_alpn = state.client_hello().extensions().get<Application_Layer_Protocol_Notification>();
512 const auto& offered = client_alpn->protocols();
514 throw TLS_Exception(Alert::IllegalParameter,
"Server selected an ALPN protocol not offered by the client");
517 if(
active_state().has_value() && !state.client_hello().supports_alpn()) {
521 m_application_protocol =
active_state()->application_protocol();
523 m_application_protocol = state.server_hello().next_protocol();
529 if(
policy().require_extended_master_secret() && !state.server_hello().supports_extended_master_secret()) {
530 throw TLS_Exception(Alert::HandshakeFailure,
531 "Policy requires the Extended Master Secret extension but the server did not send it");
534 const bool server_returned_same_session_id =
535 !state.server_hello().session_id().empty() &&
536 (state.server_hello().session_id() == state.client_hello().session_id());
538 if(server_returned_same_session_id) {
546 if(state.server_hello().legacy_version() != state.client_hello().legacy_version()) {
547 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session but with wrong version");
552 if(state.server_hello().ciphersuite() != state.resumed_session_ciphersuite_code()) {
553 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session with a different ciphersuite");
556 if(state.server_hello().supports_extended_master_secret() &&
557 !state.resumed_session_supports_extended_master_secret()) {
558 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session but added extended master secret");
561 if(!state.server_hello().supports_extended_master_secret() &&
562 state.resumed_session_supports_extended_master_secret()) {
563 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session and removed extended master secret");
569 if(state.server_hello().supports_encrypt_then_mac() != state.resumed_session_supports_encrypt_then_mac()) {
570 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session but changed encrypt-then-MAC");
573 if(state.server_hello().srtp_profile() != state.resumed_session_dtls_srtp_profile()) {
574 throw TLS_Exception(Alert::HandshakeFailure,
"Server resumed session but changed the DTLS-SRTP profile");
577 state.compute_session_keys(state.resume_master_secret());
578 if(
policy().allow_ssl_key_log_file()) {
584 "CLIENT_RANDOM", state.client_hello().random(), state.session_keys().master_secret());
587 if(state.server_hello().supports_session_ticket()) {
600 if(
active_state()->version() != state.server_hello().legacy_version()) {
601 throw TLS_Exception(Alert::ProtocolVersion,
"Server changed version after renegotiation");
604 if(state.server_hello().supports_extended_master_secret() !=
606 throw TLS_Exception(Alert::HandshakeFailure,
"Server changed its mind about extended master secret");
610 state.discard_resumption_state();
612 if(state.version() > state.client_hello().legacy_version()) {
613 throw TLS_Exception(Alert::HandshakeFailure,
"Server replied with later version than client offered");
616 if(state.version().major_version() == 3 && state.version().minor_version() == 0) {
617 throw TLS_Exception(Alert::ProtocolVersion,
"Server attempting to negotiate SSLv3 which is not supported");
620 if(!
policy().acceptable_protocol_version(state.version())) {
621 throw TLS_Exception(Alert::ProtocolVersion,
622 "Server version " + state.version().to_string() +
" is unacceptable by policy");
625 if(state.ciphersuite().is_certificate_required()) {
627 }
else if(state.ciphersuite().kex_method() ==
Kex_Algo::PSK) {
648 state.server_certs(std::make_unique<Certificate_12>(contents,
policy()));
650 const std::vector<X509_Certificate>& server_certs = state.server_certs().cert_chain();
652 if(server_certs.empty()) {
653 throw TLS_Exception(Alert::HandshakeFailure,
"Client: No certificates sent by server");
662 const X509_Certificate server_cert = server_certs[0];
665 const X509_Certificate& current_cert =
active_state()->peer_certs().at(0);
667 if(current_cert != server_cert) {
668 throw TLS_Exception(Alert::BadCertificate,
"Server certificate changed during renegotiation");
672 auto peer_key = server_cert.subject_public_key();
674 const std::string expected_key_type =
675 state.ciphersuite().signature_used() ? state.ciphersuite().sig_algo() :
"RSA";
677 if(peer_key->algo_name() != expected_key_type) {
678 throw TLS_Exception(Alert::IllegalParameter,
"Certificate key type did not match ciphersuite");
681 if(!key_usage_matches_ciphersuite(server_cert.constraints(), state.ciphersuite())) {
682 throw TLS_Exception(Alert::BadCertificate,
"Certificate usage constraints do not allow this ciphersuite");
689 state.record_server_public_key(std::move(peer_key));
698 if(state.server_hello().supports_certificate_status_message()) {
702 const auto trusted_CAs = m_creds->trusted_certificate_authorities(
"tls-client", m_info.hostname());
706 }
catch(TLS_Exception&) {
708 }
catch(std::exception& e) {
709 throw TLS_Exception(Alert::InternalError, e.what());
722 if(!state.ciphersuite().psk_ciphersuite()) {
727 state.server_kex(std::make_unique<Server_Key_Exchange>(
728 contents, state.ciphersuite().kex_method(), state.ciphersuite().auth_method(), state.version()));
730 if(state.ciphersuite().signature_used()) {
731 const Public_Key& server_key = state.server_public_key();
733 if(!state.server_kex().verify(server_key, state,
policy())) {
734 throw TLS_Exception(Alert::DecryptError,
"Bad signature on server key exchange");
739 state.cert_req(std::make_unique<Certificate_Request_12>(contents));
741 state.server_hello_done(std::make_unique<Server_Hello_Done>(contents));
743 if(state.handshake_io().have_more_data()) {
744 throw TLS_Exception(Alert::UnexpectedMessage,
"Have data remaining in buffer after ServerHelloDone");
747 if(state.has_server_certs() && state.server_hello().supports_certificate_status_message()) {
749 const auto trusted_CAs = m_creds->trusted_certificate_authorities(
"tls-client", m_info.hostname());
751 std::vector<std::optional<OCSP::Response>> ocsp;
752 if(state.has_server_cert_status()) {
753 ocsp.emplace_back(
callbacks().tls_parse_ocsp_response(state.server_cert_status().response()));
762 }
catch(TLS_Exception&) {
764 }
catch(std::exception& e) {
765 throw TLS_Exception(Alert::InternalError, e.what());
770 const auto& cert_req = state.cert_req();
785 std::vector<std::string> key_types;
786 for(
const auto& cert_type : cert_req.acceptable_cert_types()) {
788 key_types.push_back(cert_type);
798 std::vector<X509_Certificate> client_certs;
799 if(!key_types.empty()) {
800 client_certs = m_creds->find_cert_chain(key_types,
802 cert_req.acceptable_CAs(),
807 state.client_certs(std::make_unique<Certificate_12>(state.handshake_io(), state.hash(), client_certs));
810 state.client_kex(std::make_unique<Client_Key_Exchange>(
811 state.handshake_io(), state,
policy(), *m_creds, state.maybe_server_public_key(), m_info.hostname(),
rng()));
813 state.compute_session_keys();
814 if(
policy().allow_ssl_key_log_file()) {
820 "CLIENT_RANDOM", state.client_hello().random(), state.session_keys().master_secret());
824 const auto private_key =
825 m_creds->private_key_for(state.client_certs().cert_chain()[0],
"tls-client", m_info.hostname());
828 throw TLS_Exception(Alert::InternalError,
"Failed to get private key for signing");
832 std::make_unique<Certificate_Verify_12>(state.handshake_io(), state,
policy(),
rng(), private_key.get()));
835 state.handshake_io().send(Change_Cipher_Spec());
845 if(state.server_hello().supports_session_ticket()) {
851 state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(contents));
859 if(state.handshake_io().have_more_data()) {
860 throw TLS_Exception(Alert::UnexpectedMessage,
"Have data remaining in buffer after Finished");
863 state.server_finished(std::make_unique<Finished_12>(contents));
866 throw TLS_Exception(Alert::DecryptError,
"Finished message didn't verify");
869 state.hash().update(state.handshake_io().format(contents, type));
871 if(!state.has_client_finished()) {
873 state.handshake_io().send(Change_Cipher_Spec());
880 const std::chrono::seconds session_lifetime_hint = [&] {
881 if(state.has_new_session_ticket()) {
882 return std::chrono::seconds(state.new_session_ticket().ticket_lifetime_hint());
884 return std::chrono::seconds::max();
888 Session session_info(state.session_keys().master_secret(),
889 state.server_hello().legacy_version(),
890 state.server_hello().ciphersuite(),
892 state.server_hello().supports_extended_master_secret(),
893 state.server_hello().supports_encrypt_then_mac(),
894 state.peer_cert_chain(),
896 state.server_hello().srtp_profile(),
898 session_lifetime_hint);
903 const auto handle = [&]() -> std::optional<Session_Handle> {
911 if(
const auto* nst = state.maybe_new_session_ticket(); nst !=
nullptr && !nst->ticket().empty()) {
912 return Session_Handle(nst->ticket());
914 if(state.is_a_resumption() && !state.client_hello().session_ticket().empty()) {
915 return Session_Handle(state.client_hello().session_ticket());
917 if(
const auto& session_id = state.server_hello().session_id(); !session_id.empty()) {
918 return Session_Handle(session_id);
926 Session_Summary summary(session_info, state.is_a_resumption(), state.psk_identity());
927 summary.set_session_id(state.server_hello().session_id());
928 if(
const auto* nst = state.maybe_new_session_ticket()) {
929 summary.set_session_ticket(nst->ticket());
934 if(handle.has_value()) {
944 if(state.is_a_resumption() && !state.client_hello().session_ticket().empty() && handle->is_ticket() &&
952 if(!state.is_a_resumption()) {
958 }
else if(!should_save) {
961 if(!state.client_hello().session_ticket().empty()) {
971 throw Unexpected_Message(
"Unknown handshake message received");
#define BOTAN_ASSERT_NOMSG(expr)
#define BOTAN_STATE_CHECK(expr)
#define BOTAN_ASSERT_NONNULL(ptr)
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
#define BOTAN_ASSERT(expr, assertion_made)
virtual void tls_examine_extensions(const Extensions &extn, Connection_Side which_side, Handshake_Type which_message)
virtual void tls_session_established(const Session_Summary &session)
virtual bool tls_should_persist_resumption_information(const Session &session)
virtual void tls_verify_cert_chain(const std::vector< X509_Certificate > &cert_chain, const std::vector< std::optional< OCSP::Response > > &ocsp_responses, const std::vector< Certificate_Store * > &trusted_roots, Usage_Type usage, std::string_view hostname, const TLS::Policy &policy)
virtual void tls_ssl_key_log_data(std::string_view label, std::span< const uint8_t > client_random, std::span< const uint8_t > secret) const
RandomNumberGenerator & rng()
void change_cipher_spec_reader(Connection_Side side)
void maybe_arm_dtls_retransmission_timer(TimerGeneration generation_policy=TimerGeneration::Advance)
Callbacks & callbacks() const
TLS_Flavor flavor() const
Session_Manager & session_manager()
const Policy & policy() const
void note_resumption_handle(std::optional< Session_Handle > handle)
void change_cipher_spec_writer(Connection_Side side)
std::vector< uint8_t > secure_renegotiation_data_for_client_hello() const
void secure_renegotiation_check(const Client_Hello_12 *client_hello, bool fresh_handshake_mode=false)
const std::optional< Active_Connection_State_12 > & active_state() const
bool secure_renegotiation_supported() const override
void send_warning_alert(Alert::Type type)
static bool is_scsv(uint16_t suite)
static std::optional< Ciphersuite > by_id(uint16_t suite)
static std::shared_ptr< Client_Impl_12 > create(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< Credentials_Manager > &creds, const std::shared_ptr< const Policy > &policy, const std::shared_ptr< RandomNumberGenerator > &rng, Server_Information server_info=Server_Information(), TLS_Flavor flavor=TLS_Flavor::TLS, const std::vector< std::string > &next_protocols={}, size_t reserved_io_buffer_size=TLS::Channel::IO_BUF_DEFAULT_SIZE)
virtual void check_peer_key_acceptable(const Public_Key &public_key) const
virtual std::optional< size_t > dtls_maximum_hello_verify_requests() const
virtual bool only_resume_with_exact_version() const
virtual bool acceptable_protocol_version(Protocol_Version version) const
virtual size_t remove(const Session_Handle &handle)=0
virtual void store(const Session &session, const Session_Handle &handle)=0
Save a Session under a Session_Handle (TLS Client).
std::vector< AlgorithmIdentifier > to_algorithm_identifiers(const std::vector< Signature_Scheme > &schemes)
std::vector< std::string > filter_signature_schemes(const std::vector< Signature_Scheme > &schemes, const Protocol_Version &version)
bool value_exists(const std::vector< T > &vec, const V &val)
std::vector< T, secure_allocator< T > > secure_vector