Botan 3.14.1
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>
74bool absorb_malformed_input_errors(bool absorb, F fn) {
75 try {
76 fn();
77 return false;
78 } catch(const TLS_Exception&) {
79 if(!absorb) {
80 throw;
81 }
82 } catch(const Decoding_Error&) {
83 if(!absorb) {
84 throw;
85 }
86 }
87 return true;
88}
89
90} // namespace
91
92Channel_Impl_12::Channel_Impl_12(const std::shared_ptr<Callbacks>& callbacks,
93 const std::shared_ptr<Session_Manager>& session_manager,
94 const std::shared_ptr<RandomNumberGenerator>& rng,
95 const std::shared_ptr<const Policy>& policy,
96 bool is_server,
98 size_t reserved_io_buffer_size) :
99 m_is_server(is_server),
100 m_flavor(flavor),
101 m_callbacks(callbacks),
102 m_session_manager(session_manager),
103 m_policy(policy),
104 m_rng(rng),
105 m_has_been_closed(false) {
106 BOTAN_ASSERT_NONNULL(m_callbacks);
107 BOTAN_ASSERT_NONNULL(m_session_manager);
109 BOTAN_ASSERT_NONNULL(m_policy);
110
111 /* epoch 0 is plaintext, thus null cipher state */
112 m_write_cipher_states[0] = nullptr;
113 m_read_cipher_states[0] = {};
114
115 m_writebuf.reserve(reserved_io_buffer_size);
116 m_readbuf.reserve(reserved_io_buffer_size);
117}
118
119void Channel_Impl_12::reset_state() {
120 m_active_state.reset();
121 m_pending_state.reset();
122 m_epochs_before_latest_renegotiation.reset();
123 m_dtls_pending_is_epoch0_restart = false;
124 m_resumption_handle.reset();
125 m_readbuf.clear();
126 m_write_cipher_states.clear();
127 m_read_cipher_states.clear();
128}
129
130void Channel_Impl_12::note_resumption_handle(std::optional<Session_Handle> handle) {
131 m_resumption_handle = std::move(handle);
132}
133
134std::vector<Session_Handle> Channel_Impl_12::take_sessions_to_invalidate() {
135 // A ticket-backed session is not cached under the ServerHello session ID, so
136 // both handles have to be collected.
137 std::vector<Session_Handle> handles;
138
139 if(m_resumption_handle.has_value()) {
140 handles.push_back(m_resumption_handle.value());
141 m_resumption_handle.reset();
142 }
143
144 if(m_active_state.has_value()) {
145 const auto& sid = m_active_state->session_id();
146 if(!sid.empty()) {
147 handles.emplace_back(sid);
148 }
149 }
150
151 return handles;
152}
153
154void Channel_Impl_12::invalidate_sessions(const std::vector<Session_Handle>& handles) {
155 // RFC 5246 7.2.2: "Servers and clients MUST forget any session-identifiers,
156 // keys, and secrets associated with a failed connection. Thus, any
157 // connection terminated with a fatal alert MUST NOT be resumed."
158 //
159 // Best effort, and deliberately last: remove() reaches application-supplied
160 // storage and can throw, and by then the keys are already gone. Letting a
161 // failed cache eviction abort the teardown would leave the channel usable
162 // after a security-fatal event, which is the worse of the two outcomes. A
163 // stateless ticket issuer has nothing to remove and cannot revoke what it
164 // already handed out.
165 for(const auto& handle : handles) {
166 try {
167 session_manager().remove(handle);
168 } catch(...) {}
169 }
170}
171
173 // This operation only makes sense for DTLS
175 m_active_state.reset();
176 // With the old association gone the restart is an ordinary handshake, whose
177 // failure must be reported rather than rolled back
178 m_dtls_pending_is_epoch0_restart = false;
179 m_read_cipher_states.clear();
180 m_write_cipher_states.clear();
181
182 m_write_cipher_states[0] = nullptr;
183 m_read_cipher_states[0] = {};
184
185 if(m_sequence_numbers) {
186 m_sequence_numbers->reset(); // NOLINT(*-ambiguous-smartptr-reset-call)
187 }
188}
189
191
192Connection_Sequence_Numbers& Channel_Impl_12::sequence_numbers() const {
193 BOTAN_ASSERT(m_sequence_numbers, "Have a sequence numbers object");
194 return *m_sequence_numbers;
195}
196
197std::shared_ptr<Connection_Cipher_State> Channel_Impl_12::read_cipher_state_epoch(uint16_t epoch) const {
198 const auto i = m_read_cipher_states.find(epoch);
199 if(i == m_read_cipher_states.end()) {
200 throw Internal_Error("TLS::Channel_Impl_12 No read cipherstate for epoch " + std::to_string(epoch));
201 }
202
203 // RFC 6347 4.1: "In general, implementations SHOULD discard packets from
204 // earlier epochs, but if packet loss causes noticeable problems they MAY
205 // choose to retain keying material from previous epochs for up to the
206 // default MSL specified for TCP [TCP] to allow for packet reordering."
207 // read_dtls_record drops the record when this throws.
208 if(const auto& retired_at = i->second.retired_at; retired_at.has_value()) {
209 const auto now = callbacks().tls_current_monotonic_clock_ms();
210 const auto retired = retired_at.value();
211 BOTAN_ASSERT_NOMSG(now >= retired);
212 if(now - retired > TCP_MSL_MS) {
213 throw Invalid_State("TLS::Channel_Impl_12 Read cipherstate for epoch " + std::to_string(epoch) +
214 " is past its retention window");
215 }
216 }
217
218 return i->second.state;
219}
220
221std::shared_ptr<Connection_Cipher_State> Channel_Impl_12::write_cipher_state_epoch(uint16_t epoch) const {
222 const auto i = m_write_cipher_states.find(epoch);
223 if(i == m_write_cipher_states.end()) {
224 throw Internal_Error("TLS::Channel_Impl_12 No write cipherstate for epoch " + std::to_string(epoch));
225 }
226 return i->second;
227}
228
229std::vector<X509_Certificate> Channel_Impl_12::peer_cert_chain() const {
230 if(m_active_state.has_value()) {
231 return m_active_state->peer_certs();
232 }
233 return std::vector<X509_Certificate>();
234}
235
236std::optional<std::string> Channel_Impl_12::external_psk_identity() const {
237 if(m_active_state.has_value()) {
238 return m_active_state->psk_identity();
239 }
240 if(const auto* state = pending_state()) {
241 return state->psk_identity();
242 }
243 return std::nullopt;
244}
245
247 bool epoch0_restart,
248 std::optional<uint64_t> read_sequence_number,
249 std::optional<uint64_t> write_sequence_number) {
250 if(pending_state() != nullptr) {
251 throw Internal_Error("create_handshake_state called during handshake");
252 }
253
254 if(m_active_state.has_value()) {
255 const Protocol_Version active_version = m_active_state->version();
256
257 if(active_version.is_datagram_protocol() != version.is_datagram_protocol()) {
258 throw TLS_Exception(Alert::ProtocolVersion,
259 "Active state using version " + active_version.to_string() + " cannot change to " +
260 version.to_string() + " in pending");
261 }
262 }
263
264 if(!m_sequence_numbers) {
265 if(version.is_datagram_protocol()) {
266 m_sequence_numbers = std::make_unique<Datagram_Sequence_Numbers>(read_sequence_number.value_or(0),
267 write_sequence_number.value_or(0));
268 } else {
269 BOTAN_ARG_CHECK(!read_sequence_number.has_value() && !write_sequence_number.has_value(),
270 "TLS does not support externally provided sequence numbers");
271 m_sequence_numbers = std::make_unique<Stream_Sequence_Numbers>();
272 }
273 }
274
275 // Read epochs at or below this one belong to the association already in place,
276 // so application data under them stays deliverable while this handshake runs.
277 // Anything above it is this handshake's own, unauthenticated until its
278 // Finished. See the application-data gate in from_peer.
279 m_epochs_before_latest_renegotiation = Epochs_Before_Latest_Renegotiation{sequence_numbers().current_read_epoch(),
280 sequence_numbers().current_write_epoch()};
281
282 // Floor for the pending handshake's reassembly: a delayed record from the
283 // handshake arrives under a lower epoch and must be rejected. It would
284 // otherwise take the sequence slot the real message needs.
285 //
286 // Zero on an epoch-zero restart, because there the peer legitimately
287 // begins again at epoch zero and the floor would reject it. This is keyed
288 // on the restart actually occurring, not on the policy allowing it: an
289 // ordinary renegotiation needs the floor either way.
290 const uint16_t initial_epoch = epoch0_restart ? 0 : m_epochs_before_latest_renegotiation->read_epoch;
291
292 using namespace std::placeholders;
293
294 std::unique_ptr<Handshake_IO> io;
295 if(version.is_datagram_protocol()) {
296 const size_t policy_mtu = policy().dtls_default_mtu();
297 if(policy_mtu > 0xFFFF) {
298 throw Invalid_Argument("Policy specifies a DTLS MTU larger than 65535");
299 }
300 const uint16_t mtu = static_cast<uint16_t>(policy_mtu);
301
302 const size_t initial_timeout_ms = policy().dtls_initial_timeout();
303 const size_t max_timeout_ms = policy().dtls_maximum_timeout();
304 // A zero timeout would cause retransmissions without any backoff
305 if(initial_timeout_ms == 0 || max_timeout_ms < initial_timeout_ms) {
306 throw Invalid_Argument("Policy specifies invalid DTLS retransmission timeouts");
307 }
308 const std::optional<size_t> max_retransmissions = policy().dtls_maximum_retransmissions();
309
310 const auto send_record_f = [this](uint16_t epoch, Record_Type record_type, const std::vector<uint8_t>& record) {
311 send_record_under_epoch(epoch, record_type, record);
312 };
313 const auto clock_f = [this]() { return callbacks().tls_current_monotonic_clock_ms(); };
314 io = std::make_unique<Datagram_Handshake_IO>(send_record_f,
315 clock_f,
316 sequence_numbers(),
317 mtu,
318 initial_timeout_ms,
319 max_timeout_ms,
320 max_retransmissions,
321 policy().maximum_handshake_message_size(),
322 m_is_server,
323 initial_epoch);
324 } else {
325 const auto send_record_f = [this](Record_Type rec_type, const std::vector<uint8_t>& record) {
326 send_record(rec_type, record);
327 };
328 io = std::make_unique<Stream_Handshake_IO>(send_record_f);
329 }
330
331 m_pending_state = new_handshake_state(std::move(io));
332
333 if(m_active_state.has_value()) {
334 m_pending_state->set_version(m_active_state->version());
335 }
336
337 return *m_pending_state;
338}
339
340bool Channel_Impl_12::pending_handshake_epochs_unmoved() const {
341 // Nothing pending: there is nothing to act on, and the epoch markers are
342 // unset, so the comparison would be meaningless.
343 if(!m_pending_state || !m_epochs_before_latest_renegotiation.has_value()) {
344 return true;
345 }
346
347 // Before either ChangeCipherSpec the established association still owns both
348 // epochs, so dropping the pending handshake leaves it exactly as it was.
349 return sequence_numbers().current_read_epoch() == m_epochs_before_latest_renegotiation->read_epoch &&
350 sequence_numbers().current_write_epoch() == m_epochs_before_latest_renegotiation->write_epoch;
351}
352
353void Channel_Impl_12::clear_pending_handshake_state() {
354 m_pending_state.reset();
355 m_epochs_before_latest_renegotiation.reset();
356 m_dtls_pending_is_epoch0_restart = false;
357}
358
359/*
360* The retransmission budget is exhausted and this handshake will not complete.
361* Leaving the pending state installed makes every later timeout_check throw
362* again from unchanged state, and blocks renegotiate(), so the channel can
363* neither recover nor be retried.
364*/
365void Channel_Impl_12::abandon_timed_out_handshake() {
366 if(m_active_state.has_value() && pending_handshake_epochs_unmoved()) {
367 // A renegotiation that never reached its ChangeCipherSpec. The
368 // established association is untouched, so keep it and let the
369 // application try again.
370 clear_pending_handshake_state();
371 } else {
372 // Either there is no established association to fall back to, or a
373 // ChangeCipherSpec has already moved an epoch and there is no rollback
374 // that would leave keys, identity and sequence numbers describing the
375 // same handshake. Close.
376 m_has_been_closed = true;
377 reset_state();
378 }
379}
380
382 if(m_flavor == TLS_Flavor::DTLS && !m_has_been_closed && m_pending_state) {
383 try {
384 return m_pending_state->handshake_io().timeout_check();
385 } catch(const TLS_Exception&) {
386 abandon_timed_out_handshake();
387 throw;
388 }
389 }
390
391 // Old cipher states are pruned at install time (see prune_old_cipher_states),
392 // so no periodic cleanup is needed here.
393 return false;
394}
395
397 auto next_timeout = next_retransmission_timeout();
398
399 // If there is no timeout, the handshake is complete or there is no handshake
400 // in progress, so there is nothing to arm a timer for.
401 if(!next_timeout.has_value()) {
402 return;
403 }
404
405 // If a new timer generation was requested, we increment the channel-wide
406 // generation counter to invalidate any other timer chain that might still be
407 // running from a backoff interval that has been cut short by incoming data
408 // from the peer.
409 if(generation_policy == TimerGeneration::Advance) {
410 ++m_retransmission_timer_generation;
411 }
412
413 // The actual asynchronous operation:
414 const auto on_timer = [self = weak_from_this(), generation = m_retransmission_timer_generation]() mutable {
415 // If this operation is called after the channel implementation is gone,
416 // the channel magically became some other type, or the operation was
417 // called more than once (see below) just return.
418 const auto channel = std::dynamic_pointer_cast<Channel_Impl_12>(self.lock());
419 if(!channel) {
420 return;
421 }
422
423 // Drop the reference to the channel in this deferred operation. If the
424 // user accidentally calls the operation more than once, the second
425 // invocation will be a harmless no-op.
426 self.reset();
427
428 // This timer-chain may have been superseded by a newer one, when a
429 // backoff interval was reset by the arrival of a belated handshake
430 // message. This generation is no longer active and ends here.
431 if(generation != channel->m_retransmission_timer_generation) {
432 return;
433 }
434
435 // Now we know that we're on the active retransmission/backoff
436 // chain...
437 if(channel->timeout_check()) {
438 // ... and a retransmission was performed: Spawn the next timer
439 // generation for the next backoff interval in this chain.
440 channel->maybe_arm_dtls_retransmission_timer(TimerGeneration::Advance);
441 } else {
442 // ... but no retransmission was performed. Probably, because the
443 // operation was invoked too-early. Re-spawn this generation's
444 // timer for the remaining time until the next deadline.
445 channel->maybe_arm_dtls_retransmission_timer(TimerGeneration::Keep);
446 }
447 };
448
449 m_callbacks->tls_register_deferred_operation(next_timeout->count(), on_timer);
450}
451
452void Channel_Impl_12::renegotiate(bool force_full_renegotiation) {
453 if(pending_state() != nullptr) { // currently in handshake?
454 return;
455 }
456
457 if(m_active_state.has_value()) {
458 // A handshake consumes one read and one write epoch. Refuse here if
459 // either is spent, so the caller learns before the handshake tears the
460 // working connection down partway through. See next_epoch().
461 if(sequence_numbers().current_read_epoch() == 0xFFFF || sequence_numbers().current_write_epoch() == 0xFFFF) {
462 throw Invalid_State("TLS epoch counter exhausted, a new connection is required");
463 }
464
465 if(!secure_renegotiation_supported() && !policy().allow_insecure_renegotiation()) {
466 throw Invalid_State("Peer does not support secure renegotiation and policy prohibits insecure renegotiation");
467 }
468
469 if(!force_full_renegotiation) {
470 force_full_renegotiation = !policy().allow_resumption_for_renegotiation();
471 }
472
473 initiate_handshake(create_handshake_state(m_active_state->version()), force_full_renegotiation);
474 } else {
475 throw Invalid_State("Cannot renegotiate on inactive connection");
476 }
477}
478
479void Channel_Impl_12::update_traffic_keys(bool /*update_requested*/) {
480 throw Invalid_Argument("cannot update traffic keys on a TLS 1.2 channel");
481}
482
484 const auto* pending = pending_state();
485
486 BOTAN_ASSERT(pending && pending->has_server_hello(), "Have received server hello");
487
488 if(pending->server_hello().compression_method() != 0) {
489 throw Internal_Error("Negotiated unknown compression algorithm");
490 }
491
492 sequence_numbers().new_read_cipher_state();
493
494 const uint16_t epoch = sequence_numbers().current_read_epoch();
495
496 BOTAN_ASSERT(!m_read_cipher_states.contains(epoch), "No read cipher state currently set for next epoch");
497
498 // flip side as we are reading
499 const auto read_state = std::make_shared<Connection_Cipher_State>(
500 pending->version(),
502 false,
503 pending->ciphersuite(),
504 pending->session_keys(),
505 pending->server_hello().supports_encrypt_then_mac());
506
507 // The epoch we just left is retained only to absorb reordering, so start its
508 // clock now (see read_cipher_state_epoch). Epoch 0 is the plaintext
509 // placeholder and holds no keys, so the window does not apply to it.
510 if(m_flavor == TLS_Flavor::DTLS && epoch > 1) {
511 if(const auto prev = m_read_cipher_states.find(static_cast<uint16_t>(epoch - 1));
512 prev != m_read_cipher_states.end()) {
513 prev->second.retired_at = callbacks().tls_current_monotonic_clock_ms();
514 }
515 }
516
517 m_read_cipher_states[epoch] = Retained_Read_Cipher_State{.state = read_state, .retired_at = std::nullopt};
518 prune_old_cipher_states(m_read_cipher_states);
519}
520
522 const auto* pending = pending_state();
523
524 BOTAN_ASSERT(pending && pending->has_server_hello(), "Have received server hello");
525
526 if(pending->server_hello().compression_method() != 0) {
527 throw Internal_Error("Negotiated unknown compression algorithm");
528 }
529
530 sequence_numbers().new_write_cipher_state();
531
532 const uint16_t epoch = sequence_numbers().current_write_epoch();
533
534 BOTAN_ASSERT(!m_write_cipher_states.contains(epoch), "No write cipher state currently set for next epoch");
535
536 const auto write_state =
537 std::make_shared<Connection_Cipher_State>(pending->version(),
538 side,
539 true,
540 pending->ciphersuite(),
541 pending->session_keys(),
542 pending->server_hello().supports_encrypt_then_mac());
543
544 m_write_cipher_states[epoch] = write_state;
545 prune_old_cipher_states(m_write_cipher_states);
546}
547
549 return m_active_state.has_value();
550}
551
553 return !is_closed() && is_handshake_complete();
554}
555
556std::optional<std::chrono::milliseconds> Channel_Impl_12::next_retransmission_timeout() const {
557 if(m_flavor == TLS_Flavor::DTLS && !m_has_been_closed && m_pending_state) {
558 return m_pending_state->handshake_io().next_retransmission_timeout();
559 }
560
561 return std::nullopt;
562}
563
565 return m_has_been_closed;
566}
567
569 BOTAN_ASSERT_NONNULL(m_pending_state);
570
571 const auto& state = *m_pending_state;
572
573 if(!state.version().is_datagram_protocol()) {
574 // TLS is easy just remove all but the current state
575 const uint16_t current_epoch = sequence_numbers().current_write_epoch();
576
577 const auto not_current_epoch = [current_epoch](uint16_t epoch) { return (epoch != current_epoch); };
578
579 map_remove_if(not_current_epoch, m_write_cipher_states);
580 map_remove_if(not_current_epoch, m_read_cipher_states);
581 }
582
583 // RFC 6347 4.2.4: "the node that transmits the last flight (the server in an
584 // ordinary handshake or the client in a resumed handshake) MUST respond to a
585 // retransmit of the peer's last flight with a retransmit of the last
586 // flight." Both endpoints retain handshake sequence state, but only that
587 // node replays its outgoing flight.
588 const bool sent_terminal_dtls_flight =
589 (m_flavor == TLS_Flavor::DTLS) && (m_is_server == state.has_server_hello_done());
590
591 const bool encrypt_then_mac_used = m_active_state.has_value() && m_active_state->encrypt_then_mac_used();
592
593 if(m_flavor == TLS_Flavor::DTLS) {
594 m_active_state =
595 Active_Connection_State_12(state, negotiated_application_protocol(), m_pending_state->take_handshake_io());
596 if(auto* dtls_io = m_active_state->dtls_handshake_io()) {
597 // Retain receive sequence state on both endpoints to distinguish a
598 // retransmission from an unexpected new handshake message. Only the
599 // terminal-flight sender responds by replaying its final flight.
600 dtls_io->finalize_handshake(sent_terminal_dtls_flight);
601 }
602 } else {
604 }
605
606 if(encrypt_then_mac_used) {
607 m_active_state->note_encrypt_then_mac_used();
608 }
609
610 clear_pending_handshake_state();
611
613}
614
615size_t Channel_Impl_12::from_peer(std::span<const uint8_t> data) {
616 const bool allow_epoch0_restart = (m_flavor == TLS_Flavor::DTLS) && dtls_epoch0_restart_enabled();
617
618 const auto* input = data.data();
619 auto input_size = data.size();
620
621 try {
622 while(input_size > 0) {
623 // A fatal alert destroys the cipher states, so nothing further can even
624 // be decrypted. Closure by close_notify is different: the responding
625 // close_notify still has to be read, so those records keep flowing
626 // through the loop and are filtered per record type below.
627 if(m_had_fatal_alert) {
628 return 0;
629 }
630
631 size_t consumed = 0;
632
633 const auto get_epoch = [this](uint16_t epoch) { return read_cipher_state_epoch(epoch); };
634
635 const Record_Header record = read_record(m_flavor,
636 m_readbuf,
637 input,
638 input_size,
639 consumed,
640 m_record_buf,
641 m_sequence_numbers.get(),
642 get_epoch,
643 allow_epoch0_restart);
644
645 const size_t needed = record.needed();
646
647 BOTAN_ASSERT(consumed > 0, "Got to eat something");
648
649 BOTAN_ASSERT(consumed <= input_size, "Record reader consumed sane amount");
650
651 input += consumed;
652 input_size -= consumed;
653
654 BOTAN_ASSERT(input_size == 0 || needed == 0, "Got a full record or consumed all input");
655
656 if(input_size == 0 && needed != 0) {
657 return needed; // need more data to complete record
658 }
659
660 // Ignore invalid records in DTLS
661 if(m_flavor == TLS_Flavor::DTLS && record.type() == Record_Type::Invalid) {
662 continue;
663 }
664
665 const bool old_unprotected_record = m_flavor == TLS_Flavor::DTLS && record.epoch() == 0 &&
666 m_active_state.has_value() && sequence_numbers().current_read_epoch() > 0;
667
668 // Once encrypted traffic is expected, epoch-zero records are
669 // unauthenticated. Only handshake records can be useful as part of a
670 // retransmitted flight or an explicitly allowed association restart.
671 if(old_unprotected_record && record.type() != Record_Type::Handshake &&
673 continue;
674 }
675
676 if(m_record_buf.size() > MAX_PLAINTEXT_SIZE) {
677 if(old_unprotected_record) {
678 continue;
679 }
680
681 throw TLS_Exception(Alert::RecordOverflow, "TLS plaintext record is larger than allowed maximum");
682 }
683
684 const bool epoch0_restart = allow_epoch0_restart && record.epoch() == 0 && m_active_state.has_value();
685 BOTAN_ASSERT_IMPLICATION(epoch0_restart, allow_epoch0_restart, "Allowed state");
686
687 const bool initial_record = epoch0_restart || (pending_state() == nullptr && !m_active_state.has_value());
688 bool initial_handshake_message = false;
689 if(record.type() == Record_Type::Handshake && !m_record_buf.empty()) {
690 const Handshake_Type type = static_cast<Handshake_Type>(m_record_buf[0]);
691 initial_handshake_message = (type == Handshake_Type::ClientHello);
692 }
693
694 if(record.type() != Record_Type::Alert && !old_unprotected_record) {
695 if(initial_record) {
696 // For initial records just check for basic sanity
697 if(record.version().major_version() != 3 && record.version().major_version() != 0xFE) {
698 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version in initial record");
699 }
700 } else if(const auto* pending = pending_state()) {
701 if(pending->has_server_hello() && !initial_handshake_message && record.version() != pending->version()) {
702 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version");
703 }
704 } else if(m_active_state.has_value()) {
705 if(record.version() != m_active_state->version() && !initial_handshake_message) {
706 throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version");
707 }
708 }
709 }
710
711 // RFC 5246 7.2.1: "Any data received after a closure alert is ignored."
712 // This is about a closure alert the peer sent us. A peer that keeps
713 // talking after *our* close_notify is a different case, kept as an
714 // error below; BoGo's Shutdown-Shim-ApplicationData requires it.
715 if(m_peer_closed_connection && record.type() != Record_Type::Alert) {
716 continue;
717 }
718
719 // An off-path attacker can forge DTLS epoch-zero records, so they
720 // must neither trip nor reset the limit on useless records
721 const bool counts_for_useless_records = (m_flavor != TLS_Flavor::DTLS || record.epoch() > 0);
722
723 if(record.type() == Record_Type::Handshake || record.type() == Record_Type::ChangeCipherSpec) {
724 if(m_has_been_closed) {
725 throw TLS_Exception(Alert::UnexpectedMessage, "Received handshake data after connection closure");
726 }
727 if(counts_for_useless_records) {
728 if(m_record_buf.empty()) {
730 } else {
732 }
733 }
734 process_handshake_ccs(m_record_buf, record.sequence(), record.type(), record.version(), epoch0_restart);
735 } else if(record.type() == Record_Type::ApplicationData) {
736 if(m_has_been_closed) {
737 throw TLS_Exception(Alert::UnexpectedMessage, "Received application data after connection closure");
738 }
739 if(pending_state() != nullptr) {
740 /*
741 What matters is which epoch the record belongs to, not which role we
742 are playing.
743
744 RFC 6347 4.2.4: "Implementations MUST either discard or buffer all
745 application data packets for the new epoch until they have received
746 the Finished message for that epoch." Data under the epoch this
747 handshake installed is not authenticated until its Finished, so it
748 must not reach the application; equally it is not an error, because
749 ordinary reordering produces it whenever a peer writes immediately
750 after activating.
751
752 Data under an epoch the established association owns stays valid
753 while a renegotiation is in flight, per 4.1.
754
755 Epoch zero is neither: application data there is plaintext, so it is
756 never legitimate and no association is at stake.
757 */
758 if(m_flavor == TLS_Flavor::DTLS && record.epoch() > 0) {
759 const uint16_t active_epoch =
760 m_epochs_before_latest_renegotiation ? m_epochs_before_latest_renegotiation->read_epoch : 0;
761
762 if(!m_active_state.has_value() || record.epoch() > active_epoch) {
763 continue; // this handshake's epoch, still unauthenticated
764 }
765 } else {
766 throw TLS_Exception(Alert::UnexpectedMessage, "Can't interleave application and handshake data");
767 }
768 }
769 process_application_data(record.sequence(), m_record_buf);
770 } else if(record.type() == Record_Type::Alert) {
771 process_alert(m_record_buf, counts_for_useless_records);
772 } else if(record.type() != Record_Type::Invalid) {
773 throw Unexpected_Message("Unexpected record type " + std::to_string(static_cast<size_t>(record.type())) +
774 " from counterparty");
775 }
776 }
777
778 return 0; // on a record boundary
779 } catch(TLS_Exception& e) {
781 throw;
783 send_fatal_alert(Alert::BadRecordMac);
784 throw;
785 } catch(Decoding_Error&) {
786 send_fatal_alert(Alert::DecodeError);
787 throw;
788 } catch(...) {
789 send_fatal_alert(Alert::InternalError);
790 throw;
791 }
792}
793
794void Channel_Impl_12::process_handshake_ccs(const secure_vector<uint8_t>& record,
795 uint64_t record_sequence,
796 Record_Type record_type,
797 Protocol_Version record_version,
798 bool epoch0_restart) {
799 const auto process_retransmitted_record = [&] {
800 BOTAN_ASSERT(m_active_state.has_value(), "Have active DTLS association for retransmission");
801 BOTAN_ASSERT_NONNULL(m_active_state->dtls_handshake_io());
802 // Epoch-zero records are unauthenticated and may be spoofed, so a
803 // malformed one must not tear down an established association.
804 const bool unauthenticated = (record_sequence >> 48) == 0;
805
806 absorb_malformed_input_errors(unauthenticated, [&] {
807 m_active_state->dtls_handshake_io()->add_retransmitted_record(
808 record.data(), record.size(), record_type, record_sequence);
809 });
810 };
811
812 const bool no_pending_at_entry = !m_pending_state;
813
814 if(!m_pending_state) {
815 // With no pending handshake this is either a new handshake attempt or a
816 // DTLS retransmission from the previous handshake. The latter must not
817 // create fresh pending state; it only asks us to replay our last flight.
818 if(epoch0_restart && m_sequence_numbers && m_active_state.has_value()) {
819 const bool starts_new_handshake = is_new_dtls_association_client_hello(record, record_type);
820
821 if(!starts_new_handshake) {
822 process_retransmitted_record();
823 return;
824 }
825 }
826
827 if(m_flavor == TLS_Flavor::DTLS && !epoch0_restart) {
828 if(m_sequence_numbers) {
829 const uint16_t epoch = record_sequence >> 48;
830 const uint16_t current_epoch = sequence_numbers().current_read_epoch();
831 if(epoch == current_epoch) {
832 // Either endpoint can initiate renegotiation from FINISHED:
833 // clients send ClientHello, servers send HelloRequest.
834 const bool starts_new_handshake =
835 (record_type == Record_Type::Handshake && !record.empty() &&
836 (static_cast<Handshake_Type>(record[0]) == Handshake_Type::ClientHello ||
837 static_cast<Handshake_Type>(record[0]) == Handshake_Type::HelloRequest));
838
839 if(m_active_state.has_value() && !starts_new_handshake) {
840 process_retransmitted_record();
841 } else {
842 create_handshake_state(record_version, epoch0_restart);
843 }
844 } else if(current_epoch > 0 && epoch == current_epoch - 1) {
845 process_retransmitted_record();
846 }
847 } else {
848 create_handshake_state(record_version, epoch0_restart);
849 }
850 } else {
851 create_handshake_state(record_version, epoch0_restart);
852 }
853 }
854
855 // A handshake created just now from an epoch-zero record while an association
856 // is live is a restart; remember that, so its failure rolls back to the live
857 // association instead of tearing it down, and so a stray epoch-zero record
858 // arriving later against an unrelated pending handshake (a renegotiation) is
859 // not mistaken for one. A pending state that already existed is untouched: a
860 // restart's own cookie-bearing ClientHello arrives while it is set.
861 if(no_pending_at_entry && m_pending_state) {
862 m_dtls_pending_is_epoch0_restart = epoch0_restart;
863 }
864
865 // May have been created in above conditional
866 if(m_pending_state) {
867 // An epoch-zero record is unauthenticated. Once an association is
868 // established, one arriving during a pending renegotiation must not be
869 // able to destroy it, exactly as for the no-pending-handshake path above.
870 // Without this a single forged CCS or handshake fragment tore down the
871 // active association and the renegotiation along with it.
872 //
873 // Delivery is inside the guard as well as reassembly. A bare 12-byte
874 // header declaring a zero-length message reassembles cleanly and only
875 // fails when the message itself is parsed or dispatched, which reaches
876 // the same teardown by a later route.
877 const bool unauthenticated_against_active_association =
878 (m_flavor == TLS_Flavor::DTLS) && (record_sequence >> 48) == 0 && m_active_state.has_value();
879
880 const bool absorbed = absorb_malformed_input_errors(unauthenticated_against_active_association, [&] {
881 m_pending_state->handshake_io().add_record(record.data(), record.size(), record_type, record_sequence);
882
883 while(auto* pending = m_pending_state.get()) {
884 const auto msg = pending->get_next_handshake_msg(policy().maximum_handshake_message_size());
885
886 if(msg.first == Handshake_Type::None) { // no full handshake yet
887 break;
888 }
889
890 process_handshake_msg(*pending, msg.first, msg.second, epoch0_restart);
891
892 if(!m_pending_state) {
893 break;
894 }
895 }
896 });
897
898 // A restart's ClientHello authenticates through its cookie, but the checks
899 // after it (choosing a ciphersuite, for one) can still fail on input the
900 // peer controls. Until the restart commits by discarding the old
901 // association, a failure rolls the pending state back: the association
902 // stays live and untouched, and a handshake begun by a forged record
903 // cannot block a genuine restart for as long as the association exists.
904 if(absorbed && m_dtls_pending_is_epoch0_restart) {
905 clear_pending_handshake_state();
906 }
907 }
908}
909
910void Channel_Impl_12::process_application_data(uint64_t seq_no, const secure_vector<uint8_t>& record) {
911 if(!m_active_state.has_value()) {
912 throw Unexpected_Message("Application data before handshake done");
913 }
914
915 // ApplicationData must arrive under a non-zero read epoch
916 const uint16_t read_epoch =
917 (m_flavor == TLS_Flavor::DTLS) ? static_cast<uint16_t>(seq_no >> 48) : sequence_numbers().current_read_epoch();
918 if(read_epoch == 0) {
919 throw Unexpected_Message("Application data received in unexpected read epoch");
920 }
921
922 if(record.empty()) {
924 } else {
926 }
927
928 callbacks().tls_record_received(seq_no, record);
929}
930
931void Channel_Impl_12::process_alert(const secure_vector<uint8_t>& record, bool counts_for_useless_records) {
932 const Alert alert_msg(record);
933
934 if(counts_for_useless_records && !alert_msg.is_fatal() && alert_msg.type() != Alert::CloseNotify) {
936 }
937
938 // RFC 5246 7.2.2:
939 // no_renegotiation
940 // Sent by the client in response to a hello request or by the
941 // server in response to a client hello after initial handshaking.
942 //
943 // Both of those precede any ChangeCipherSpec from the refusing side, so a
944 // refusal arriving after one means the peer both refused the handshake and
945 // proceeded with it. Discarding the pending state is what implements the
946 // refusal, but past a CCS that state is the only thing keeping application
947 // data under the new, un-Finished keys from being delivered, and there is no
948 // rollback that would leave keys, identity and exporter describing the same
949 // handshake. End the association rather than open that gate.
950 if(alert_msg.type() == Alert::NoRenegotiation && m_active_state.has_value()) {
951 if(!pending_handshake_epochs_unmoved()) {
952 throw TLS_Exception(Alert::UnexpectedMessage, "Received no_renegotiation after ChangeCipherSpec");
953 }
954
955 clear_pending_handshake_state();
956 }
957
958 if(alert_msg.is_fatal()) {
959 // RFC 5246 7.2.2: "Upon transmission or receipt of a fatal alert message,
960 // both parties immediately close the connection."
961 //
962 // The teardown completes before the application hears about the alert, so
963 // the callback cannot reach the connection or its secrets. Same order as
964 // the TLS 1.3 channel.
965 m_has_been_closed = true;
966 m_had_fatal_alert = true;
967 const auto invalidated = take_sessions_to_invalidate();
968 reset_state();
969 invalidate_sessions(invalidated);
970 }
971
972 callbacks().tls_alert(alert_msg);
973
974 if(alert_msg.type() == Alert::CloseNotify) {
975 m_peer_closed_connection = true;
976
977 // TLS 1.2 requires us to immediately react with our "close_notify",
978 // the return value of the application's callback has no effect on that.
980 send_warning_alert(Alert::CloseNotify); // reply in kind
981 }
982
983 if(alert_msg.type() == Alert::CloseNotify || alert_msg.is_fatal()) {
984 m_has_been_closed = true;
985 }
986}
987
988void Channel_Impl_12::write_record(Connection_Cipher_State* cipher_state,
989 uint16_t epoch,
990 Record_Type record_type,
991 const uint8_t input[],
992 size_t length) {
993 BOTAN_ASSERT(m_pending_state || m_active_state.has_value(), "Some connection state exists");
994
995 const Protocol_Version record_version = (m_pending_state) ? (m_pending_state->version()) : m_active_state->version();
996
997 const uint64_t next_seq = sequence_numbers().next_write_sequence(epoch);
998
999 if(cipher_state == nullptr) {
1000 TLS::write_unencrypted_record(m_writebuf, record_type, record_version, next_seq, input, length);
1001 } else {
1002 TLS::write_record(m_writebuf, record_type, record_version, next_seq, input, length, *cipher_state, rng());
1003 }
1004
1005 callbacks().tls_emit_data(m_writebuf);
1006}
1007
1008void Channel_Impl_12::send_record_array(uint16_t epoch, Record_Type type, const uint8_t input[], size_t length) {
1009 if(length == 0) {
1010 return;
1011 }
1012
1013 const auto cipher_state = write_cipher_state_epoch(epoch);
1014
1015 while(length > 0) {
1016 const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
1017 write_record(cipher_state.get(), epoch, type, input, sending);
1018
1019 input += sending;
1020 length -= sending;
1021 }
1022}
1023
1024void Channel_Impl_12::send_record(Record_Type record_type, const std::vector<uint8_t>& record) {
1025 send_record_array(sequence_numbers().current_write_epoch(), record_type, record.data(), record.size());
1026}
1027
1028void Channel_Impl_12::send_record_under_epoch(uint16_t epoch,
1029 Record_Type record_type,
1030 const std::vector<uint8_t>& record) {
1031 send_record_array(epoch, record_type, record.data(), record.size());
1032}
1033
1034void Channel_Impl_12::to_peer(std::span<const uint8_t> data) {
1035 if(!is_active()) {
1036 throw Invalid_State("Data cannot be sent on inactive TLS connection");
1037 }
1038
1039 send_record_array(sequence_numbers().current_write_epoch(), Record_Type::ApplicationData, data.data(), data.size());
1040}
1041
1043 const bool ready_to_send_anything = !is_closed() && m_sequence_numbers;
1044 if(alert.is_valid() && ready_to_send_anything) {
1045 try {
1046 send_record(Record_Type::Alert, alert.serialize());
1047 } catch(...) { /* swallow it */
1048 }
1049 }
1050
1051 // RFC 5246 7.2.2:
1052 // no_renegotiation
1053 // Sent by the client in response to a hello request or by the
1054 // server in response to a client hello after initial handshaking.
1055 //
1056 // In this case we are the peer sending the refusal, so there is no reason
1057 // for our epochs to have moved. If they somehow did, clear the pending
1058 // state. A strictly better approach here would be to simply throw
1059 // Internal_Error, but send_alert is called from within catch handlers
1060 // so this is not currently viable.
1061 if(alert.type() == Alert::NoRenegotiation && m_active_state.has_value()) {
1062 if(pending_handshake_epochs_unmoved()) {
1063 clear_pending_handshake_state();
1064 }
1065 }
1066
1067 if(alert.is_fatal()) {
1068 // Order matters: the channel is made unusable and its secrets destroyed
1069 // before any application-supplied storage is touched, so a throwing
1070 // session manager cannot leave is_active() true with live keys.
1071 m_had_fatal_alert = true;
1072 m_has_been_closed = true;
1073
1074 // Alert::None is the local teardown that is never sent to the peer, used
1075 // where the trigger was unauthenticated input or a local timeout. Evicting
1076 // the resumption state on that basis would hand anyone able to reach the
1077 // address the ability to destroy it, which is what keeping the teardown
1078 // local exists to prevent.
1079 const auto invalidated =
1080 (alert.type() == Alert::None) ? std::vector<Session_Handle>() : take_sessions_to_invalidate();
1081
1082 reset_state();
1083 invalidate_sessions(invalidated);
1084 }
1085
1086 if(alert.type() == Alert::CloseNotify || alert.is_fatal()) {
1087 m_has_been_closed = true;
1088 }
1089}
1090
1091void Channel_Impl_12::secure_renegotiation_check(const Client_Hello_12* client_hello, bool fresh_handshake_mode) {
1092 BOTAN_ASSERT_NONNULL(client_hello);
1093 const bool secure_renegotiation = client_hello->secure_renegotiation();
1094
1095 if(!fresh_handshake_mode && m_active_state &&
1096 m_active_state->client_supports_secure_renegotiation() != secure_renegotiation) {
1097 throw TLS_Exception(Alert::HandshakeFailure, "Client changed its mind about secure renegotiation");
1098 }
1099
1100 if(secure_renegotiation) {
1101 const std::vector<uint8_t>& data = client_hello->renegotiation_info();
1102
1103 const auto expected =
1104 fresh_handshake_mode ? std::vector<uint8_t>() : secure_renegotiation_data_for_client_hello();
1105 if(!CT::is_equal<uint8_t>(data, expected).as_bool()) {
1106 throw TLS_Exception(Alert::HandshakeFailure, "Client sent bad values for secure renegotiation");
1107 }
1108 }
1109}
1110
1112 BOTAN_ASSERT_NONNULL(server_hello);
1113 const bool secure_renegotiation = server_hello->secure_renegotiation();
1114
1115 if(m_active_state && m_active_state->server_supports_secure_renegotiation() != secure_renegotiation) {
1116 throw TLS_Exception(Alert::HandshakeFailure, "Server changed its mind about secure renegotiation");
1117 }
1118
1119 if(secure_renegotiation) {
1120 const std::vector<uint8_t>& data = server_hello->renegotiation_info();
1121
1122 const auto expected = secure_renegotiation_data_for_server_hello();
1123 if(!CT::is_equal<uint8_t>(data, expected).as_bool()) {
1124 throw TLS_Exception(Alert::HandshakeFailure, "Server sent bad values for secure renegotiation");
1125 }
1126 }
1127
1128 // RFC 7366 3.1
1129 // implementations MUST NOT renegotiate a downgrade from
1130 // encrypt-then-MAC to MAC-then-encrypt.
1131 //
1132 // Note that these rules apply across potentially many rehandshakes.
1133 if(m_active_state && m_active_state->encrypt_then_mac_used() && !server_hello->supports_encrypt_then_mac()) {
1134 const auto suite = Ciphersuite::by_id(server_hello->ciphersuite());
1135 if(suite.has_value() && suite->cbc_ciphersuite()) {
1136 throw TLS_Exception(Alert::HandshakeFailure, "Renegotiation would downgrade from encrypt-then-MAC");
1137 }
1138 }
1139}
1140
1142 if(m_active_state.has_value()) {
1143 return m_active_state->client_finished_verify_data();
1144 }
1145 return std::vector<uint8_t>();
1146}
1147
1149 if(m_active_state.has_value()) {
1150 return concat(m_active_state->client_finished_verify_data(), m_active_state->server_finished_verify_data());
1151 } else {
1152 return {};
1153 }
1154}
1155
1157 if(m_active_state.has_value()) {
1158 return m_active_state->server_supports_secure_renegotiation();
1159 }
1160
1161 if(const auto* pending = pending_state()) {
1162 if(const auto* hello = pending->maybe_server_hello()) {
1163 return hello->secure_renegotiation();
1164 }
1165 }
1166
1167 return false;
1168}
1169
1171 std::string_view context,
1172 size_t length) const {
1173 if(!m_active_state.has_value()) {
1174 throw Invalid_State("Channel_Impl_12::key_material_export connection not active");
1175 }
1176
1177 // A fatal alert should have already cleared the active state:
1178 BOTAN_ASSERT_NOMSG(!m_had_fatal_alert);
1179
1180 if(pending_state() != nullptr) {
1181 throw Invalid_State("Channel_Impl_12::key_material_export cannot export during renegotiation");
1182 }
1183
1184 // RFC 7627 5.4
1185 // If a client or server chooses to continue with a full handshake
1186 // without the extended master secret extension, then the new session
1187 // becomes vulnerable to the man-in-the-middle key synchronization
1188 // attack described in Section 1. Hence, the client or server MUST NOT
1189 // export any key material based on the new master secret for any
1190 // subsequent application-level authentication. In particular, it MUST
1191 // disable [RFC5705] [...]
1192 if(!m_active_state->supports_extended_master_secret()) {
1193 throw Invalid_State("Channel_Impl_12::key_material_export requires the extended master secret");
1194 }
1195
1196 // RFC 5705 4.
1197 // The context value length is encoded as an unsigned, 16-bit quantity
1198 if(context.size() > 0xFFFF) {
1199 throw Invalid_Argument("Channel_Impl_12::key_material_export context is too long");
1200 }
1201
1202 auto prf = callbacks().tls12_protocol_specific_kdf(m_active_state->prf_algo());
1203
1204 const auto salt = [&] {
1205 if(context.empty()) {
1206 return concat(m_active_state->client_random(), m_active_state->server_random());
1207 } else {
1208 return concat(m_active_state->client_random(),
1209 m_active_state->server_random(),
1210 store_be(static_cast<uint16_t>(context.size())),
1211 as_span_of_bytes(context));
1212 }
1213 }();
1214
1215 return SymmetricKey(prf->derive_key(length, m_active_state->master_secret(), salt, as_span_of_bytes(label)));
1216}
1217
1218} // 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
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
bool is_valid() const
Definition tls_alert.h:79
std::vector< uint8_t > serialize() const
Definition tls_alert.cpp:32
bool is_fatal() const
Definition tls_alert.h:98
Type type() const
Definition tls_alert.h:105
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 maybe_arm_dtls_retransmission_timer(TimerGeneration generation_policy=TimerGeneration::Advance)
virtual std::string negotiated_application_protocol() const =0
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
virtual bool dtls_epoch0_restart_enabled() const
size_t from_peer(std::span< const uint8_t > data) override
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, TLS_Flavor flavor, size_t io_buf_sz=TLS::Channel::IO_BUF_DEFAULT_SIZE)
Session_Manager & session_manager()
Handshake_State & create_handshake_state(Protocol_Version version, bool epoch0_restart=false, std::optional< uint64_t > read_sequence_number=std::nullopt, std::optional< uint64_t > write_sequence_number=std::nullopt)
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
void secure_renegotiation_check(const Client_Hello_12 *client_hello, bool fresh_handshake_mode=false)
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
void send_warning_alert(Alert::Type type)
void send_fatal_alert(Alert::Type type)
void note_useless_record(const Policy &policy)
static std::optional< Ciphersuite > by_id(uint16_t suite)
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 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:88
Protocol_Version version() const
Definition tls_record.h:119
Record_Type type() const
Definition tls_record.h:131
uint64_t sequence() const
Definition tls_record.h:124
uint16_t epoch() const
Definition tls_record.h:129
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:803
@ MAX_PLAINTEXT_SIZE
Definition tls_magic.h:37
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)
Record_Header read_record(TLS_Flavor flavor, 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)
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:95
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