Botan 3.14.1
Crypto and TLS for C&
tls_channel_impl_13.cpp
Go to the documentation of this file.
1/*
2* TLS Channel - implementation for TLS 1.3
3* (C) 2022 Jack Lloyd
4* 2021 Elektrobit Automotive GmbH
5* 2022 Hannes Rantzsch, René Meusel - neXenio GmbH
6* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#include <botan/internal/tls_channel_impl_13.h>
12
13#include <botan/tls_callbacks.h>
14#include <botan/tls_exceptn.h>
15#include <botan/tls_messages_13.h>
16#include <botan/internal/stl_util.h>
17#include <botan/internal/tls_channel_io.h>
18#include <botan/internal/tls_cipher_state.h>
19#include <botan/internal/tls_transcript_hash_13.h>
20
21#include <utility>
22
23namespace Botan::TLS {
24
25namespace {
26
27bool is_user_canceled_alert(const Botan::TLS::Alert& alert) {
28 return alert.type() == Botan::TLS::Alert::UserCanceled;
29}
30
31bool is_close_notify_alert(const Botan::TLS::Alert& alert) {
32 return alert.type() == Botan::TLS::Alert::CloseNotify;
33}
34
35bool is_error_alert(const Botan::TLS::Alert& alert) {
36 // In TLS 1.3 all alerts except for closure alerts are considered error alerts.
37 // (RFC 8446 6.)
38 return !is_close_notify_alert(alert) && !is_user_canceled_alert(alert);
39}
40
41} // namespace
42
43Channel_Impl_13::Channel_Impl_13(const std::shared_ptr<Callbacks>& callbacks,
44 const std::shared_ptr<Session_Manager>& session_manager,
45 const std::shared_ptr<Credentials_Manager>& credentials_manager,
46 const std::shared_ptr<RandomNumberGenerator>& rng,
47 const std::shared_ptr<const Policy>& policy,
48 bool is_server) :
52 m_callbacks(callbacks),
53 m_session_manager(session_manager),
54 m_credentials_manager(credentials_manager),
55 m_rng(rng),
56 m_policy(policy),
57 m_can_read(true),
58 m_can_write(true) {
59 BOTAN_ASSERT_NONNULL(m_callbacks);
60 BOTAN_ASSERT_NONNULL(m_session_manager);
61 BOTAN_ASSERT_NONNULL(m_credentials_manager);
63 BOTAN_ASSERT_NONNULL(m_policy);
64}
65
66Cipher_State& Channel_Impl_13::setup_cipher_state(std::unique_ptr<Cipher_State> cipher_state) {
67 BOTAN_ASSERT_NONNULL(cipher_state);
68 m_cipher_state = std::move(cipher_state);
69 m_channel_io->set_cipher_state(m_cipher_state);
70 return *m_cipher_state;
71}
72
74
75size_t Channel_Impl_13::from_peer(std::span<const uint8_t> data) {
77
78 // RFC 8446 6.1
79 // Any data received after a closure alert has been received MUST be ignored.
80 if(!m_can_read) {
81 return 0;
82 }
83
84 try {
85#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
86 if(expects_downgrade()) {
87 preserve_peer_transcript(data);
88 }
89#endif
90
91 // First, ingest all incoming data...
92 m_channel_io->copy_data(data);
93
94 // ... then, process all pending events (i.e. decoded handshake messages,
95 // alerts, application data, etc.) until we either run out of events and
96 // have to wait for more data, or we encounter an exception and terminate.
97 while(true) {
98 // RFC 8446 6.1
99 // Any data received after a closure alert has been received MUST be ignored.
100 //
101 // ... this data might already be in the record layer's read buffer.
102 if(!m_can_read) {
103 return 0;
104 }
105
106 const auto bytes_needed = std::visit( //
108 [](BytesNeeded bytes) -> std::optional<BytesNeeded> { return bytes; },
109 // NOLINTNEXTLINE(*-missing-std-forward) false positive on templated lambdas in clang-tidy 23
110 [&]<typename T>(T&& event) -> std::optional<BytesNeeded> {
111 constexpr bool can_report_bytes_needed =
112 std::is_same_v<std::optional<BytesNeeded>, decltype(process(std::forward<T>(event)))>;
113 if constexpr(can_report_bytes_needed) {
114 return process(std::forward<T>(event));
115 } else {
116 process(std::forward<T>(event));
117 return {};
118 }
119 },
120 },
122
123 if(bytes_needed.has_value()) {
124 return *bytes_needed;
125 }
126 }
127
128 } catch(TLS_Exception& e) {
130 throw;
132 // RFC 8446 5.2
133 // If the decryption fails, the receiver MUST terminate the connection
134 // with a "bad_record_mac" alert.
135 send_fatal_alert(Alert::BadRecordMac);
136 throw;
137 } catch(Decoding_Error&) {
138 send_fatal_alert(Alert::DecodeError);
139 throw;
140 } catch(...) {
141 send_fatal_alert(Alert::InternalError);
142 throw;
143 }
144}
145
146void Channel_Impl_13::handle(const Key_Update& key_update) {
147 m_channel_io->handle_key_update(key_update);
148}
149
150void Channel_Impl_13::to_peer(std::span<const uint8_t> data) {
152
153 if(!is_active()) {
154 throw Invalid_State("Data cannot be sent on inactive TLS connection");
155 }
156
157 m_channel_io->send(data);
158}
159
161 // An alert that cannot be encoded is never sent; a fatal one is a local teardown
162 if(!alert.is_valid()) {
163 if(alert.is_fatal()) {
164 shutdown();
165 }
166 return;
167 }
168
169 if(m_can_write) {
170 // RFC 8446 6.
171 // All the alerts listed in Section 6.2 MUST be sent with
172 // AlertLevel=fatal [...]
173 const Alert to_send = is_error_alert(alert) ? Alert(alert.type(), true) : alert;
174 try {
175 m_channel_io->send(to_send, compat_mode_ccs_requested());
176 } catch(...) { /* swallow it */
177 }
178 }
179
180 // Note: In TLS 1.3 sending a CloseNotify must not immediately lead to closing the reading end.
181 // RFC 8446 6.1
182 // Each party MUST send a "close_notify" alert before closing its write
183 // side of the connection, unless it has already sent some error alert.
184 // This does not have any effect on its read side of the connection.
185 if(is_close_notify_alert(alert) && m_can_write) {
186 m_can_write = false;
187 if(m_cipher_state) {
188 m_cipher_state->clear_write_keys();
189 }
190 }
191
192 if(is_error_alert(alert)) {
193 shutdown();
194 }
195}
196
198 return m_cipher_state != nullptr && m_cipher_state->can_encrypt_application_traffic() // handshake done
199 && m_can_write; // close() hasn't been called
200}
201
203 std::string_view context,
204 size_t length) const {
206 BOTAN_STATE_CHECK(m_cipher_state != nullptr && m_cipher_state->can_export_keys());
207 return SymmetricKey(m_cipher_state->export_key(label, context, length));
208}
209
210void Channel_Impl_13::update_traffic_keys(bool request_peer_update) {
212 m_channel_io->update_traffic_keys(request_peer_update);
213}
214
216 return [weak = weak_from_this()](std::string_view label, std::span<const uint8_t> secret) {
217 if(const auto self = dynamic_pointer_cast<const Channel_Impl_13>(weak.lock())) {
218 self->maybe_log_secret(label, secret);
219 };
220 };
221}
222
223void Channel_Impl_13::send_flight(std::vector<Flight::Message> flight) {
224 BOTAN_STATE_CHECK(!flight.empty());
226 BOTAN_STATE_CHECK(m_can_write);
227
228 m_channel_io->send(std::move(flight));
229}
230
231std::optional<BytesNeeded> Channel_Impl_13::process(Handshake_Message_13 handshake_msg) {
233 process_handshake_msg(std::move(handshake_msg));
234
235#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
236 if(is_downgrading()) {
237 // Downgrade to TLS 1.2 was detected. Stop everything we do and await
238 // being replaced by a 1.2 implementation.
239 return 0;
240 }
241 if(m_downgrade_info != nullptr) {
242 // We received a TLS 1.3 error alert that could have been a TLS 1.2 warning alert.
243 // Now that we know that we are talking to a TLS 1.3 server, shut down.
244 if(m_downgrade_info->received_tls_13_error_alert) {
245 shutdown();
246 }
247
248 // Downgrade can only be indicated in the first received peer message. This was not the case.
249 m_downgrade_info.reset();
250 }
251#endif
252
253 return {};
254}
255
256void Channel_Impl_13::process(Post_Handshake_Message_13 post_handshake_msg) {
258 process_post_handshake_msg(std::move(post_handshake_msg));
259}
260
261void Channel_Impl_13::process(const Alert_Record& alert_record) {
262 const Alert alert(alert_record.payload);
263
264 if(is_close_notify_alert(alert)) {
265 m_can_read = false;
266 if(m_cipher_state) {
267 m_cipher_state->clear_read_keys();
268 }
269 m_channel_io->notify_closed_for_reading();
270 }
271
272 // user canceled alerts are ignored
273
274 // RFC 8446 6.
275 // All the alerts listed in Section 6.2 MUST be sent with
276 // AlertLevel=fatal and MUST be treated as error alerts when received
277 // regardless of the AlertLevel in the message. Unknown Alert types
278 // MUST be treated as error alerts.
279 if(is_error_alert(alert) && !alert.is_fatal()) {
280 if(!expects_downgrade()) {
281 throw TLS_Exception(Alert::DecodeError, "Error alert not marked fatal");
282 }
283
284#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
286
287 // In TLS 1.2 error alerts might be marked as 'warnings' and would not
288 // demand an immediate shutdown. Until we are sure to talk to a TLS 1.3
289 // peer we must defer the shutdown and refrain from raising a decode
290 // error.
291 m_downgrade_info->received_tls_13_error_alert = true;
292#endif
293 }
294
295 // RFC 8446 6.
296 // In TLS 1.3, the severity is implicit in the type of alert being sent,
297 // and the "level" field can safely be ignored.
298 //
299 // An error alert marked as a warning is only accepted here if a downgrade
300 // to TLS 1.2 is still possible, and then the shutdown is deferred.
301 const bool is_fatal_error_alert = is_error_alert(alert) && alert.is_fatal();
302
303 if(!is_close_notify_alert(alert) && !is_fatal_error_alert) {
305 }
306
307 if(is_fatal_error_alert) {
308 shutdown();
309 }
310
311 callbacks().tls_alert(alert);
312
313 // Respond with our "close_notify" if the application requests us to.
314 if(is_close_notify_alert(alert) && callbacks().tls_peer_closed_connection()) {
315 close();
316 }
317}
318
319void Channel_Impl_13::process(const ChangeCipherSpec_Record& ccs_record) {
320 BOTAN_UNUSED(ccs_record);
323}
324
325void Channel_Impl_13::process(const ApplicationData_Record& record) {
326 BOTAN_ASSERT_NOMSG(record.sequence_number.has_value());
328 if(!m_cipher_state->can_decrypt_application_traffic()) {
329 throw Unexpected_Message("Application data received before handshake completion");
330 }
331
332 if(record.payload.empty()) {
334 } else {
336 }
337
338 callbacks().tls_record_received(record.sequence_number.value(), record.payload);
339}
340
341void Channel_Impl_13::shutdown() {
342 // RFC 8446 6.2
343 // Upon transmission or receipt of a fatal alert message, both
344 // parties MUST immediately close the connection.
345 m_can_read = false;
346 m_can_write = false;
347 m_cipher_state.reset();
348 m_active_state.reset();
349 // Drop any records of the peer that are still buffered
350 m_channel_io->notify_shutdown();
351}
352
353#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
354
355void Channel_Impl_13::expect_downgrade(const Server_Information& server_info,
356 const std::vector<std::string>& next_protocols) {
357 Downgrade_Information di{
358 {},
359 {},
360 {},
361 server_info,
362 next_protocols,
364 {},
365 m_callbacks,
366 m_session_manager,
367 m_credentials_manager,
368 m_rng,
369 m_policy,
371 false, // received_tls_13_error_alert
372 false // will_downgrade
373 };
374 m_downgrade_info = std::make_unique<Downgrade_Information>(std::move(di));
375}
376
377#endif
378
379void Channel_Impl_13::set_record_size_limits(const uint16_t outgoing_limit, const uint16_t incoming_limit) {
380 m_channel_io->set_record_size_limits(outgoing_limit, incoming_limit);
381}
382
384 m_channel_io->set_selected_certificate_type(cert_type);
385}
386
387} // namespace Botan::TLS
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
bool is_valid() const
Definition tls_alert.h:79
bool is_fatal() const
Definition tls_alert.h:98
Type type() const
Definition tls_alert.h:105
virtual void tls_record_received(uint64_t seq_no, std::span< const uint8_t > data)=0
virtual void tls_alert(Alert alert)=0
std::shared_ptr< Cipher_State > m_cipher_state
Cipher_State & setup_cipher_state(std::unique_ptr< Cipher_State > cipher_state)
const Policy & policy() const
SymmetricKey key_material_export(std::string_view label, std::string_view context, size_t length) const override
void send_flight(std::vector< Flight::Message > flight)
void handle(const Key_Update &key_update)
Credentials_Manager & credentials_manager()
RandomNumberGenerator & rng()
std::optional< Transcript_Hash_State > m_transcript_hash
void to_peer(std::span< const uint8_t > data) override
virtual bool compat_mode_ccs_requested() const =0
virtual void process_post_handshake_msg(Post_Handshake_Message_13 msg)=0
std::optional< Active_Connection_State_13 > m_active_state
virtual void process_handshake_msg(Handshake_Message_13 msg)=0
Channel_Impl_13(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< Credentials_Manager > &credentials_manager, const std::shared_ptr< RandomNumberGenerator > &rng, const std::shared_ptr< const Policy > &policy, bool is_server)
SecretLoggerFn secret_logger() const
std::shared_ptr< Channel_IO > m_channel_io
void send_alert(const Alert &alert) override
size_t from_peer(std::span< const uint8_t > data) override
void update_traffic_keys(bool request_peer_update=false) override
virtual void process_dummy_change_cipher_spec()=0
Session_Manager & session_manager()
void set_selected_certificate_type(Certificate_Type cert_type)
void set_record_size_limits(uint16_t outgoing_limit, uint16_t incoming_limit)
void send_fatal_alert(Alert::Type type)
void note_useless_record(const Policy &policy)
virtual bool is_handshake_complete() const =0
static constexpr size_t IO_BUF_DEFAULT_SIZE
Definition tls_channel.h:38
Alert::Type type() const
Definition tls_exceptn.h:21
size_t BytesNeeded
std::variant< Client_Hello_13, Client_Hello_12_Shim, Server_Hello_13, Server_Hello_12_Shim, Hello_Retry_Request, Encrypted_Extensions, Certificate_13, Certificate_Request_13, Certificate_Verify_13, Finished_13 > Handshake_Message_13
std::function< void(std::string_view label, std::span< const uint8_t > secret)> SecretLoggerFn
std::variant< New_Session_Ticket_13, Key_Update > Post_Handshake_Message_13
OctetString SymmetricKey
Definition symkey.h:153