Botan 3.14.1
Crypto and TLS for C&
tls_channel_io.cpp
Go to the documentation of this file.
1/*
2* TLS Channel I/O
3* (C) 2026 Jack Lloyd
4* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/tls_channel_io.h>
10
11#include <botan/tls_callbacks.h>
12#include <botan/tls_exceptn.h>
13#include <botan/tls_policy.h>
14#include <botan/internal/bit_ops.h>
15#include <botan/internal/buffer_slicer.h>
16#include <botan/internal/stl_util.h>
17#include <botan/internal/tls_cipher_state.h>
18#include <botan/internal/tls_handshake_layer_13.h>
19#include <botan/internal/tls_record_layer_13.h>
20#include <botan/internal/tls_transcript_hash_13.h>
21
22namespace Botan::TLS {
23
24std::optional<Channel_IO::ReceiveEvent> Channel_IO::next_pending_handshake_message(
25 std::optional<Transcript_Hash_State>& transcript_hash, bool handshake_complete) {
26 auto& hs_layer = handshake_layer();
27 auto& rec_layer = record_layer();
28
29 if(!handshake_complete) {
30 BOTAN_ASSERT_NOMSG(transcript_hash.has_value());
31 auto handshake_msg = hs_layer.next_message(policy(), *transcript_hash);
32 if(!handshake_msg.has_value()) {
33 return std::nullopt;
34 }
35
36 // RFC 9846 5.1
37 // Handshake messages MUST NOT span key changes. Implementations
38 // MUST verify that all messages immediately preceding a key change
39 // align with a record boundary; if not, then they MUST terminate the
40 // connection with an "unexpected_message" alert. Because the
41 // ClientHello, EndOfEarlyData, ServerHello, Finished, and KeyUpdate
42 // messages can immediately precede a key change, implementations
43 // MUST send these messages in alignment with a record boundary.
44 //
45 // Note: Hello_Retry_Request was added to the list below although it
46 // cannot immediately precede a key change. However, there cannot be
47 // any further sensible messages in the record after HRR.
48 //
49 // Note: Server_Hello_12 was deliberately not included in the check below
50 // because in TLS 1.2 Server Hello and other handshake messages can
51 // be legally coalesced in a single record.
52 //
54 Client_Hello_13 /*, EndOfEarlyData,*/,
57 Finished_13>(handshake_msg.value()) &&
58 hs_layer.has_pending_data()) {
59 throw Unexpected_Message("Unexpected additional handshake message data found in record");
60 }
61
62 // After the initial handshake message is received, the record
63 // layer must be more restrictive.
64 // See RFC 9846 5.1 regarding "legacy_record_version"
65 if(!m_first_message_delivered) {
66 rec_layer.disable_receiving_compat_mode();
67 m_first_message_delivered = true;
68 }
69
70 return std::move(handshake_msg).value();
71 } else {
72 auto post_handshake_msg = hs_layer.next_post_handshake_message(policy());
73 if(!post_handshake_msg.has_value()) {
74 return std::nullopt;
75 }
76
77 // make sure Key_Update appears only at the end of a record; see RFC
78 // 9846 5.1 description above
79 if(std::holds_alternative<Key_Update>(post_handshake_msg.value()) && hs_layer.has_pending_data()) {
80 throw Unexpected_Message("Unexpected additional post-handshake message data found in record");
81 }
82
83 return std::move(post_handshake_msg).value();
84 }
85}
86
87void Channel_IO::copy_data(std::span<const uint8_t> data) {
88 // RFC 9846 6.1
89 // Any data received after a closure alert has been received MUST
90 // be ignored.
91 if(m_closed_for_reading) {
92 return;
93 }
94
95 record_layer().copy_data(data);
96}
97
98Channel_IO::ReceiveEvent Channel_IO::next_pending_event(std::optional<Transcript_Hash_State>& transcript_hash,
99 bool handshake_complete) {
100 const auto cs = cipher_state();
101
102 while(true) {
103 // First we check if the handshake layer has any complete messages ready
104 // to be consumed by the channel. If yes, we return that message....
105 if(auto event = next_pending_handshake_message(transcript_hash, handshake_complete)) {
106 // Handshake messages can be directly consumed by the channel
107 return std::move(event).value();
108 }
109
110 // ... otherwise we check if the record layer has any complete records
111 // ready to be processed. If yes, we dispatch the record to the
112 // appropriate handler or return it to the channel (e.g. application data,
113 // alerts, etc.). If no complete record is available, we return a
114 // BytesNeeded event which indicates that no more events are available and
115 // the channel needs to wait for the application to provide more data.
116 auto res = std::visit( //
118 [](BytesNeeded bytes) -> std::optional<Channel_IO::ReceiveEvent> { return bytes; },
119 [&](const Handshake_Record& record) -> std::optional<Channel_IO::ReceiveEvent> {
120 process(record);
121 return std::nullopt; // continue looping, the handshake layer may have progressed...
122 },
123 [&](auto anything_else) -> std::optional<Channel_IO::ReceiveEvent> {
124 // RFC 8446 5.1
125 // Handshake messages MUST NOT be interleaved with other record types.
126 if(handshake_layer().has_pending_data()) {
127 throw Unexpected_Message("Expected remainder of a handshake message");
128 }
129 return anything_else;
130 },
131 },
132 record_layer().next_record(cs.get()));
133
134 if(res.has_value()) {
135 return std::move(res).value();
136 }
137 }
138}
139
140void Channel_IO::send(std::vector<Flight::Message> flight) {
141 send_flight(std::move(flight));
142}
143
144void Channel_IO::send(std::span<const uint8_t> payload) {
145 // RFC 9846 4.7.3
146 // If the request_update field [of a received KeyUpdate] is set to
147 // "update_requested", then the receiver MUST send a KeyUpdate of its own
148 // with request_update set to "update_not_requested" prior to sending its
149 // next Application Data record. This mechanism allows either side to
150 // force an update to the entire connection, but causes an implementation
151 // which receives multiple KeyUpdates while it is silent to respond with
152 // a single update.
153 if(m_key_update_reciprocation_pending) {
154 update_traffic_keys(false /* update_requested */);
155 m_key_update_reciprocation_pending = false;
156 } else if(needs_traffic_based_key_update()) {
157 // If approaching traffic limits request the peer update their own keys
158 // as well, unless an earlier request is still unanswered:
159 //
160 // RFC 9846 4.7.3
161 // Until receiving a subsequent KeyUpdate from the peer, the sender
162 // MUST NOT send another KeyUpdate with request_update set to
163 // "update_requested".
164 update_traffic_keys(!m_key_update_requested);
165 }
166
167 const auto cs = cipher_state();
169 send_data(Record_Type::ApplicationData, payload, cs.get());
170}
171
172/**
173 * RFC 9846 Section 5.5
174 * Implementations MUST either close the connection or do a key update as
175 * described in Section 4.7.3 prior to reaching these limits.
176 *
177 * [This is a SHOULD in RFC 8446]
178 *
179 * The ChaCha-based suites don't have any practical usage limit but we
180 * apply the limit for all suites for simplicity.
181 */
182bool Channel_IO::needs_traffic_based_key_update() const {
183 // RFC 9846 5.5
184 // There are cryptographic limits on the amount of plaintext which can be
185 // safely encrypted under a given set of keys. [...] Implementations MUST
186 // either close the connection or do a key update as described in Section
187 // 4.7.3 prior to reaching these limits.
188 //
189 // The ChaCha-based suites don't have any practical usage limit but we apply
190 // the limit for all suites for simplicity.
191 const uint64_t limit = policy().records_per_traffic_key();
192 const auto cs = cipher_state();
194
195 // Have to skip this if the handshake is not yet completed since we can't
196 // send a KeyUpdate in the (unlikely) case that the limit is hit with
197 // half-RTT data. If it is we just defer until the handshake completes.
198 if(limit == 0 || !cs->is_handshake_complete()) {
199 return false;
200 }
201
202 // If we half-closed the connection for writing, i.e. we cannot encrypt
203 // application traffic any longer, naturally, we won't need to update our
204 // traffic keys.
205 if(cs->can_encrypt_application_traffic() && cs->records_encrypted_with_current_key() >= limit) {
206 return true;
207 }
208
209 // For the read side all we can do is ask the peer to update its keys,
210 // and only if no earlier request is still outstanding. The threshold is
211 // set above the write-side limit so that a peer which tracks its own
212 // write limit will normally have rotated its keys already, avoiding a
213 // redundant key update crossing ours in flight.
214 //
215 // Note: if the peer half-closed their connection for writing, i.e we
216 // destroyed the receive traffic keys, there's no point in requesting a key
217 // update from them.
218 const uint64_t read_limit = limit + limit / 2;
219 return !m_key_update_requested && cs->can_decrypt_application_traffic() &&
220 cs->records_decrypted_with_current_key() >= read_limit;
221}
222
224 const auto cs = cipher_state();
226
227 // A non-requesting KeyUpdate received while our own request is outstanding
228 // is the reciprocation we solicited. It is exempt from rate limiting (and
229 // invisible to it), so that a peer whose own key update crossed ours in
230 // flight is not penalized for the resulting back to back KeyUpdates.
231 const bool solicited_reciprocation = m_key_update_requested && !key_update.expects_reciprocation();
232
233 if(const uint64_t min_interval = policy().minimum_key_update_interval_ms();
234 min_interval > 0 && !solicited_reciprocation) {
235 const uint64_t now = callbacks().tls_current_monotonic_clock_ms();
236
237 if(m_last_peer_key_update_ms != 0 && (now - m_last_peer_key_update_ms) < min_interval) {
238 throw TLS_Exception(Alert::UnexpectedMessage, "Peer is requesting KeyUpdates too frequently");
239 }
240
241 m_last_peer_key_update_ms = now;
242 }
243
244 cs->update_read_keys();
245
246 if(key_update.expects_reciprocation() && cs->can_encrypt_application_traffic()) {
247 // RFC 9846 4.7.3
248 // If the request_update field is set to "update_requested", then the
249 // receiver MUST send a KeyUpdate of its own with request_update set to
250 // "update_not_requested" prior to sending its next Application Data
251 // record.
252 //
253 // This happens opportunistically in send(), and only if we can (still)
254 // encrypt application data. If we half-closed the connection on our side
255 // we cannot reciprocate the key update any longer.
256 m_key_update_reciprocation_pending = true;
257 } else {
258 // Only an actual reciprocation settles our outstanding request. RFC 9846
259 // 4.7.3 would allow requesting again after any KeyUpdate from the peer,
260 // but waiting for the reciprocation keeps the exemption above one-shot.
261 m_key_update_requested = false;
262 }
263}
264
265void Channel_IO::update_traffic_keys(bool request_peer_update) {
266 const auto cs = cipher_state();
268
270 .add(Key_Update(request_peer_update))
271 .commit());
272
273 if(request_peer_update) {
274 m_key_update_requested = true;
275 }
276 cs->update_write_keys();
277}
278
279void Channel_IO::send(const Alert& alert, bool handle_compat_mode) {
280 const auto cs = cipher_state();
281
282 // RFC 9846 E.4
283 // [...] the client sends a dummy change_cipher_spec record [...]
284 // immediately before its second flight. [...]
285 // The server sends a dummy change_cipher_spec record immediately after
286 // its first handshake message.
287 //
288 // For the client, the "second flight" might be an alert that aborts the
289 // handshake (e.g., from a failing certificate verification or a throwing
290 // callback). The server isn't expected to emit an alert immediately after
291 // its first handshake message, hence it is not handled here.
292 //
293 // Also, the dummy CCS is only sent if the handshake actually produced a
294 // cipher state: i.e., only if we would actually encrypt now.
295 if(handle_compat_mode && !m_dummy_ccs_emitted && m_side == Connection_Side::Client && cs != nullptr) {
297 }
298
299 send_data(Record_Type::Alert, alert.serialize(), cs.get());
300}
301
303 // RFC 9846 5.
304 // An implementation which [...] receives a protected change_cipher_spec
305 // record MUST abort the handshake [...].
306 //
307 // I.e. Change Cipher Spec records must always be sent unprotected, even if
308 // the cipher state is already set up for handshake message encryption.
309 constexpr auto ccs = std::array<uint8_t, 1>{0x01};
311 m_dummy_ccs_emitted = true;
312}
313
316 m_closed_for_reading = true;
317}
318
322
323void Channel_IO::set_record_size_limits(uint16_t out, uint16_t in) {
325}
326
330
331std::shared_ptr<const Cipher_State> Channel_IO::cipher_state() const {
332 return m_cipher_state.lock();
333}
334
335std::shared_ptr<Cipher_State> Channel_IO::cipher_state() {
336 return m_cipher_state.lock();
337}
338
339namespace {
340
341// Once the write buffer grew beyond this size (e.g. due to a single large
342// application write), it is released rather than kept for the lifetime of the
343// connection.
344constexpr size_t max_retained_write_buffer_size = 4 * (TLS_HEADER_SIZE + MAX_CIPHERTEXT_SIZE_TLS13);
345
346class TLS_Channel_IO final : public Channel_IO {
347 public:
348 TLS_Channel_IO(Connection_Side side, std::shared_ptr<const Policy> policy, std::shared_ptr<Callbacks> callbacks) :
349 Channel_IO(side, std::move(policy), std::move(callbacks)), m_record_layer(side), m_handshake_layer(side) {}
350
351 void send_data(Record_Type record_type, std::span<const uint8_t> payload, Cipher_State* cipher_state) override {
352 const size_t max_plaintext_payload_size = record_layer().record_payload_size_limit(policy(), cipher_state);
353
354 // RFC 9846 5.1
355 // Handshake messages MAY be [...] fragmented across several records.
356 // [...] Application Data fragments MAY be split across multiple records
357 // [...].
358 //
359 // In TLS, we may fragment application data and handshake data into multiple
360 // records. Other record types are not allowed to be fragmented.
361 BOTAN_ASSERT_IMPLICATION(payload.size() > max_plaintext_payload_size,
362 record_type == Record_Type::ApplicationData || record_type == Record_Type::Handshake,
363 "Only Handshake and Application Data records may be fragmented");
364
365 auto& output = m_write_buffer;
366 output.clear();
367 if(output.capacity() > max_retained_write_buffer_size) {
368 output.shrink_to_fit();
369 }
370
371 const auto records = ceil_division(payload.size(), max_plaintext_payload_size);
372
373 if(cipher_state == nullptr) {
374 output.reserve(records * TLS_HEADER_SIZE + payload.size());
375 } else if(records > 1) {
376 const auto max_record_size =
377 cipher_state != nullptr
378 ? cipher_state->encrypt_output_length(record_layer().outgoing_record_size_limit())
379 : max_plaintext_payload_size;
380 output.reserve(records * (TLS_HEADER_SIZE + max_record_size));
381 }
382
383 BufferSlicer bs(payload);
384
385 // RFC 9846 5.1
386 // Zero-length fragments of Application Data [...] MAY be sent, as they
387 // are potentially useful as a traffic analysis countermeasure.
388 //
389 // We're using a do-while loop to ensure that we process at least one slice
390 // of the payload, even if that first slice is empty.
391 do /* NOLINT(*-avoid-do-while) */ {
392 const size_t pt_size = std::min(bs.remaining(), max_plaintext_payload_size);
393 const auto pt_fragment = bs.take(pt_size);
394
395 m_record_layer.prepare_record(policy(), record_type, pt_fragment, cipher_state, output);
396 } while(!bs.empty());
397
398 callbacks().tls_emit_data(output);
399 }
400
401 void send_flight(std::vector<Flight::Message> flight) override {
402 auto cs = cipher_state();
404
405 // This isn't very efficient or elegant, but it is a simple way to send
406 // the collected messages and dummy CCSs in as little records as
407 // possible. It will be replaced with a more efficient implementation
408 // with upcoming patches towards DTLS 1.3 support anyway.
409 //
410 // TODO: Replace this with a more efficient implementation
411
412 for(const auto& msg_info : flight) {
413 std::visit( //
415 [&](const Flight::Dummy_ChangeCipherSpec&) {
416 // Flush pending handshake messages, then send the dummy
417 // CCS record. Note that messages preceding a dummy CCS
418 // (i.e. a HelloRetryRequest) are always unprotected
419 // because no cipher state is available, yet.
420 if(!msgs.get().empty()) {
421 send_data(Record_Type::Handshake, msgs.get(), cs.get());
422 msgs.get().clear();
423 }
424 send_dummy_change_cipher_spec();
425 },
426 [&](const Flight::Message_Info& info) {
427 // Collect marshalled messages into the flight's buffer.
428 msgs.get().insert(msgs.get().end(), info.header.begin(), info.header.end());
429 msgs.get().insert(msgs.get().end(), info.serialized.begin(), info.serialized.end());
430 },
431 },
432 msg_info);
433 }
434
435 if(!msgs.get().empty()) {
436 send_data(Record_Type::Handshake, msgs.get(), cs.get());
437
438 // RFC 9846 5.1
439 // To maximize backward compatibility, a record containing an
440 // initial ClientHello SHOULD have version 0x0301.
441 //
442 // We collected the entire first flight of handshake messages into
443 // the `msgs` buffer. By definition, the first flight contains the
444 // initial ClientHello for a TLS client.
445 m_record_layer.disable_sending_compat_mode();
446 }
447 }
448
449 void process(const Handshake_Record& record) override { m_handshake_layer.copy_data(policy(), record); }
450
451 Record_Layer& record_layer() override { return m_record_layer; }
452
453 const Record_Layer& record_layer() const override { return m_record_layer; }
454
455 Handshake_Layer& handshake_layer() override { return m_handshake_layer; }
456
457 const Handshake_Layer& handshake_layer() const override { return m_handshake_layer; }
458
459 private:
460 TLS_Record_Layer m_record_layer;
461 TLS_Handshake_Layer m_handshake_layer;
462
463 secure_vector<uint8_t> m_write_buffer;
464};
465
466} // namespace
467
468std::shared_ptr<Channel_IO> Channel_IO::create(Connection_Side side,
469 TLS_Flavor flavor,
470 std::shared_ptr<const Policy> policy,
471 std::shared_ptr<Callbacks> callbacks) {
472 if(flavor == TLS_Flavor::DTLS) {
473 throw Not_Implemented("DTLS 1.3 is not yet supported");
474 } else {
475 return std::make_shared<TLS_Channel_IO>(side, std::move(policy), std::move(callbacks));
476 }
477}
478
479} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:108
std::vector< uint8_t > serialize() const
Definition tls_alert.cpp:32
virtual uint64_t tls_current_monotonic_clock_ms()
void copy_data(std::span< const uint8_t > data)
std::shared_ptr< const Cipher_State > cipher_state() const
virtual void process(const Handshake_Record &record)=0
const Callbacks & callbacks() const
void send(std::vector< Flight::Message > flight)
Sends a flight of handshake messages to the peer.
std::variant< BytesNeeded, Handshake_Message_13, Post_Handshake_Message_13, ChangeCipherSpec_Record, Alert_Record, ApplicationData_Record > ReceiveEvent
void send_dummy_change_cipher_spec()
Sends a dummy ChangeCipherSpec record to the peer.
void handle_key_update(const Key_Update &key_update)
const Policy & policy() const
void set_selected_certificate_type(Certificate_Type cert_type)
virtual void send_data(Record_Type record_type, std::span< const uint8_t > payload, Cipher_State *cipher_state)=0
void set_record_size_limits(uint16_t out, uint16_t in)
ReceiveEvent next_pending_event(std::optional< Transcript_Hash_State > &transcript_hash, bool handshake_complete)
std::optional< ReceiveEvent > next_pending_handshake_message(std::optional< Transcript_Hash_State > &transcript_hash, bool handshake_complete)
virtual void send_flight(std::vector< Flight::Message > flight)=0
void update_traffic_keys(bool request_peer_update)
static std::shared_ptr< Channel_IO > create(Connection_Side side, TLS_Flavor flavor, std::shared_ptr< const Policy > policy, std::shared_ptr< Callbacks > callbacks)
virtual Record_Layer & record_layer()=0
virtual Handshake_Layer & handshake_layer()=0
void set_selected_certificate_type(Certificate_Type cert_type)
bool expects_reciprocation() const
virtual uint64_t records_per_traffic_key() const
virtual void copy_data(std::span< const uint8_t > data_from_peer)=0
void set_record_size_limits(uint16_t outgoing_limit, uint16_t incoming_limit)
virtual ReadResult next_record(Cipher_State *cipher_state=nullptr)=0
virtual void clear_read_buffer()=0
Strong< std::vector< uint8_t >, struct MarshalledHandshakeMessageFlight_ > MarshalledHandshakeMessageFlight
size_t BytesNeeded
@ MAX_CIPHERTEXT_SIZE_TLS13
Definition tls_magic.h:47
@ TLS_HEADER_SIZE
Definition tls_magic.h:30
BOTAN_FORCE_INLINE constexpr T ceil_division(T a, T b)
Definition bit_ops.h:167
constexpr bool holds_any_of(const std::variant< Ts... > &v) noexcept
Definition stl_util.h:66
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
overloaded(Ts...) -> overloaded< Ts... >