Botan 3.13.0
Crypto and TLS for C&
tls_channel_impl_12.cpp
Go to the documentation of this file.
1/*
2* TLS Channels
3* (C) 2011,2012,2014,2015,2016 Jack Lloyd
4* 2016 Matthias Gierlings
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/tls_channel_impl_12.h>
10
11#include <botan/kdf.h>
12#include <botan/tls_callbacks.h>
13#include <botan/tls_messages_12.h>
14#include <botan/tls_policy.h>
15#include <botan/x509cert.h>
16#include <botan/internal/concat_util.h>
17#include <botan/internal/ct_utils.h>
18#include <botan/internal/loadstor.h>
19#include <botan/internal/mem_utils.h>
20#include <botan/internal/stl_util.h>
21#include <botan/internal/tls_handshake_state.h>
22#include <botan/internal/tls_record.h>
23#include <botan/internal/tls_seq_numbers.h>
24#include <utility>
25
26namespace Botan::TLS {
27
28namespace {
29
30bool is_new_dtls_association_client_hello(std::span<const uint8_t> msg_and_header, Record_Type record_type) {
31 constexpr size_t DTLS_HANDSHAKE_HEADER_SIZE = 12;
32
33 // Every new DTLS handshake starts at message_seq 0. A cookie-bearing
34 // ClientHello uses message_seq 1, so one arriving late belongs to the
35 // previous handshake and must not replace the active association's state.
36 return record_type == Record_Type::Handshake && msg_and_header.size() >= DTLS_HANDSHAKE_HEADER_SIZE &&
37 static_cast<Handshake_Type>(msg_and_header[0]) == Handshake_Type::ClientHello &&
38 load_be(msg_and_header.subspan<4, 2>()) == 0;
39}
40
41// Cap on the number of non-zero-epoch cipher states retained per direction.
42// The current epoch is in active use; one earlier epoch covers any in-flight
43// DTLS records sent immediately before a rekey. Epoch 0 is the pre-handshake
44// plaintext placeholder and is always retained.
45//
46// Note the logic in prune_epochs in tls_seq_numbers.h assumes this is exactly 2
47// so adjust that code if changing this.
48constexpr size_t TLS_RETAINED_CIPHERSTATES = 2;
49
50// The "default MSL specified for TCP" of RFC 6347 4.1; RFC 793 sets it to two
51// minutes. Bounds how long a retired DTLS read epoch stays usable.
52constexpr uint64_t TCP_MSL_MS = 2 * 60 * 1000;
53
54template <typename T>
55void prune_old_cipher_states(std::map<uint16_t, T>& states) {
56 // std::map iterates in ascending key order. Drop the lowest non-zero
57 // entries until at most TLS_RETAINED_CIPHERSTATES remain. The newly
58 // installed epoch is the highest key, so it is preserved.
59 size_t non_zero = states.size() - states.count(0);
60 auto it = states.lower_bound(1);
61 while(non_zero > TLS_RETAINED_CIPHERSTATES) {
62 it = states.erase(it);
63 --non_zero;
64 }
65}
66
67// Run fn, absorbing the exceptions that report malformed input when `absorb`
68// is set. Used where the input is unauthenticated epoch-zero data that must
69// not be able to tear down an established association. Only TLS_Exception and
70// Decoding_Error are absorbed: an Internal_Error from one of the reassembly
71// accounting assertions, or a failed allocation, still propagates rather than
72// leaving the association running on state those assertions exist to protect.
73template <typename F>
74void absorb_malformed_input_errors(bool absorb, F fn) {
75 try {
76 fn();
77 } catch(const TLS_Exception&) {
78 if(!absorb) {
79 throw;
80 }
81 } catch(const Decoding_Error&) {
82 if(!absorb) {
83 throw;
84 }
85 }
86}
87
88} // namespace
89
90Channel_Impl_12::Channel_Impl_12(const std::shared_ptr<Callbacks>& callbacks,
91 const std::shared_ptr<Session_Manager>& session_manager,
92 const std::shared_ptr<RandomNumberGenerator>& rng,
93 const std::shared_ptr<const Policy>& policy,
94 bool is_server,
95 bool is_datagram,
96 size_t reserved_io_buffer_size) :
97 m_is_server(is_server),
98 m_is_datagram(is_datagram),
99 m_callbacks(callbacks),
100 m_session_manager(session_manager),
101 m_policy(policy),
102 m_rng(rng),
103 m_has_been_closed(false) {
104 BOTAN_ASSERT_NONNULL(m_callbacks);
105 BOTAN_ASSERT_NONNULL(m_session_manager);
107 BOTAN_ASSERT_NONNULL(m_policy);
108
109 /* epoch 0 is plaintext, thus null cipher state */
110 m_write_cipher_states[0] = nullptr;
111 m_read_cipher_states[0] = {};
112
113 m_writebuf.reserve(reserved_io_buffer_size);
114 m_readbuf.reserve(reserved_io_buffer_size);
115}
116
117void Channel_Impl_12::reset_state() {
118 m_active_state.reset();
119 m_pending_state.reset();
120 m_epochs_before_latest_renegotiation.reset();
121 m_resumption_handle.reset();
122 m_readbuf.clear();
123 m_write_cipher_states.clear();
124 m_read_cipher_states.clear();
125}
126
127void Channel_Impl_12::note_resumption_handle(std::optional<Session_Handle> handle) {
128 m_resumption_handle = std::move(handle);
129}
130
131std::vector<Session_Handle> Channel_Impl_12::take_sessions_to_invalidate() {
132 // A ticket-backed session is not cached under the ServerHello session ID, so
133 // both handles have to be collected.
134 std::vector<Session_Handle> handles;
135
136 if(m_resumption_handle.has_value()) {
137 handles.push_back(m_resumption_handle.value());
138 m_resumption_handle.reset();
139 }
140
141 if(m_active_state.has_value()) {
142 const auto& sid = m_active_state->session_id();
143 if(!sid.empty()) {
144 handles.emplace_back(sid);
145 }
146 }
147
148 return handles;
149}
150
151void Channel_Impl_12::invalidate_sessions(const std::vector<Session_Handle>& handles) {
152 // RFC 5246 7.2.2: "Servers and clients MUST forget any session-identifiers,
153 // keys, and secrets associated with a failed connection. Thus, any
154 // connection terminated with a fatal alert MUST NOT be resumed."
155 //
156 // Best effort, and deliberately last: remove() reaches application-supplied
157 // storage and can throw, and by then the keys are already gone. Letting a
158 // failed cache eviction abort the teardown would leave the channel usable
159 // after a security-fatal event, which is the worse of the two outcomes. A
160 // stateless ticket issuer has nothing to remove and cannot revoke what it
161 // already handed out.
162 for(const auto& handle : handles) {
163 try {
164 session_manager().remove(handle);
165 } catch(...) {}
166 }
167}
168
170 // This operation only makes sense for DTLS
171 BOTAN_ASSERT_NOMSG(m_is_datagram);
172 m_active_state.reset();
173 m_read_cipher_states.clear();
174 m_write_cipher_states.clear();
175
176 m_write_cipher_states[0] = nullptr;
177 m_read_cipher_states[0] = {};
178
179 if(m_sequence_numbers) {
180 m_sequence_numbers->reset(); // NOLINT(*-ambiguous-smartptr-reset-call)
181 }
182}
183
185
186Connection_Sequence_Numbers& Channel_Impl_12::sequence_numbers() const {
187 BOTAN_ASSERT(m_sequence_numbers, "Have a sequence numbers object");
188 return *m_sequence_numbers;
189}
190
191std::shared_ptr<Connection_Cipher_State> Channel_Impl_12::read_cipher_state_epoch(uint16_t epoch) const {
192 auto i = m_read_cipher_states.find(epoch);
193 if(i == m_read_cipher_states.end()) {
194 throw Internal_Error("TLS::Channel_Impl_12 No read cipherstate for epoch " + std::to_string(epoch));
195 }
196
197 // RFC 6347 4.1: "In general, implementations SHOULD discard packets from
198 // earlier epochs, but if packet loss causes noticeable problems they MAY
199 // choose to retain keying material from previous epochs for up to the
200 // default MSL specified for TCP [TCP] to allow for packet reordering."
201 // read_dtls_record drops the record when this throws.
202 if(const auto& retired_at = i->second.retired_at; retired_at.has_value()) {
203 const auto now = callbacks().tls_current_monotonic_clock_ms();
204 const auto retired = retired_at.value();
205 BOTAN_ASSERT_NOMSG(now >= retired);
206 if(now - retired > TCP_MSL_MS) {
207 throw Invalid_State("TLS::Channel_Impl_12 Read cipherstate for epoch " + std::to_string(epoch) +
208 " is past its retention window");
209 }
210 }
211
212 return i->second.state;
213}
214
215std::shared_ptr<Connection_Cipher_State> Channel_Impl_12::write_cipher_state_epoch(uint16_t epoch) const {
216 auto i = m_write_cipher_states.find(epoch);
217 if(i == m_write_cipher_states.end()) {
218 throw Internal_Error("TLS::Channel_Impl_12 No write cipherstate for epoch " + std::to_string(epoch));
219 }
220 return i->second;
221}
222
223std::vector<X509_Certificate> Channel_Impl_12::peer_cert_chain() const {
224 if(m_active_state.has_value()) {
225 return m_active_state->peer_certs();
226 }
227 return std::vector<X509_Certificate>();
228}
229
230std::optional<std::string> Channel_Impl_12::external_psk_identity() const {
231 if(m_active_state.has_value()) {
232 return m_active_state->psk_identity();
233 }
234 if(const auto* state = pending_state()) {
235 return state->psk_identity();
236 }
237 return std::nullopt;
238}
239
241 if(pending_state() != nullptr) {
242 throw Internal_Error("create_handshake_state called during handshake");
243 }
244
245 if(m_active_state.has_value()) {
246 const Protocol_Version active_version = m_active_state->version();
247
248 if(active_version.is_datagram_protocol() != version.is_datagram_protocol()) {
249 throw TLS_Exception(Alert::ProtocolVersion,
250 "Active state using version " + active_version.to_string() + " cannot change to " +
251 version.to_string() + " in pending");
252 }
253 }
254
255 if(!m_sequence_numbers) {
256 if(version.is_datagram_protocol()) {
257 m_sequence_numbers = std::make_unique<Datagram_Sequence_Numbers>();
258 } else {
259 m_sequence_numbers = std::make_unique<Stream_Sequence_Numbers>();
260 }
261 }
262
263 // Read epochs at or below this one belong to the association already in place,
264 // so application data under them stays deliverable while this handshake runs.
265 // Anything above it is this handshake's own, unauthenticated until its
266 // Finished. See the application-data gate in from_peer.
267 m_epochs_before_latest_renegotiation = Epochs_Before_Latest_Renegotiation{sequence_numbers().current_read_epoch(),
268 sequence_numbers().current_write_epoch()};
269
270 // Floor for the pending handshake's reassembly: a delayed record from the
271 // handshake arrives under a lower epoch and must be rejected. It would
272 // otherwise take the sequence slot the real message needs.
273 //
274 // Zero on an epoch-zero restart, because there the peer legitimately
275 // begins again at epoch zero and the floor would reject it. This is keyed
276 // on the restart actually occurring, not on the policy allowing it: an
277 // ordinary renegotiation needs the floor either way.
278 const uint16_t initial_epoch = epoch0_restart ? 0 : m_epochs_before_latest_renegotiation->read_epoch;
279
280 using namespace std::placeholders;
281
282 std::unique_ptr<Handshake_IO> io;
283 if(version.is_datagram_protocol()) {
284 const uint16_t mtu = static_cast<uint16_t>(policy().dtls_default_mtu());
285 const size_t initial_timeout_ms = policy().dtls_initial_timeout();
286 const size_t max_timeout_ms = policy().dtls_maximum_timeout();
287 const std::optional<size_t> max_retransmissions = policy().dtls_maximum_retransmissions();
288
289 auto send_record_f = [this](uint16_t epoch, Record_Type record_type, const std::vector<uint8_t>& record) {
290 send_record_under_epoch(epoch, record_type, record);
291 };
292 auto clock_f = [this]() { return callbacks().tls_current_monotonic_clock_ms(); };
293 io = std::make_unique<Datagram_Handshake_IO>(send_record_f,
294 clock_f,
295 sequence_numbers(),
296 mtu,
297 initial_timeout_ms,
298 max_timeout_ms,
299 max_retransmissions,
300 policy().maximum_handshake_message_size(),
301 initial_epoch);
302 } else {
303 auto send_record_f = [this](Record_Type rec_type, const std::vector<uint8_t>& record) {
304 send_record(rec_type, record);
305 };
306 io = std::make_unique<Stream_Handshake_IO>(send_record_f);
307 }
308
309 m_pending_state = new_handshake_state(std::move(io));
310
311 if(m_active_state.has_value()) {
312 m_pending_state->set_version(m_active_state->version());
313 }
314
315 return *m_pending_state;
316}
317
318bool Channel_Impl_12::pending_handshake_epochs_unmoved() const {
319 // Nothing pending: there is nothing to act on, and the epoch markers are
320 // unset, so the comparison would be meaningless.
321 if(!m_pending_state || !m_epochs_before_latest_renegotiation.has_value()) {
322 return true;
323 }
324
325 // Before either ChangeCipherSpec the established association still owns both
326 // epochs, so dropping the pending handshake leaves it exactly as it was.
327 return sequence_numbers().current_read_epoch() == m_epochs_before_latest_renegotiation->read_epoch &&
328 sequence_numbers().current_write_epoch() == m_epochs_before_latest_renegotiation->write_epoch;
329}
330
331void Channel_Impl_12::clear_pending_handshake_state() {
332 m_pending_state.reset();
333 m_epochs_before_latest_renegotiation.reset();
334}
335
336/*
337* The retransmission budget is exhausted and this handshake will not complete.
338* Leaving the pending state installed makes every later timeout_check throw
339* again from unchanged state, and blocks renegotiate(), so the channel can
340* neither recover nor be retried.
341*/
342void Channel_Impl_12::abandon_timed_out_handshake() {
343 if(m_active_state.has_value() && pending_handshake_epochs_unmoved()) {
344 // A renegotiation that never reached its ChangeCipherSpec. The
345 // established association is untouched, so keep it and let the
346 // application try again.
347 clear_pending_handshake_state();
348 } else {
349 // Either there is no established association to fall back to, or a
350 // ChangeCipherSpec has already moved an epoch and there is no rollback
351 // that would leave keys, identity and sequence numbers describing the
352 // same handshake. Close.
353 m_has_been_closed = true;
354 reset_state();
355 }
356}
357
359 if(m_is_datagram && !m_has_been_closed && m_pending_state) {
360 try {
361 return m_pending_state->handshake_io().timeout_check();
362 } catch(const TLS_Exception&) {
363 abandon_timed_out_handshake();
364 throw;
365 }
366 }
367
368 // Old cipher states are pruned at install time (see prune_old_cipher_states),
369 // so no periodic cleanup is needed here.
370 return false;
371}
372
373void Channel_Impl_12::renegotiate(bool force_full_renegotiation) {
374 if(pending_state() != nullptr) { // currently in handshake?
375 return;
376 }
377
378 if(m_active_state.has_value()) {
379 // A DTLS handshake consumes one read and one write epoch. Refuse here if
380 // either is spent, so the caller learns before the handshake tears the
381 // working association down partway through. See next_epoch().
382 if(m_is_datagram &&
383 (sequence_numbers().current_read_epoch() == 0xFFFF || sequence_numbers().current_write_epoch() == 0xFFFF)) {
384 throw Invalid_State("DTLS epoch counter exhausted, a new association is required");
385 }
386
387 if(!force_full_renegotiation) {
388 force_full_renegotiation = !policy().allow_resumption_for_renegotiation();
389 }
390
391 initiate_handshake(create_handshake_state(m_active_state->version()), force_full_renegotiation);
392 } else {
393 throw Invalid_State("Cannot renegotiate on inactive connection");
394 }
395}
396
397void Channel_Impl_12::update_traffic_keys(bool /*update_requested*/) {
398 throw Invalid_Argument("cannot update traffic keys on a TLS 1.2 channel");
399}
400
402 const auto* pending = pending_state();
403
404 BOTAN_ASSERT(pending && pending->server_hello(), "Have received server hello");
405
406 if(pending->server_hello()->compression_method() != 0) {
407 throw Internal_Error("Negotiated unknown compression algorithm");
408 }
409
410 sequence_numbers().new_read_cipher_state();
411
412 const uint16_t epoch = sequence_numbers().current_read_epoch();
413
414 BOTAN_ASSERT(!m_read_cipher_states.contains(epoch), "No read cipher state currently set for next epoch");
415
416 // flip side as we are reading
417 auto read_state = std::make_shared<Connection_Cipher_State>(
418 pending->version(),
420 false,
421 pending->ciphersuite(),
422 pending->session_keys(),
423 pending->server_hello()->supports_encrypt_then_mac());
424
425 // The epoch we just left is retained only to absorb reordering, so start its
426 // clock now (see read_cipher_state_epoch). Epoch 0 is the plaintext
427 // placeholder and holds no keys, so the window does not apply to it.
428 if(m_is_datagram && epoch > 1) {
429 if(auto prev = m_read_cipher_states.find(static_cast<uint16_t>(epoch - 1)); prev != m_read_cipher_states.end()) {
430 prev->second.retired_at = callbacks().tls_current_monotonic_clock_ms();
431 }
432 }
433
434 m_read_cipher_states[epoch] = Retained_Read_Cipher_State{.state = read_state, .retired_at = std::nullopt};
435 prune_old_cipher_states(m_read_cipher_states);
436}
437
439 const auto* pending = pending_state();
440
441 BOTAN_ASSERT(pending && pending->server_hello(), "Have received server hello");
442
443 if(pending->server_hello()->compression_method() != 0) {
444 throw Internal_Error("Negotiated unknown compression algorithm");
445 }
446
447 sequence_numbers().new_write_cipher_state();
448
449 const uint16_t epoch = sequence_numbers().current_write_epoch();
450
451 BOTAN_ASSERT(!m_write_cipher_states.contains(epoch), "No write cipher state currently set for next epoch");
452
453 auto write_state = std::make_shared<Connection_Cipher_State>(pending->version(),
454 side,
455 true,
456 pending->ciphersuite(),
457 pending->session_keys(),
458 pending->server_hello()->supports_encrypt_then_mac());
459
460 m_write_cipher_states[epoch] = write_state;
461 prune_old_cipher_states(m_write_cipher_states);
462}
463
465 return m_active_state.has_value();
466}
467
469 return !is_closed() && is_handshake_complete();
470}
471
472std::optional<std::chrono::milliseconds> Channel_Impl_12::next_retransmission_timeout() const {
473 if(m_is_datagram && !m_has_been_closed && m_pending_state) {
474 return m_pending_state->handshake_io().next_retransmission_timeout();
475 }
476
477 return std::nullopt;
478}
479
481 return m_has_been_closed;
482}
483
485 BOTAN_ASSERT_NONNULL(m_pending_state);
486
487 const auto& state = *m_pending_state;
488
489 if(!state.version().is_datagram_protocol()) {
490 // TLS is easy just remove all but the current state
491 const uint16_t current_epoch = sequence_numbers().current_write_epoch();
492
493 const auto not_current_epoch = [current_epoch](uint16_t epoch) { return (epoch != current_epoch); };
494
495 map_remove_if(not_current_epoch, m_write_cipher_states);
496 map_remove_if(not_current_epoch, m_read_cipher_states);
497 }
498
499 // RFC 6347 4.2.4: "the node that transmits the last flight (the server in an
500 // ordinary handshake or the client in a resumed handshake) MUST respond to a
501 // retransmit of the peer's last flight with a retransmit of the last
502 // flight." Both endpoints retain handshake sequence state, but only that
503 // node replays its outgoing flight.
504 const bool sent_terminal_dtls_flight = m_is_datagram && (m_is_server == (state.server_hello_done() != nullptr));
505
506 if(m_is_datagram) {
507 m_active_state = Active_Connection_State_12(state, application_protocol(), m_pending_state->take_handshake_io());
508 if(auto* dtls_io = m_active_state->dtls_handshake_io()) {
509 // Retain receive sequence state on both endpoints to distinguish a
510 // retransmission from an unexpected new handshake message. Only the
511 // terminal-flight sender responds by replaying its final flight.
512 dtls_io->finalize_handshake(sent_terminal_dtls_flight);
513 }
514 } else {
515 m_active_state = Active_Connection_State_12(state, application_protocol());
516 }
517
518 clear_pending_handshake_state();
519
521}
522
523size_t Channel_Impl_12::from_peer(std::span<const uint8_t> data) {
524 const bool allow_epoch0_restart = m_is_datagram && m_is_server && policy().allow_dtls_epoch0_restart();
525
526 const auto* input = data.data();
527 auto input_size = data.size();
528
529 try {
530 while(input_size > 0) {
531 // A fatal alert destroys the cipher states, so nothing further can even
532 // be decrypted. Closure by close_notify is different: the responding
533 // close_notify still has to be read, so those records keep flowing
534 // through the loop and are filtered per record type below.
535 if(m_had_fatal_alert) {
536 return 0;
537 }
538
539 size_t consumed = 0;
540
541 auto get_epoch = [this](uint16_t epoch) { return read_cipher_state_epoch(epoch); };
542
543 const Record_Header record = read_record(m_is_datagram,
544 m_readbuf,
545 input,
546 input_size,
547 consumed,
548 m_record_buf,
549 m_sequence_numbers.get(),
550 get_epoch,
551 allow_epoch0_restart);
552
553 const size_t needed = record.needed();
554
555 BOTAN_ASSERT(consumed > 0, "Got to eat something");
556
557 BOTAN_ASSERT(consumed <= input_size, "Record reader consumed sane amount");
558
559 input += consumed;
560 input_size -= consumed;
561
562 BOTAN_ASSERT(input_size == 0 || needed == 0, "Got a full record or consumed all input");
563
564 if(input_size == 0 && needed != 0) {
565 return needed; // need more data to complete record
566 }
567
568 // Ignore invalid records in DTLS
569 if(m_is_datagram && record.type() == Record_Type::Invalid) {
570 return 0;
571 }
572
573 const bool old_unprotected_record = m_is_datagram && record.epoch() == 0 && m_active_state.has_value() &&
574 sequence_numbers().current_read_epoch() > 0;
575
576 // Once encrypted traffic is expected, epoch-zero records are
577 // unauthenticated. Only handshake records can be useful as part of a
578 // retransmitted flight or an explicitly allowed association restart.
579 if(old_unprotected_record && record.type() != Record_Type::Handshake &&
581 continue;
582 }
583
584 if(m_record_buf.size() > MAX_PLAINTEXT_SIZE) {
585 if(old_unprotected_record) {
586 continue;
587 }
588
589 throw TLS_Exception(Alert::RecordOverflow, "TLS plaintext record is larger than allowed maximum");
590 }
591
592 const bool epoch0_restart = allow_epoch0_restart && record.epoch() == 0 && m_active_state.has_value();
593 BOTAN_ASSERT_IMPLICATION(epoch0_restart, allow_epoch0_restart, "Allowed state");
594
595 const bool initial_record = epoch0_restart || (pending_state() == nullptr && !m_active_state.has_value());
596 bool initial_handshake_message = false;
597 if(record.type() == Record_Type::Handshake && !m_record_buf.empty()) {
598 const Handshake_Type type = static_cast<Handshake_Type>(m_record_buf[0]);
599 initial_handshake_message = (type == Handshake_Type::ClientHello);
600 }
601
602 if(record.type() != Record_Type::Alert && !old_unprotected_record) {
603 if(initial_record) {
604 // For initial records just check for basic sanity
605 if(record.version().major_version() != 3 && record.version().major_version() != 0xFE) {
606 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version in initial record");
607 }
608 } else if(const auto* pending = pending_state()) {
609 if(pending->server_hello() != nullptr && !initial_handshake_message &&
610 record.version() != pending->version()) {
611 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version");
612 }
613 } else if(m_active_state.has_value()) {
614 if(record.version() != m_active_state->version() && !initial_handshake_message) {
615 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version");
616 }
617 }
618 }
619
620 // RFC 5246 7.2.1: "Any data received after a closure alert is ignored."
621 // This is about a closure alert the peer sent us. A peer that keeps
622 // talking after *our* close_notify is a different case, kept as an
623 // error below; BoGo's Shutdown-Shim-ApplicationData requires it.
624 if(m_peer_closed_connection && record.type() != Record_Type::Alert) {
625 continue;
626 }
627
628 if(record.type() == Record_Type::Handshake || record.type() == Record_Type::ChangeCipherSpec) {
629 if(m_has_been_closed) {
630 throw TLS_Exception(Alert::UnexpectedMessage, "Received handshake data after connection closure");
631 }
632 process_handshake_ccs(m_record_buf, record.sequence(), record.type(), record.version(), epoch0_restart);
633 } else if(record.type() == Record_Type::ApplicationData) {
634 if(m_has_been_closed) {
635 throw TLS_Exception(Alert::UnexpectedMessage, "Received application data after connection closure");
636 }
637 if(pending_state() != nullptr) {
638 /*
639 What matters is which epoch the record belongs to, not which role we
640 are playing.
641
642 RFC 6347 4.2.4: "Implementations MUST either discard or buffer all
643 application data packets for the new epoch until they have received
644 the Finished message for that epoch." Data under the epoch this
645 handshake installed is not authenticated until its Finished, so it
646 must not reach the application; equally it is not an error, because
647 ordinary reordering produces it whenever a peer writes immediately
648 after activating.
649
650 Data under an epoch the established association owns stays valid
651 while a renegotiation is in flight, per 4.1.
652
653 Epoch zero is neither: application data there is plaintext, so it is
654 never legitimate and no association is at stake.
655 */
656 if(m_is_datagram && record.epoch() > 0) {
657 const uint16_t active_epoch =
658 m_epochs_before_latest_renegotiation ? m_epochs_before_latest_renegotiation->read_epoch : 0;
659
660 if(!m_active_state.has_value() || record.epoch() > active_epoch) {
661 continue; // this handshake's epoch, still unauthenticated
662 }
663 } else {
664 throw TLS_Exception(Alert::UnexpectedMessage, "Can't interleave application and handshake data");
665 }
666 }
667 process_application_data(record.sequence(), m_record_buf);
668 } else if(record.type() == Record_Type::Alert) {
669 process_alert(m_record_buf);
670 } else if(record.type() != Record_Type::Invalid) {
671 throw Unexpected_Message("Unexpected record type " + std::to_string(static_cast<size_t>(record.type())) +
672 " from counterparty");
673 }
674 }
675
676 return 0; // on a record boundary
677 } catch(TLS_Exception& e) {
679 throw;
681 send_fatal_alert(Alert::BadRecordMac);
682 throw;
683 } catch(Decoding_Error&) {
684 send_fatal_alert(Alert::DecodeError);
685 throw;
686 } catch(...) {
687 send_fatal_alert(Alert::InternalError);
688 throw;
689 }
690}
691
692void Channel_Impl_12::process_handshake_ccs(const secure_vector<uint8_t>& record,
693 uint64_t record_sequence,
694 Record_Type record_type,
695 Protocol_Version record_version,
696 bool epoch0_restart) {
697 const auto process_retransmitted_record = [&] {
698 BOTAN_ASSERT(m_active_state.has_value(), "Have active DTLS association for retransmission");
699 BOTAN_ASSERT_NONNULL(m_active_state->dtls_handshake_io());
700 // Epoch-zero records are unauthenticated and may be spoofed, so a
701 // malformed one must not tear down an established association.
702 const bool unauthenticated = (record_sequence >> 48) == 0;
703
704 absorb_malformed_input_errors(unauthenticated, [&] {
705 m_active_state->dtls_handshake_io()->add_retransmitted_record(
706 record.data(), record.size(), record_type, record_sequence);
707 });
708 };
709
710 if(!m_pending_state) {
711 // With no pending handshake this is either a new handshake attempt or a
712 // DTLS retransmission from the previous handshake. The latter must not
713 // create fresh pending state; it only asks us to replay our last flight.
714 if(epoch0_restart && m_sequence_numbers && m_active_state.has_value()) {
715 const bool starts_new_handshake = is_new_dtls_association_client_hello(record, record_type);
716
717 if(!starts_new_handshake) {
718 process_retransmitted_record();
719 return;
720 }
721 }
722
723 if(m_is_datagram && !epoch0_restart) {
724 if(m_sequence_numbers) {
725 const uint16_t epoch = record_sequence >> 48;
726 const uint16_t current_epoch = sequence_numbers().current_read_epoch();
727 if(epoch == current_epoch) {
728 // Either endpoint can initiate renegotiation from FINISHED:
729 // clients send ClientHello, servers send HelloRequest.
730 const bool starts_new_handshake =
731 (record_type == Record_Type::Handshake && !record.empty() &&
732 (static_cast<Handshake_Type>(record[0]) == Handshake_Type::ClientHello ||
733 static_cast<Handshake_Type>(record[0]) == Handshake_Type::HelloRequest));
734
735 if(m_active_state.has_value() && !starts_new_handshake) {
736 process_retransmitted_record();
737 } else {
738 create_handshake_state(record_version, epoch0_restart);
739 }
740 } else if(current_epoch > 0 && epoch == current_epoch - 1) {
741 process_retransmitted_record();
742 }
743 } else {
744 create_handshake_state(record_version, epoch0_restart);
745 }
746 } else {
747 create_handshake_state(record_version, epoch0_restart);
748 }
749 }
750
751 // May have been created in above conditional
752 if(m_pending_state) {
753 // An epoch-zero record is unauthenticated. Once an association is
754 // established, one arriving during a pending renegotiation must not be
755 // able to destroy it, exactly as for the no-pending-handshake path above.
756 // Without this a single forged CCS or handshake fragment tore down the
757 // active association and the renegotiation along with it.
758 //
759 // Delivery is inside the guard as well as reassembly. A bare 12-byte
760 // header declaring a zero-length message reassembles cleanly and only
761 // fails when the message itself is parsed or dispatched, which reaches
762 // the same teardown by a later route.
763 const bool unauthenticated_against_active_association =
764 m_is_datagram && (record_sequence >> 48) == 0 && m_active_state.has_value();
765
766 absorb_malformed_input_errors(unauthenticated_against_active_association, [&] {
767 m_pending_state->handshake_io().add_record(record.data(), record.size(), record_type, record_sequence);
768
769 while(auto* pending = m_pending_state.get()) {
770 auto msg = pending->get_next_handshake_msg(policy().maximum_handshake_message_size());
771
772 if(msg.first == Handshake_Type::None) { // no full handshake yet
773 break;
774 }
775
776 process_handshake_msg(*pending, msg.first, msg.second, epoch0_restart);
777
778 if(!m_pending_state) {
779 break;
780 }
781 }
782 });
783 }
784}
785
786void Channel_Impl_12::process_application_data(uint64_t seq_no, const secure_vector<uint8_t>& record) {
787 if(!m_active_state.has_value()) {
788 throw Unexpected_Message("Application data before handshake done");
789 }
790
791 // ApplicationData must arrive under a non-zero read epoch
792 const uint16_t read_epoch =
793 m_is_datagram ? static_cast<uint16_t>(seq_no >> 48) : sequence_numbers().current_read_epoch();
794 if(read_epoch == 0) {
795 throw Unexpected_Message("Application data received in unexpected read epoch");
796 }
797
798 callbacks().tls_record_received(seq_no, record);
799}
800
801void Channel_Impl_12::process_alert(const secure_vector<uint8_t>& record) {
802 const Alert alert_msg(record);
803
804 // RFC 5246 7.2.2:
805 // no_renegotiation
806 // Sent by the client in response to a hello request or by the
807 // server in response to a client hello after initial handshaking.
808 //
809 // Both of those precede any ChangeCipherSpec from the refusing side, so a
810 // refusal arriving after one means the peer both refused the handshake and
811 // proceeded with it. Discarding the pending state is what implements the
812 // refusal, but past a CCS that state is the only thing keeping application
813 // data under the new, un-Finished keys from being delivered, and there is no
814 // rollback that would leave keys, identity and exporter describing the same
815 // handshake. End the association rather than open that gate.
816 if(alert_msg.type() == Alert::NoRenegotiation && m_active_state.has_value()) {
817 if(!pending_handshake_epochs_unmoved()) {
818 throw TLS_Exception(Alert::UnexpectedMessage, "Received no_renegotiation after ChangeCipherSpec");
819 }
820
821 clear_pending_handshake_state();
822 }
823
824 if(alert_msg.is_fatal()) {
825 // RFC 5246 7.2.2: "Upon transmission or receipt of a fatal alert message,
826 // both parties immediately close the connection."
827 //
828 // The teardown completes before the application hears about the alert, so
829 // the callback cannot reach the connection or its secrets. Same order as
830 // the TLS 1.3 channel.
831 m_has_been_closed = true;
832 m_had_fatal_alert = true;
833 const auto invalidated = take_sessions_to_invalidate();
834 reset_state();
835 invalidate_sessions(invalidated);
836 }
837
838 callbacks().tls_alert(alert_msg);
839
840 if(alert_msg.type() == Alert::CloseNotify) {
841 m_peer_closed_connection = true;
842
843 // TLS 1.2 requires us to immediately react with our "close_notify",
844 // the return value of the application's callback has no effect on that.
846 send_warning_alert(Alert::CloseNotify); // reply in kind
847 }
848
849 if(alert_msg.type() == Alert::CloseNotify || alert_msg.is_fatal()) {
850 m_has_been_closed = true;
851 }
852}
853
854void Channel_Impl_12::write_record(Connection_Cipher_State* cipher_state,
855 uint16_t epoch,
856 Record_Type record_type,
857 const uint8_t input[],
858 size_t length) {
859 BOTAN_ASSERT(m_pending_state || m_active_state.has_value(), "Some connection state exists");
860
861 const Protocol_Version record_version = (m_pending_state) ? (m_pending_state->version()) : m_active_state->version();
862
863 const uint64_t next_seq = sequence_numbers().next_write_sequence(epoch);
864
865 if(cipher_state == nullptr) {
866 TLS::write_unencrypted_record(m_writebuf, record_type, record_version, next_seq, input, length);
867 } else {
868 TLS::write_record(m_writebuf, record_type, record_version, next_seq, input, length, *cipher_state, rng());
869 }
870
871 callbacks().tls_emit_data(m_writebuf);
872}
873
874void Channel_Impl_12::send_record_array(uint16_t epoch, Record_Type type, const uint8_t input[], size_t length) {
875 if(length == 0) {
876 return;
877 }
878
879 auto cipher_state = write_cipher_state_epoch(epoch);
880
881 while(length > 0) {
882 const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
883 write_record(cipher_state.get(), epoch, type, input, sending);
884
885 input += sending;
886 length -= sending;
887 }
888}
889
890void Channel_Impl_12::send_record(Record_Type record_type, const std::vector<uint8_t>& record) {
891 send_record_array(sequence_numbers().current_write_epoch(), record_type, record.data(), record.size());
892}
893
894void Channel_Impl_12::send_record_under_epoch(uint16_t epoch,
895 Record_Type record_type,
896 const std::vector<uint8_t>& record) {
897 send_record_array(epoch, record_type, record.data(), record.size());
898}
899
900void Channel_Impl_12::to_peer(std::span<const uint8_t> data) {
901 if(!is_active()) {
902 throw Invalid_State("Data cannot be sent on inactive TLS connection");
903 }
904
905 send_record_array(sequence_numbers().current_write_epoch(), Record_Type::ApplicationData, data.data(), data.size());
906}
907
909 const bool ready_to_send_anything = !is_closed() && m_sequence_numbers;
910 if(alert.is_valid() && ready_to_send_anything) {
911 try {
912 send_record(Record_Type::Alert, alert.serialize());
913 } catch(...) { /* swallow it */
914 }
915 }
916
917 // RFC 5246 7.2.2:
918 // no_renegotiation
919 // Sent by the client in response to a hello request or by the
920 // server in response to a client hello after initial handshaking.
921 //
922 // In this case we are the peer sending the refusal, so there is no reason
923 // for our epochs to have moved. If they somehow did, clear the pending
924 // state. A strictly better approach here would be to simply throw
925 // Internal_Error, but send_alert is called from within catch handlers
926 // so this is not currently viable.
927 if(alert.type() == Alert::NoRenegotiation && m_active_state.has_value()) {
928 if(pending_handshake_epochs_unmoved()) {
929 clear_pending_handshake_state();
930 }
931 }
932
933 if(alert.is_fatal()) {
934 // Order matters: the channel is made unusable and its secrets destroyed
935 // before any application-supplied storage is touched, so a throwing
936 // session manager cannot leave is_active() true with live keys.
937 m_had_fatal_alert = true;
938 m_has_been_closed = true;
939
940 // Alert::None is the local teardown that is never sent to the peer, used
941 // where the trigger was unauthenticated input or a local timeout. Evicting
942 // the resumption state on that basis would hand anyone able to reach the
943 // address the ability to destroy it, which is what keeping the teardown
944 // local exists to prevent.
945 const auto invalidated =
946 (alert.type() == Alert::None) ? std::vector<Session_Handle>() : take_sessions_to_invalidate();
947
948 reset_state();
949 invalidate_sessions(invalidated);
950 }
951
952 if(alert.type() == Alert::CloseNotify || alert.is_fatal()) {
953 m_has_been_closed = true;
954 }
955}
956
958 BOTAN_ASSERT_NONNULL(client_hello);
959 const bool secure_renegotiation = client_hello->secure_renegotiation();
960
961 if(m_active_state && m_active_state->client_supports_secure_renegotiation() != secure_renegotiation) {
962 throw TLS_Exception(Alert::HandshakeFailure, "Client changed its mind about secure renegotiation");
963 }
964
965 if(secure_renegotiation) {
966 const std::vector<uint8_t>& data = client_hello->renegotiation_info();
967
968 const auto expected = secure_renegotiation_data_for_client_hello();
969 if(!CT::is_equal<uint8_t>(data, expected).as_bool()) {
970 throw TLS_Exception(Alert::HandshakeFailure, "Client sent bad values for secure renegotiation");
971 }
972 }
973}
974
976 BOTAN_ASSERT_NONNULL(server_hello);
977 const bool secure_renegotiation = server_hello->secure_renegotiation();
978
979 if(m_active_state && m_active_state->server_supports_secure_renegotiation() != secure_renegotiation) {
980 throw TLS_Exception(Alert::HandshakeFailure, "Server changed its mind about secure renegotiation");
981 }
982
983 if(secure_renegotiation) {
984 const std::vector<uint8_t>& data = server_hello->renegotiation_info();
985
986 const auto expected = secure_renegotiation_data_for_server_hello();
987 if(!CT::is_equal<uint8_t>(data, expected).as_bool()) {
988 throw TLS_Exception(Alert::HandshakeFailure, "Server sent bad values for secure renegotiation");
989 }
990 }
991}
992
994 if(m_active_state.has_value()) {
995 return m_active_state->client_finished_verify_data();
996 }
997 return std::vector<uint8_t>();
998}
999
1001 if(m_active_state.has_value()) {
1002 return concat(m_active_state->client_finished_verify_data(), m_active_state->server_finished_verify_data());
1003 } else {
1004 return {};
1005 }
1006}
1007
1009 if(m_active_state.has_value()) {
1010 return m_active_state->server_supports_secure_renegotiation();
1011 }
1012
1013 if(const auto* pending = pending_state()) {
1014 if(const auto* hello = pending->server_hello()) {
1015 return hello->secure_renegotiation();
1016 }
1017 }
1018
1019 return false;
1020}
1021
1023 std::string_view context,
1024 size_t length) const {
1025 if(!m_active_state.has_value()) {
1026 throw Invalid_State("Channel_Impl_12::key_material_export connection not active");
1027 }
1028
1029 // A fatal alert should have already cleared the active state:
1030 BOTAN_ASSERT_NOMSG(!m_had_fatal_alert);
1031
1032 if(pending_state() != nullptr) {
1033 throw Invalid_State("Channel_Impl_12::key_material_export cannot export during renegotiation");
1034 }
1035
1036 auto prf = callbacks().tls12_protocol_specific_kdf(m_active_state->prf_algo());
1037
1038 const auto salt = [&] {
1039 if(context.empty()) {
1040 return concat(m_active_state->client_random(), m_active_state->server_random());
1041 } else {
1042 return concat(m_active_state->client_random(),
1043 m_active_state->server_random(),
1044 store_be(static_cast<uint16_t>(context.size())),
1045 as_span_of_bytes(context));
1046 }
1047 }();
1048
1049 return SymmetricKey(prf->derive_key(length, m_active_state->master_secret(), salt, as_span_of_bytes(label)));
1050}
1051
1052} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:114
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:101
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
bool is_valid() const
Definition tls_alert.h:78
std::vector< uint8_t > serialize() const
Definition tls_alert.cpp:32
bool is_fatal() const
Definition tls_alert.h:93
Type type() const
Definition tls_alert.h:100
virtual void tls_session_activated()
virtual std::unique_ptr< KDF > tls12_protocol_specific_kdf(std::string_view prf_algo) const
virtual void tls_record_received(uint64_t seq_no, std::span< const uint8_t > data)=0
virtual void tls_alert(Alert alert)=0
virtual uint64_t tls_current_monotonic_clock_ms()
virtual bool tls_peer_closed_connection()
virtual void tls_emit_data(std::span< const uint8_t > data)=0
RandomNumberGenerator & rng()
void change_cipher_spec_reader(Connection_Side side)
void update_traffic_keys(bool request_peer_update=false) override
std::vector< uint8_t > secure_renegotiation_data_for_server_hello() const
bool is_handshake_complete() const override
Handshake_State & create_handshake_state(Protocol_Version version, bool epoch0_restart=false)
size_t from_peer(std::span< const uint8_t > data) override
void secure_renegotiation_check(const Client_Hello_12 *client_hello)
Session_Manager & session_manager()
const Policy & policy() const
void send_alert(const Alert &alert) override
virtual void initiate_handshake(Handshake_State &state, bool force_full_renegotiation)=0
std::vector< X509_Certificate > peer_cert_chain() const override
void to_peer(std::span< const uint8_t > data) override
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
Channel_Impl_12(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< RandomNumberGenerator > &rng, const std::shared_ptr< const Policy > &policy, bool is_server, bool is_datagram, size_t io_buf_sz=TLS::Channel::IO_BUF_DEFAULT_SIZE)
SymmetricKey key_material_export(std::string_view label, std::string_view context, size_t length) const override
std::optional< std::string > external_psk_identity() const override
virtual std::unique_ptr< Handshake_State > new_handshake_state(std::unique_ptr< Handshake_IO > io)=0
std::optional< std::chrono::milliseconds > next_retransmission_timeout() const override
virtual void process_handshake_msg(Handshake_State &pending_state, Handshake_Type type, const std::vector< uint8_t > &contents, bool epoch0_restart)=0
bool secure_renegotiation_supported() const override
void renegotiate(bool force_full_renegotiation=false) override
virtual std::string application_protocol() const =0
void send_warning_alert(Alert::Type type)
void send_fatal_alert(Alert::Type type)
std::vector< uint8_t > renegotiation_info() const
virtual uint16_t current_read_epoch() const =0
virtual uint16_t current_write_epoch() const =0
virtual size_t dtls_maximum_timeout() const
virtual size_t dtls_default_mtu() const
virtual std::optional< size_t > dtls_maximum_retransmissions() const
virtual bool allow_dtls_epoch0_restart() const
virtual size_t dtls_initial_timeout() const
virtual bool allow_resumption_for_renegotiation() const
std::string to_string() const
uint8_t major_version() const
Definition tls_version.h:84
Protocol_Version version() const
Definition tls_record.h:93
Record_Type type() const
Definition tls_record.h:105
uint64_t sequence() const
Definition tls_record.h:98
size_t needed() const
Definition tls_record.h:91
uint16_t epoch() const
Definition tls_record.h:103
std::vector< uint8_t > renegotiation_info() const
virtual size_t remove(const Session_Handle &handle)=0
Alert::Type type() const
Definition tls_exceptn.h:21
constexpr CT::Mask< T > is_equal(const T x[], const T y[], size_t len)
Definition ct_utils.h:798
Record_Header read_record(bool is_datagram, secure_vector< uint8_t > &readbuf, const uint8_t input[], size_t input_len, size_t &consumed, secure_vector< uint8_t > &recbuf, Connection_Sequence_Numbers *sequence_numbers, const get_cipherstate_fn &get_cipherstate, bool allow_epoch0_restart)
@ MAX_PLAINTEXT_SIZE
Definition tls_magic.h:35
void write_unencrypted_record(secure_vector< uint8_t > &output, Record_Type record_type, Protocol_Version version, uint64_t record_sequence, const uint8_t *message, size_t message_len)
void write_record(secure_vector< uint8_t > &output, Record_Type record_type, Protocol_Version version, uint64_t record_sequence, const uint8_t *message, size_t message_len, Connection_Cipher_State &cs, RandomNumberGenerator &rng)
void map_remove_if(Pred pred, T &assoc)
Definition stl_util.h:54
OctetString SymmetricKey
Definition symkey.h:153
std::span< const uint8_t > as_span_of_bytes(const char *s, size_t len)
Definition mem_utils.h:59
constexpr auto concat(Rs &&... ranges)
Definition concat_util.h:90
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504