94#include <botan/internal/tls_cipher_state.h>
96#include <botan/aead.h>
97#include <botan/assert.h>
98#include <botan/hash.h>
99#include <botan/secmem.h>
100#include <botan/tls_ciphersuite.h>
101#include <botan/tls_exceptn.h>
102#include <botan/tls_magic.h>
104#include <botan/mem_ops.h>
105#include <botan/internal/concat_util.h>
106#include <botan/internal/fmt.h>
107#include <botan/internal/hkdf.h>
108#include <botan/internal/hmac.h>
109#include <botan/internal/int_utils.h>
110#include <botan/internal/loadstor.h>
111#include <botan/internal/mem_utils.h>
112#include <botan/internal/stl_util.h>
113#include <botan/internal/tls_channel_impl_13.h>
119 throw Not_Implemented(
"DTLS 1.3 is not yet supported");
121 return std::make_unique<TLS_Cipher_State>(side, prf_algo);
127std::unique_ptr<MessageAuthenticationCode> create_hmac(std::string_view hash) {
134 std::string_view hash_function,
136 m_state(State::Uninitialized),
137 m_connection_side(whoami),
138 m_extract(std::make_unique<
HKDF_Extract>(create_hmac(hash_function))),
139 m_expand(std::make_unique<
HKDF_Expand>(create_hmac(hash_function))),
141 m_expansion_label_prefix(expansion_label_prefix),
142 m_salt(m_hash->output_length(), 0x00),
153 auto cs = Cipher_State::create(side, flavor, cipher.
prf_algo());
154 cs->set_secret_logger(std::move(secret_logger));
155 cs->advance_without_psk();
156 cs->advance_with_server_hello(cipher, std::move(shared_secret), transcript_hash);
164 std::string_view prf_algo) {
165 auto cs = Cipher_State::create(side, flavor, prf_algo);
166 cs->advance_with_psk(type, std::move(
psk));
181 m_exporter_master_secret = derive_secret(m_early_secret,
"e exp master", transcript_hash);
187 maybe_log_secret(
"EARLY_EXPORTER_MASTER_SECRET", m_exporter_master_secret);
189 m_salt = derive_secret(m_early_secret,
"derived", empty_hash());
192 m_state = State::EarlyTraffic;
204 m_client_application_traffic_secret_0 = derive_secret(master_secret,
"c ap traffic", transcript_hash);
205 auto server_application_traffic_secret = derive_secret(master_secret,
"s ap traffic", transcript_hash);
211 maybe_log_secret(
"CLIENT_TRAFFIC_SECRET_0", m_client_application_traffic_secret_0);
212 maybe_log_secret(
"SERVER_TRAFFIC_SECRET_0", server_application_traffic_secret);
223 m_exporter_master_secret = derive_secret(master_secret,
"exp master", transcript_hash);
229 maybe_log_secret(
"EXPORTER_SECRET", m_exporter_master_secret);
231 m_state = State::ServerApplicationTraffic;
249 zap(m_client_application_traffic_secret_0);
253 m_resumption_master_secret = derive_secret(master_secret,
"res master", transcript_hash);
258 m_state = State::Completed;
297 (m_state == State::HandshakeTraffic || m_state == State::ServerApplicationTraffic)) {
313 m_state != State::Completed) {
325 m_state != State::Completed) {
338 return m_hash->name();
354 const auto our_aead_name = [&]() -> std::optional<std::string> {
370 if(our_aead_name.has_value()) {
372 if(!ciphersuite_aead || ciphersuite_aead->name() != *our_aead_name) {
381 const Transcript_Hash& transcript_hash_with_truncated_client_hello)
const {
385 auto hmac =
HMAC(m_hash->new_object());
386 hmac.set_key(m_binder_key);
387 hmac.update(transcript_hash_with_truncated_client_hello);
388 return hmac.final_stdvec();
399 auto hmac =
HMAC(m_hash->new_object());
400 hmac.set_key(*epoch.finished_key);
401 hmac.update(transcript_hash);
402 return hmac.final_stdvec();
406 const std::vector<uint8_t>& peer_mac)
const {
414 auto hmac =
HMAC(m_hash->new_object());
415 hmac.set_key(*epoch.finished_key);
416 hmac.update(transcript_hash);
417 return hmac.verify_mac(peer_mac);
423 return derive_secret(m_resumption_master_secret,
"resumption", nonce.
get());
428 if(m_ticket_nonce_exhausted) {
434 if(m_ticket_nonce == std::numeric_limits<
decltype(m_ticket_nonce)>::max()) {
435 m_ticket_nonce_exhausted =
true;
447 m_hash->update(context);
448 const auto context_hash = m_hash->final_stdvec();
450 derive_secret(m_exporter_master_secret, label, empty_hash()),
"exporter", context_hash, length);
463constexpr size_t NONCE_LENGTH = 12;
465std::array<uint8_t, NONCE_LENGTH> current_nonce(
const uint64_t seq_no, std::span<const uint8_t> iv) {
474 std::array<uint8_t, NONCE_LENGTH> nonce{};
475 store_be(std::span{nonce}.last<
sizeof(seq_no)>(), seq_no);
487 constexpr size_t content_type_tag_length = 1;
489 const size_t plaintext_length = payload_length + content_type_tag_length + padding_bytes;
490 return epoch.
cipher->output_length(plaintext_length);
494 std::span<const uint8_t> header,
495 std::span<const uint8_t> payload,
497 size_t padding_bytes,
501 const size_t record_offset = out.size();
502 const size_t content_offset = record_offset + header.size();
504 out.reserve(record_offset + record_length);
522 out.resize(content_offset + payload.size() + 1 + padding_bytes);
523 copy_mem(std::span{out}.subspan(record_offset, header.size()), header);
524 copy_mem(std::span{out}.subspan(content_offset, payload.size()), payload);
529 epoch.
cipher->set_associated_data(header);
531 epoch.
cipher->finish(out, content_offset);
536 std::span<const uint8_t> header,
538 size_t incoming_record_size_limit)
const {
543 epoch.
cipher->set_associated_data(header);
555 if(protected_record.
payload.size() > incoming_record_size_limit) {
556 throw TLS_Exception(Alert::RecordOverflow,
"Received an encrypted record that exceeds maximum plaintext size");
568 const auto end_of_content = std::find_if(
569 protected_record.
payload.crbegin(), protected_record.
payload.crend(), [](uint8_t b) { return b != 0x00; });
575 if(end_of_content == protected_record.
payload.crend()) {
576 throw TLS_Exception(Alert::UnexpectedMessage,
"No content type found in encrypted record");
586 std::distance(protected_record.
payload.crbegin(), end_of_content) -
597 throw TLS_Exception(Alert::UnexpectedMessage,
"Application data received before handshake completion");
606 throw TLS_Exception(Alert::UnexpectedMessage,
"Received a protected record with empty TLSInnerPlaintext content");
610void Cipher_State::advance_without_psk() {
617 m_salt = derive_secret(early_secret,
"derived", empty_hash());
620 m_state = State::EarlyTraffic;
627 m_early_secret = hkdf_extract(std::move(
psk));
630 const char* binder_label = [type]() ->
const char* {
648 const auto binder_key = derive_secret(m_early_secret, binder_label, empty_hash());
649 m_binder_key =
hkdf_expand_label(binder_key,
"finished", {}, m_hash->output_length());
653 m_state = State::PskBinder;
663 m_ciphersuite = cipher;
665 const auto handshake_secret = hkdf_extract(std::move(shared_secret));
667 const auto client_handshake_traffic_secret = derive_secret(handshake_secret,
"c hs traffic", transcript_hash);
668 const auto server_handshake_traffic_secret = derive_secret(handshake_secret,
"s hs traffic", transcript_hash);
674 maybe_log_secret(
"CLIENT_HANDSHAKE_TRAFFIC_SECRET", client_handshake_traffic_secret);
675 maybe_log_secret(
"SERVER_HANDSHAKE_TRAFFIC_SECRET", server_handshake_traffic_secret);
685 m_salt = derive_secret(handshake_secret,
"derived", empty_hash());
687 m_state = State::HandshakeTraffic;
692 bool handshake_epoch)
const {
697 .cipher = [&]() -> std::unique_ptr<AEAD_Mode> {
699 cipher->set_key(
hkdf_expand_label(traffic_secret,
"key", {}, cipher->minimum_keylength()));
703 .sequence_number = 0,
704 .traffic_secret = traffic_secret,
705 .finished_key = [&]() -> std::optional<secure_vector<uint8_t>> {
706 if(handshake_epoch) {
709 return hkdf_expand_label(traffic_secret,
"finished", {}, m_hash->output_length());
718 return *m_ciphersuite;
724 return m_extract->derive_key(m_hash->output_length(), ikm, m_salt, std::vector<uint8_t>());
728 std::string_view label,
729 const std::vector<uint8_t>& context,
730 const size_t length)
const {
732 BOTAN_ARG_CHECK(length <= std::numeric_limits<uint16_t>::max(),
"invalid length");
734 BOTAN_ARG_CHECK(m_expansion_label_prefix.size() + label.size() <= 255,
"label too large");
736 const auto hkdf_label =
738 store_be(
static_cast<uint8_t
>(m_expansion_label_prefix.size() + label.size())),
739 m_expansion_label_prefix,
741 store_be(
static_cast<uint8_t
>(context.size())),
745 return m_expand->derive_key(
746 length, secret, hkdf_label, std::vector<uint8_t>() );
750 std::string_view label,
756std::vector<uint8_t> Cipher_State::empty_hash()
const {
759 return m_hash->final_stdvec();
763 BOTAN_ASSERT_NOMSG(m_state == State::ServerApplicationTraffic || m_state == State::Completed);
768 const auto new_read_application_traffic_secret =
769 hkdf_expand_label(epoch.traffic_secret,
"traffic upd", {}, m_hash->output_length());
771 const auto secret_label =
fmt(
"{}_TRAFFIC_SECRET_{}",
773 ++m_read_key_update_count);
776 maybe_log_secret(secret_label, new_read_application_traffic_secret);
780 BOTAN_ASSERT_NOMSG(m_state == State::ServerApplicationTraffic || m_state == State::Completed);
785 const auto new_write_application_traffic_secret =
786 hkdf_expand_label(epoch.traffic_secret,
"traffic upd", {}, m_hash->output_length());
788 const auto secret_label =
fmt(
"{}_TRAFFIC_SECRET_{}",
790 ++m_write_key_update_count);
795 maybe_log_secret(secret_label, new_write_application_traffic_secret);
807 Cipher_State(side, prf_algo, {
't',
'l',
's',
'1',
'3',
' '} ) {}
812 std::span<const uint8_t> plaintext,
813 size_t padding_bytes,
817 "Application data must not be encrypted before handshake completion");
821 if(m_write_epoch->sequence_number == std::numeric_limits<uint64_t>::max()) {
838 Protocol_Version::TLS_V12 ,
842 ++m_write_epoch->sequence_number;
859 if(record.
payload().size() < m_read_epoch->cipher->minimum_final_size()) {
860 throw TLS_Exception(Alert::BadRecordMac,
"incomplete record mac received");
872 throw TLS_Exception(Alert::RecordOverflow,
"Received an encrypted record that exceeds maximum plaintext size");
877 if(m_read_epoch->sequence_number == std::numeric_limits<uint64_t>::max()) {
883 .sequence_number = m_read_epoch->sequence_number++,
908 throw TLS_Exception(Alert::UnexpectedMessage,
"protected TLS record type had unexpected value");
914void TLS_Cipher_State::advance_write_epoch(
const secure_vector<uint8_t>& traffic_secret,
bool handshake_epoch) {
918void TLS_Cipher_State::advance_read_epoch(
const secure_vector<uint8_t>& traffic_secret,
bool handshake_epoch) {
923 m_write_epoch.reset();
927 m_read_epoch.reset();
#define BOTAN_ASSERT_NOMSG(expr)
#define BOTAN_DEBUG_ASSERT(expr)
#define BOTAN_STATE_CHECK(expr)
#define BOTAN_ASSERT_NONNULL(ptr)
#define BOTAN_ARG_CHECK(expr, msg)
#define BOTAN_STATE_CHECK_MSG(expr, msg)
#define BOTAN_ASSERT_UNREACHABLE()
static std::unique_ptr< AEAD_Mode > create_or_throw(std::string_view algo, Cipher_Dir direction, std::string_view provider="")
static std::unique_ptr< AEAD_Mode > create(std::string_view algo, Cipher_Dir direction, std::string_view provider="")
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
bool can_decrypt_application_traffic() const
uint64_t records_encrypted_with_current_key() const
static size_t protected_record_length(Epoch &epoch, size_t payload_length, size_t padding_bytes)
static std::unique_ptr< Cipher_State > init_with_psk(Connection_Side side, TLS_Flavor flavor, PSK_Type type, secure_vector< uint8_t > &&psk, std::string_view prf_algo)
bool can_export_keys() const
const Ciphersuite & ciphersuite() const
virtual Epoch & latest_write_epoch()=0
void advance_with_client_hello(const Transcript_Hash &transcript_hash)
size_t minimum_decryption_input_length() const
virtual bool has_read_epoch() const =0
void advance_with_server_finished(const Transcript_Hash &transcript_hash)
virtual void advance_read_epoch(const secure_vector< uint8_t > &traffic_secret, bool handshake_epoch=false)=0
secure_vector< uint8_t > hkdf_expand_label(const secure_vector< uint8_t > &secret, std::string_view label, const std::vector< uint8_t > &context, size_t length) const
bool must_expect_unprotected_alert_traffic() const
void advance_with_client_finished(const Transcript_Hash &transcript_hash)
bool verify_peer_finished_mac(const Transcript_Hash &transcript_hash, const std::vector< uint8_t > &peer_mac) const
std::string hash_algorithm() const
void deprotect_and_hydrate_content_type(Epoch &epoch, std::span< const uint8_t > header, Record_Content &protected_record, size_t incoming_record_size_limit) const
Cipher_State(const Cipher_State &other)=delete
secure_vector< uint8_t > psk(const Ticket_Nonce &nonce) const
void advance_with_server_hello(const Ciphersuite &cipher, secure_vector< uint8_t > &&shared_secret, const Transcript_Hash &transcript_hash)
bool is_compatible_with(const Ciphersuite &cipher) const
secure_vector< uint8_t > export_key(std::string_view label, std::string_view context, size_t length) const
virtual void advance_write_epoch(const secure_vector< uint8_t > &traffic_secret, bool handshake_epoch=false)=0
bool can_encrypt_application_traffic() const
size_t encrypt_output_length(size_t input_length) const
static std::unique_ptr< Cipher_State > init_with_server_hello(Connection_Side side, TLS_Flavor flavor, secure_vector< uint8_t > &&shared_secret, const Ciphersuite &cipher, const Transcript_Hash &transcript_hash, SecretLoggerFn secret_logger)
std::vector< uint8_t > psk_binder_mac(const Transcript_Hash &transcript_hash_with_truncated_client_hello) const
size_t decrypt_output_length(size_t input_length) const
static void marshall_and_protect(Epoch &epoch, std::span< const uint8_t > header, std::span< const uint8_t > payload, Record_Type type, size_t padding_bytes, secure_vector< uint8_t > &out)
Cipher_State::Epoch create_epoch(Cipher_Dir direction, const secure_vector< uint8_t > &traffic_secret, bool handshake_epoch) const
std::array< uint8_t, 6 > ExpansionLabelPrefix
Ticket_Nonce next_ticket_nonce()
uint64_t records_decrypted_with_current_key() const
virtual bool has_write_epoch() const =0
std::vector< uint8_t > finished_mac(const Transcript_Hash &transcript_hash) const
virtual Epoch & latest_read_epoch()=0
bool usable_in_version(Protocol_Version version) const
std::string prf_algo() const
std::string cipher_algo() const
secure_vector< uint8_t > take_payload()
std::span< uint8_t, TLS_HEADER_SIZE > header()
static std::array< uint8_t, TLS_HEADER_SIZE > serialize_header(Record_Type type, Protocol_Version legacy_version, uint16_t payload_length)
std::span< const uint8_t > payload() const
Record deprotect_record(Record_TLS record, size_t incoming_record_size_limit)
~TLS_Cipher_State() override
TLS_Cipher_State(Connection_Side side, std::string_view prf_algo)
void clear_read_keys() override
void clear_write_keys() override
void protect_record(Record_Type type, std::span< const uint8_t > payload, size_t padding_bytes, secure_vector< uint8_t > &out)
std::variant< ChangeCipherSpec_Record, Alert_Record, Handshake_Record, ApplicationData_Record > Record
std::vector< uint8_t > Transcript_Hash
@ MAX_CIPHERTEXT_SIZE_TLS13
Strong< std::vector< uint8_t >, struct Ticket_Nonce_ > Ticket_Nonce
Used to derive the ticket's PSK from the resumption_master_secret.
std::function< void(std::string_view label, std::span< const uint8_t > secret)> SecretLoggerFn
Record annotate_record_type(Record_Content &&record)
std::span< const uint8_t > as_span_of_bytes(const char *s, size_t len)
void zap(std::vector< T, Alloc > &vec)
std::string fmt(std::string_view format, const T &... args)
auto to_underlying(T e) noexcept
constexpr RT checked_cast_to(AT i)
constexpr void copy_mem(T *out, const T *in, size_t n)
constexpr auto concat(Rs &&... ranges)
constexpr void xor_buf(ranges::contiguous_output_range< uint8_t > auto &&out, ranges::contiguous_range< uint8_t > auto &&in)
std::vector< T, secure_allocator< T > > secure_vector
constexpr auto store_be(ParamTs &&... params)
std::unique_ptr< AEAD_Mode > cipher
secure_vector< uint8_t > iv
secure_vector< uint8_t > payload
std::optional< uint64_t > sequence_number