Botan 3.14.1
Crypto and TLS for C&
tls_cipher_state.h
Go to the documentation of this file.
1/*
2* TLS cipher state implementation for TLS 1.3
3* (C) 2022 Jack Lloyd
4* 2022 Hannes Rantzsch, René Meusel - neXenio GmbH
5* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#ifndef BOTAN_TLS_CIPHER_STATE_H_
11#define BOTAN_TLS_CIPHER_STATE_H_
12
13#include <botan/assert.h>
14#include <botan/cipher_mode.h>
15#include <botan/secmem.h>
16#include <botan/tls_ciphersuite.h>
17#include <botan/tls_magic.h>
18
19#include <botan/internal/tls_record_13.h>
20#include <botan/internal/tls_transcript_hash_13.h>
21#include <botan/internal/tls_types_13.h>
22
23#include <optional>
24
25namespace Botan {
26
27class AEAD_Mode;
28class HashFunction;
29class HKDF_Extract;
30class HKDF_Expand;
31
32} // namespace Botan
33
34namespace Botan::TLS {
35
36class Ciphersuite;
37
38/**
39 * This class implements the key schedule for (D)TLS 1.3 as described in RFC 9846 7.1.
40 *
41 * Internally, it reflects the state machine pictured in the same RFC section.
42 * It provides the following entry points and state advancement methods that
43 * each facilitate certain cryptographic functionality:
44 *
45 * * init_with_psk()
46 * sets up the cipher state with a pre-shared key (out of band or via session
47 * ticket). will allow sending early data in the future
48 *
49 * * init_with_server_hello() / advance_with_server_hello()
50 * allows encrypting and decrypting handshake traffic, as well as producing
51 * and validating the client/server handshake finished MACs
52 *
53 * * advance_with_server_finished()
54 * allows encrypting and decrypting application traffic
55 *
56 * * advance_with_client_finished()
57 * allows negotiation of resumption PSKs
58 *
59 * This is an abstract base class that implements the key schedule and leaves
60 * the management of the resulting traffic epochs (as well as record
61 * protection) to concrete subclasses for TLS and DTLS.
62 *
63 * While encrypting and decrypting records (RFC 9846 5.2) the concrete
64 * subclasses internally keep track of the current sequence numbers
65 * (RFC 9846 5.3) to calculate the correct Per-Record Nonce. Sequence numbers
66 * are reset appropriately, whenever traffic secrets change.
67 *
68 * Handshake finished MAC calculation and verification is described in RFC 9846 4.5.3.
69 * PSKs calculation is described in RFC 9846 4.7.1
70 */
72 public:
73 enum class PSK_Type : uint8_t {
74 Resumption, // RFC 8446
75 External, // RFC 8446
76 Imported, // RFC 9258 PSK importer - uses "imp binder" label
77 };
78
79 public:
80 /**
81 * The cryptographic state required to protect or deprotect records in
82 * one direction. Concrete subclasses manage the available epochs, e.g.
83 * a single current epoch per direction for TLS 1.3.
84 */
85 struct Epoch {
86 std::unique_ptr<AEAD_Mode> cipher;
89
91
92 /// only relevant in the handshake traffic epoch to
93 /// calculate and verify the handshake's Finished MACs
94 std::optional<secure_vector<uint8_t>> finished_key;
95 };
96
97 using ExpansionLabelPrefix = std::array<uint8_t, 6>;
98
99 private:
100 static std::unique_ptr<Cipher_State> create(Connection_Side side, TLS_Flavor flavor, std::string_view prf_algo);
101
102 public:
103 virtual ~Cipher_State();
104
105 Cipher_State(const Cipher_State& other) = delete;
106 Cipher_State(Cipher_State&& other) = delete;
107 Cipher_State& operator=(const Cipher_State& other) = delete;
109
110 /**
111 * Construct a Cipher_State from a Pre-Shared-Key.
112 */
113 static std::unique_ptr<Cipher_State> init_with_psk(Connection_Side side,
114 TLS_Flavor flavor,
115 PSK_Type type,
117 std::string_view prf_algo);
118
119 /**
120 * Construct a Cipher_State after receiving a server hello message.
121 */
122 static std::unique_ptr<Cipher_State> init_with_server_hello(Connection_Side side,
123 TLS_Flavor flavor,
124 secure_vector<uint8_t>&& shared_secret,
125 const Ciphersuite& cipher,
126 const Transcript_Hash& transcript_hash,
127 SecretLoggerFn secret_logger);
128
129 /**
130 * Transition internal secrets/keys for transporting early application data.
131 * Note that this state transition is legal only for handshakes using PSK.
132 */
133 void advance_with_client_hello(const Transcript_Hash& transcript_hash);
134
135 /**
136 * Transition internal secrets/keys for transporting handshake data.
137 */
138 void advance_with_server_hello(const Ciphersuite& cipher,
139 secure_vector<uint8_t>&& shared_secret,
140 const Transcript_Hash& transcript_hash);
141
142 /**
143 * Transition internal secrets/keys for transporting application data.
144 */
145 void advance_with_server_finished(const Transcript_Hash& transcript_hash);
146
147 /**
148 * Transition to the final internal state allowing to create resumptions.
149 */
150 void advance_with_client_finished(const Transcript_Hash& transcript_hash);
151
152 /**
153 * @returns number of bytes needed to encrypt \p input_length bytes
154 */
155 size_t encrypt_output_length(size_t input_length) const;
156
157 /**
158 * @returns number of bytes needed to decrypt \p input_length bytes
159 */
160 size_t decrypt_output_length(size_t input_length) const;
161
162 /**
163 * @returns the minimum ciphertext length for decryption
164 */
165 size_t minimum_decryption_input_length() const;
166
167 /**
168 * Calculates the MAC for a PSK binder value in Client Hellos. Note that
169 * the transcript hash passed into this method is computed from a partial
170 * Client Hello (RFC 8446 4.2.11.2)
171 */
172 std::vector<uint8_t> psk_binder_mac(const Transcript_Hash& transcript_hash_with_truncated_client_hello) const;
173
174 /**
175 * Calculate the MAC for a TLS "Finished" handshake message (RFC 8446 4.4.4)
176 */
177 std::vector<uint8_t> finished_mac(const Transcript_Hash& transcript_hash) const;
178
179 /**
180 * Validate a MAC received in a TLS "Finished" handshake message (RFC 8446 4.4.4)
181 */
182 bool verify_peer_finished_mac(const Transcript_Hash& transcript_hash, const std::vector<uint8_t>& peer_mac) const;
183
184 /**
185 * Calculate the PSK for the given nonce (RFC 8446 4.6.1)
186 */
187 secure_vector<uint8_t> psk(const Ticket_Nonce& nonce) const;
188
189 /**
190 * Generates a nonce value that is unique for any given Cipher_State object.
191 * Note that the number of nonces is limited to 2^16 and this method will
192 * throw if more nonces are requested.
193 */
195
196 /**
197 * Derive key material to export (RFC 8446 7.5 and RFC 5705)
198 *
199 * TODO: this does not yet support key export based on the `early_exporter_master_secret`.
200 *
201 * RFC 8446 7.5
202 * Implementations MUST use the exporter_master_secret unless explicitly
203 * specified by the application. The early_exporter_master_secret is
204 * defined for use in settings where an exporter is needed for 0-RTT data.
205 * A separate interface for the early exporter is RECOMMENDED [...].
206 *
207 * @param label a disambiguating label string
208 * @param context a per-association context value
209 * @param length the length of the desired key in bytes
210 * @return key of length bytes
211 */
212 secure_vector<uint8_t> export_key(std::string_view label, std::string_view context, size_t length) const;
213
214 /**
215 * Indicates whether the appropriate secrets to export keys are available
216 */
217 bool can_export_keys() const {
218 return (m_state == State::EarlyTraffic || m_state == State::ServerApplicationTraffic ||
219 m_state == State::Completed) &&
220 !m_exporter_master_secret.empty();
221 }
222
223 /**
224 * Indicates whether both peers' Finished messages were processed, i.e.
225 * the key schedule reached its final state.
226 */
227 bool is_handshake_complete() const { return m_state == State::Completed; }
228
229 /**
230 * Indicates whether unprotected Alert records are to be expected
231 */
232 bool must_expect_unprotected_alert_traffic() const;
233
234 /**
235 * Indicates whether the appropriate secrets to encrypt application traffic are available
236 */
237 bool can_encrypt_application_traffic() const;
238
239 /**
240 * Indicates whether the appropriate secrets to decrypt application traffic are available
241 */
242 bool can_decrypt_application_traffic() const;
243
244 /**
245 * The name of the hash algorithm used for the KDF in this cipher suite
246 */
247 std::string hash_algorithm() const;
248
249 /**
250 * @returns true if the selected cipher primitives are compatible with
251 * the \p cipher suite.
252 *
253 * Note that cipher suites are considered "compatible" as long as the
254 * already selected cipher primitives in this cipher state are compatible.
255 */
256 bool is_compatible_with(const Ciphersuite& cipher) const;
257
258 /**
259 * Updates the key material used for decrypting data
260 * This is triggered after we received a Key_Update from the peer.
261 *
262 * Note that this must not be called before the connection is ready for
263 * application traffic.
264 */
265 void update_read_keys();
266
267 /**
268 * Updates the key material used for encrypting data
269 * This is triggered after we send a Key_Update to the peer.
270 *
271 * Note that this must not be called before the connection is ready for
272 * application traffic.
273 */
274 void update_write_keys();
275
276 /**
277 * @returns the number of records encrypted with the current write key
278 */
279 uint64_t records_encrypted_with_current_key() const;
280
281 /**
282 * @returns the number of records decrypted with the current read key
283 */
284 uint64_t records_decrypted_with_current_key() const;
285
286 /**
287 * Remove handshake/traffic secrets for decrypting data from peer
288 */
289 virtual void clear_read_keys() = 0;
290
291 /**
292 * Remove handshake/traffic secrets for encrypting data
293 */
294 virtual void clear_write_keys() = 0;
295
296 /**
297 * Register an optional callback function to extract secrets bound for a
298 * SSLKEYLOGFILE. See SSLKEYLOGFILE RFC 9850 for details.
299 */
300 void set_secret_logger(SecretLoggerFn secret_logger) { m_secret_logger = std::move(secret_logger); }
301
302 private:
303 void advance_with_psk(PSK_Type type, secure_vector<uint8_t>&& psk);
304 void advance_without_psk();
305
306 /**
307 * HKDF-Extract from RFC 8446 7.1
308 */
309 secure_vector<uint8_t> hkdf_extract(std::span<const uint8_t> ikm) const;
310
311 /**
312 * Derive-Secret from RFC 8446 7.1
313 */
314 secure_vector<uint8_t> derive_secret(const secure_vector<uint8_t>& secret,
315 std::string_view label,
316 const Transcript_Hash& messages_hash) const;
317
318 void maybe_log_secret(std::string_view label, std::span<const uint8_t> secret) const {
319 if(m_secret_logger) {
320 m_secret_logger(label, secret);
321 }
322 }
323
324 std::vector<uint8_t> empty_hash() const;
325
326 protected:
327 /**
328 * @param whoami whether we play the Server or Client
329 * @param hash_function the negotiated hash function to be used
330 * @param expand_prefix the prefix to be used for HKDF-Expand-Label
331 */
332 Cipher_State(Connection_Side whoami, std::string_view hash_function, ExpansionLabelPrefix expand_prefix);
333
334 static size_t protected_record_length(Epoch& epoch, size_t payload_length, size_t padding_bytes);
335
336 /**
337 * Marshalls the record (header || TLSInnerPlaintext), protects it in
338 * place and appends the result to @p out. The plaintext is copied into
339 * @p out exactly once; no intermediate buffers are allocated.
340 */
341 static void marshall_and_protect(Epoch& epoch,
342 std::span<const uint8_t> header,
343 std::span<const uint8_t> payload,
344 Record_Type type,
345 size_t padding_bytes,
346 secure_vector<uint8_t>& out);
347 void deprotect_and_hydrate_content_type(Epoch& epoch,
348 std::span<const uint8_t> header,
349 Record_Content& protected_record,
350 size_t incoming_record_size_limit) const;
351
352 /**
353 * HKDF-Expand-Label from RFC 8446 7.1
354 */
355 secure_vector<uint8_t> hkdf_expand_label(const secure_vector<uint8_t>& secret,
356 std::string_view label,
357 const std::vector<uint8_t>& context,
358 size_t length) const;
359
360 Cipher_State::Epoch create_epoch(Cipher_Dir direction,
361 const secure_vector<uint8_t>& traffic_secret,
362 bool handshake_epoch) const;
363
364 const Ciphersuite& ciphersuite() const;
365
366 virtual void advance_write_epoch(const secure_vector<uint8_t>& traffic_secret, bool handshake_epoch = false) = 0;
367 virtual void advance_read_epoch(const secure_vector<uint8_t>& traffic_secret, bool handshake_epoch = false) = 0;
368
369 virtual bool has_write_epoch() const = 0;
370 virtual bool has_read_epoch() const = 0;
371 virtual Epoch& latest_write_epoch() = 0;
372 virtual const Epoch& latest_write_epoch() const = 0;
373 virtual Epoch& latest_read_epoch() = 0;
374 virtual const Epoch& latest_read_epoch() const = 0;
375
376 private:
377 enum class State : uint8_t {
378 Uninitialized,
379 PskBinder,
380 EarlyTraffic,
381 HandshakeTraffic,
382 ServerApplicationTraffic,
383 Completed
384 };
385
386 private:
387 State m_state;
388 Connection_Side m_connection_side;
389 std::optional<Ciphersuite> m_ciphersuite;
390 SecretLoggerFn m_secret_logger;
391
392 std::unique_ptr<HKDF_Extract> m_extract;
393 std::unique_ptr<HKDF_Expand> m_expand;
394 std::unique_ptr<HashFunction> m_hash;
395
396 ExpansionLabelPrefix m_expansion_label_prefix;
398 secure_vector<uint8_t> m_client_application_traffic_secret_0;
399
400 uint32_t m_write_key_update_count = 0;
401 uint32_t m_read_key_update_count = 0;
402
403 uint16_t m_ticket_nonce;
404 bool m_ticket_nonce_exhausted = false;
405
406 secure_vector<uint8_t> m_exporter_master_secret;
407 secure_vector<uint8_t> m_resumption_master_secret;
408
409 secure_vector<uint8_t> m_early_secret;
410 secure_vector<uint8_t> m_binder_key;
411};
412
413/**
414 * Cipher State implementation for TLS 1.3 (RFC 9846).
415 *
416 * This re-uses the key schedule implementation in the Cipher_State base class
417 * and implements record (de)protection and epoch management for TLS 1.3. Epochs
418 * in TLS 1.3 are simply rolled over whenever necessary. No historic epochs are
419 * kept.
420 */
422 public:
423 TLS_Cipher_State(Connection_Side side, std::string_view prf_algo);
424
430
431 /**
432 * Protect a TLS record (RFC 9846 5.2 -- TLSInnerPlaintext) using the
433 * currently available traffic secret keys and the current sequence
434 * number. This will internally increment the sequence number. Hence,
435 * multiple calls with the same input will not produce the same result.
436 *
437 * @param type the record type to be protected
438 * @param payload the record plaintext to be protected
439 * @param padding_bytes the number of padding zero-bytes to be added
440 * @param out the marshalled and protected record (to be sent
441 * on the wire) is appended to this buffer
442 */
443 void protect_record(Record_Type type,
444 std::span<const uint8_t> payload,
445 size_t padding_bytes,
447
448 /**
449 * Deprotect a TLS record (RFC 9846 5.2 -- TLSCiphertext.encrypted_record)
450 * using the currently available traffic secret keys and the current
451 * sequence number. This will internally increment the sequence number.
452 * Hence, multiple calls with the same input will not produce the same
453 * result.
454 *
455 * @param record the record to be deprotected in-place
456 * @param incoming_record_size_limit the maximum allowed size for the incoming record
457 *
458 * @returns the record payload and deprotected content type
459 */
460 [[nodiscard]] Record deprotect_record(Record_TLS record, size_t incoming_record_size_limit);
461
462 void clear_write_keys() override;
463
464 void clear_read_keys() override;
465
466 private:
467 void advance_write_epoch(const secure_vector<uint8_t>& traffic_secret, bool handshake_epoch = false) override;
468 void advance_read_epoch(const secure_vector<uint8_t>& traffic_secret, bool handshake_epoch = false) override;
469
470 bool has_write_epoch() const override { return m_write_epoch.has_value(); }
471
472 bool has_read_epoch() const override { return m_read_epoch.has_value(); }
473
474 Epoch& latest_write_epoch() override {
475 BOTAN_STATE_CHECK(has_write_epoch());
476 return *m_write_epoch;
477 }
478
479 const Epoch& latest_write_epoch() const override {
480 BOTAN_STATE_CHECK(has_write_epoch());
481 return *m_write_epoch;
482 }
483
484 Epoch& latest_read_epoch() override {
485 BOTAN_STATE_CHECK(has_read_epoch());
486 return *m_read_epoch;
487 }
488
489 const Epoch& latest_read_epoch() const override {
490 BOTAN_STATE_CHECK(has_read_epoch());
491 return *m_read_epoch;
492 }
493
494 private:
495 std::optional<Epoch> m_write_epoch;
496 std::optional<Epoch> m_read_epoch;
497};
498
500 auto* tls_cs = dynamic_cast<TLS_Cipher_State*>(cs);
502 tls_cs == nullptr, cs == nullptr, "If the cipher state is not a TLS_Cipher_State, it must be null");
503 return tls_cs;
504}
505
506} // namespace Botan::TLS
507
508#endif // BOTAN_TLS_CIPHER_STATE_H_
#define BOTAN_TEST_API
Definition api.h:41
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:108
virtual const Epoch & latest_write_epoch() const =0
void set_secret_logger(SecretLoggerFn secret_logger)
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)
virtual Epoch & latest_write_epoch()=0
Cipher_State & operator=(Cipher_State &&other)=delete
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
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
virtual void clear_read_keys()=0
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)
secure_vector< uint8_t > export_key(std::string_view label, std::string_view context, size_t length) const
virtual const Epoch & latest_read_epoch() const =0
virtual void advance_write_epoch(const secure_vector< uint8_t > &traffic_secret, bool handshake_epoch=false)=0
Cipher_State(Cipher_State &&other)=delete
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
Cipher_State & operator=(const Cipher_State &other)=delete
std::array< uint8_t, 6 > ExpansionLabelPrefix
virtual void clear_write_keys()=0
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
Record deprotect_record(Record_TLS record, size_t incoming_record_size_limit)
TLS_Cipher_State(TLS_Cipher_State &&)=delete
TLS_Cipher_State(const TLS_Cipher_State &)=delete
TLS_Cipher_State(Connection_Side side, std::string_view prf_algo)
TLS_Cipher_State & operator=(const TLS_Cipher_State &)=delete
void protect_record(Record_Type type, std::span< const uint8_t > payload, size_t padding_bytes, secure_vector< uint8_t > &out)
TLS_Cipher_State & operator=(TLS_Cipher_State &&)=delete
TLS_Cipher_State * as_tls_cipher_state(Cipher_State *cs)
std::variant< ChangeCipherSpec_Record, Alert_Record, Handshake_Record, ApplicationData_Record > Record
std::vector< uint8_t > Transcript_Hash
Definition tls_magic.h:105
Strong< std::vector< uint8_t >, struct Ticket_Nonce_ > Ticket_Nonce
Used to derive the ticket's PSK from the resumption_master_secret.
Definition tls_magic.h:108
std::function< void(std::string_view label, std::span< const uint8_t > secret)> SecretLoggerFn
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
std::unique_ptr< AEAD_Mode > cipher
std::optional< secure_vector< uint8_t > > finished_key
secure_vector< uint8_t > traffic_secret
secure_vector< uint8_t > iv