Botan 3.14.1
Crypto and TLS for C&
tls_record_layer_13.cpp
Go to the documentation of this file.
1/*
2* TLS record layer implementation for TLS 1.3
3* (C) 2022 Jack Lloyd
4* 2022 Hannes Rantzsch, René Meusel - neXenio GmbH
5* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#include <botan/internal/tls_record_layer_13.h>
11
12#include <botan/tls_alert.h>
13#include <botan/tls_exceptn.h>
14#include <botan/tls_policy.h>
15#include <botan/tls_version.h>
16#include <botan/internal/concat_util.h>
17#include <botan/internal/int_utils.h>
18#include <botan/internal/loadstor.h>
19#include <botan/internal/tls_cipher_state.h>
20#include <algorithm>
21
22namespace Botan::TLS {
23
24namespace {
25
26// RFC 9846 5.2
27// type: The TLSPlaintext.type value containing the content type of the record.
28constexpr uint16_t content_type_tag_length = 1;
29
30bool verify_change_cipher_spec(std::span<const uint8_t> data) {
31 // RFC 8446 5.
32 // An implementation may receive an unencrypted record of type
33 // change_cipher_spec consisting of the single byte value 0x01
34 // at any time [...]. An implementation which receives any other
35 // change_cipher_spec value or which receives a protected
36 // change_cipher_spec record MUST abort the handshake [...].
37 constexpr size_t expected_fragment_length = 1;
38 constexpr uint8_t expected_fragment_byte = 0x01;
39 return (data.size() == expected_fragment_length && data.front() == expected_fragment_byte);
40}
41
42} // namespace
43
45 m_outgoing_record_size_limit(MAX_PLAINTEXT_SIZE + content_type_tag_length),
46 m_incoming_record_size_limit(MAX_PLAINTEXT_SIZE + content_type_tag_length),
47
48 // RFC 8446 5.1
49 // legacy_record_version: MUST be set to 0x0303 for all records
50 // generated by a TLS 1.3 implementation other than an initial
51 // ClientHello [...], where it MAY also be 0x0301 for compatibility
52 // purposes.
53 //
54 // Additionally, older peers might send other values while requesting a
55 // protocol downgrade. I.e. we need to be able to tolerate/emit legacy
56 // values until we negotiated a TLS 1.3 compliant connection.
57 //
58 // As a client: we may initially emit the compatibility version and
59 // accept a wider range of incoming legacy record versions.
60 // As a server: we start with emitting the specified legacy version of 0x0303
61 // but must also allow a wider range of incoming legacy values.
62 //
63 // Once TLS 1.3 is negotiateed, the implementations will disable these
64 // compatibility modes accordingly or a protocol downgrade will transfer
65 // the marshalling responsibility to our TLS 1.2 implementation.
66 m_receiving_compat_mode(true) {}
67
68void Record_Layer::set_record_size_limits(const uint16_t outgoing_limit, const uint16_t incoming_limit) {
69 // RFC 8449 4.
70 // Endpoints MUST NOT send a "record_size_limit" extension with a value
71 // smaller than 64.
72 BOTAN_ARG_CHECK(outgoing_limit >= 64, "Invalid outgoing record size limit");
73 BOTAN_ARG_CHECK(incoming_limit >= 64 && incoming_limit <= MAX_PLAINTEXT_SIZE + content_type_tag_length,
74 "Invalid incoming record size limit");
75
76 // RFC 8449 4.
77 // Even if a larger record size limit is provided by a peer, an endpoint
78 // MUST NOT send records larger than the protocol-defined limit, unless
79 // explicitly allowed by a future TLS version or extension.
80 m_outgoing_record_size_limit =
81 std::min(outgoing_limit, static_cast<uint16_t>(MAX_PLAINTEXT_SIZE + content_type_tag_length));
82 m_incoming_record_size_limit = incoming_limit;
83}
84
86 // RFC 9846 5.1
87 // legacy_record_version: MUST be set to 0x0303 for all records
88 // generated by a TLS 1.3 implementation other than an initial
89 // ClientHello [...], where it MAY also be 0x0301 [...].
90 //
91 // A server never sends a ClientHello, so the sending compatibility mode
92 // is disabled at initialization for servers.
93 m_sending_compat_mode(side == Connection_Side::Client) {}
94
95void TLS_Record_Layer::copy_data(std::span<const uint8_t> data) {
96 while(!data.empty()) {
97 auto& record = [&]() -> Record_TLS& {
98 if(m_incoming_records.empty() || m_incoming_records.back().complete()) {
99 return m_incoming_records.emplace_back();
100 } else {
101 return m_incoming_records.back();
102 }
103 }();
104
105 BOTAN_DEBUG_ASSERT(!record.complete());
106 const size_t consumed = record.append(data);
107 BOTAN_ASSERT_NOMSG(consumed <= data.size());
108 data = data.subspan(consumed);
109 }
110}
111
113 Record_Type type,
114 std::span<const uint8_t> payload,
115 Cipher_State* cipher_state,
117 auto* cs = as_tls_cipher_state(cipher_state);
118
119 BOTAN_ARG_CHECK(payload.size() <= record_payload_size_limit(policy, cs),
120 "data size exceeds record payload size limit");
121
122 // RFC 9846 5.
123 // Note that [change_cipher_spec records] may appear at a point at the
124 // handshake where the implementation is expecting protected records.
125 //
126 // RFC 9846 5.
127 // An implementation which receives [...] a protected change_cipher_spec
128 // record MUST abort the handshake [...].
129 //
130 // ... hence, CHANGE_CIPHER_SPEC is never protected, even if a usable cipher
131 // state was passed to this method.
133 type == Record_Type::ChangeCipherSpec, cs == nullptr, "CHANGE_CIPHER_SPEC records must not be protected");
134
135 // RFC 9846 5.1
136 // Application Data messages are always protected.
138 cs != nullptr,
139 "Application Data records MUST NOT be written to the wire unprotected");
140
141 BOTAN_ARG_CHECK(type != Record_Type::ChangeCipherSpec || verify_change_cipher_spec(payload),
142 "TLS 1.3 deprecated CHANGE_CIPHER_SPEC");
143
144 // RFC 9846 5.1
145 // Implementations MUST NOT send zero-length fragments of Handshake types,
146 // even if those fragments contain padding. [...] a record with an Alert
147 // type MUST contain exactly one message. [...] Zero-length fragments of
148 // Application Data [...] MAY be sent, as they are potentially useful as a
149 // traffic analysis countermeasure.
150 BOTAN_ASSERT_IMPLICATION(payload.empty(),
152 "Zero-length fragments are only allowed for Application Data");
153
154 if(cs != nullptr) {
155 const size_t pt_size_with_type_tag = payload.size() + content_type_tag_length;
156 const size_t max_record_size = outgoing_record_size_limit();
157
158 // Don't even bother consulting the policy if we already filled the
159 // record fully, because then we can't add any padding anyway.
160 // If the user requests more padding than we can actually add, we will
161 // truncate the padding to fill up the record entirely.
162 const size_t padding_length =
163 (pt_size_with_type_tag < max_record_size)
164 ? std::min(policy.record_padding_bytes(pt_size_with_type_tag), max_record_size - pt_size_with_type_tag)
165 : 0;
166 BOTAN_ASSERT_NOMSG(pt_size_with_type_tag + padding_length <= max_record_size);
167
168 cs->protect_record(type, payload, padding_length, out);
169 } else {
170 // RFC 9846 5.1
171 // MUST be set to 0x0303 for all records generated by a TLS 1.3
172 // implementation other than an initial ClientHello [...], where
173 // it MAY also be 0x0301 for compatibility purposes.
174 const auto legacy_record_version = (m_sending_compat_mode) ? Protocol_Version::TLS_V10 //
175 : Protocol_Version::TLS_V12;
176
177 // RFC 9846 5.1
178 // type: The higher-level protocol used to process
179 // the enclosed fragment.
180 // legacy_record_version: [see above]
181 // length: The length (in bytes) of the following
182 // TLSPlaintext.fragment.
183 const auto header = Record_TLS::serialize_header(type, //
184 legacy_record_version, //
185 checked_cast_to<uint16_t>(payload.size()));
186
187 append(out, header);
188 append(out, payload);
189 }
190}
191
192uint16_t TLS_Record_Layer::record_payload_size_limit(const Policy& policy, Cipher_State* cipher_state) const {
193 BOTAN_UNUSED(policy); // not relevant for TLS
194
195 // RFC 8449 4.
196 // When the "record_size_limit" extension is negotiated, an endpoint
197 // MUST NOT generate a protected record with plaintext that is larger
198 // than the RecordSizeLimit value it receives from its peer.
199 // Unprotected messages are not subject to this limit.
200 //
201 // RFC 9846 5.4
202 // [T]he full encoded TLSInnerPlaintext MUST NOT exceed 2^14 + 1 octets.
203 // If the maximum fragment length is reduced -- as for example by the
204 // record_size_limit extension from RFC 8449 -- then the reduced limit
205 // applies to the full plaintext, including the content type and padding.
206 //
207 // Hence, this calculates the maximum amount of actual application data
208 // payload bytes that can be transferred in a single record (assuming no
209 // further padding is applied by the policy).
210 return (cipher_state != nullptr) ? outgoing_record_size_limit() - content_type_tag_length
211 : static_cast<uint16_t>(MAX_PLAINTEXT_SIZE);
212}
213
215 auto* cs = as_tls_cipher_state(cipher_state);
216
217 // Special case: on the record boundary we don't actually need any more data
218 // and we also don't want to be the know-it-all that now demands exactly
219 // enough bytes to start parsing the next record header.
220 if(m_incoming_records.empty()) {
221 return BytesNeeded(0);
222 }
223
224 if(!m_incoming_records.front().complete()) {
225 return m_incoming_records.front().missing_bytes_hint();
226 }
227
228 auto record = std::move(m_incoming_records.front());
229 m_incoming_records.pop_front();
230
231 // RFC 9846 Appendix E
232 // Prior versions of TLS used the record layer version number [...] for
233 // various purposes. As of TLS 1.3, this field is deprecated. The value
234 // [...] MAY be validated to match the fixed constant value.
235 //
236 // RFC 9846 5.1
237 // legacy_record_version: MUST be set to 0x0303 for all records generated
238 // by a TLS 1.3 implementation.
239 //
240 // If `receiving_compat_mode()` is true, we don't validate the legacy version
241 // and once it is disabled by the state-machine we enforce the specified
242 // fixed value of 0x0303 (TLS 1.2) for all incoming records.
243 if(!receiving_compat_mode() && record.legacy_version() != Protocol_Version::TLS_V12) {
244 throw TLS_Exception(Alert::IllegalParameter, "Received unexpected record version");
245 }
246
247 // After the key exchange phase of the handshake is completed and record protection is engaged,
248 // cipher_state is set. At this point, only protected traffic (and CCS) is allowed.
249 //
250 // RFC 9846 2.
251 // - Key Exchange: Establish shared keying material and select the
252 // cryptographic parameters. Everything after this phase is
253 // encrypted.
254 // RFC 9846 5.
255 // An implementation may receive an unencrypted [CCS] at any time
256 if(cs != nullptr && record.type() != Record_Type::ApplicationData &&
257 record.type() != Record_Type::ChangeCipherSpec &&
258 (!cs->must_expect_unprotected_alert_traffic() || record.type() != Record_Type::Alert)) {
259 throw TLS_Exception(Alert::UnexpectedMessage, "unprotected record received where protected traffic was expected");
260 }
261
262 if(record.type() == Record_Type::ChangeCipherSpec && !verify_change_cipher_spec(record.payload())) {
263 throw TLS_Exception(Alert::UnexpectedMessage, "malformed change cipher spec record received");
264 }
265
266 if(record.type() != Record_Type::ApplicationData) {
268 .type = record.type(),
269 .sequence_number = std::nullopt,
270 .payload = record.take_payload(),
271 }));
272 } else {
273 if(cs == nullptr) {
274 // This could also mean a misuse of the interface, i.e. failing to
275 // provide a valid cipher_state to parse_records when receiving valid
276 // (encrypted) Application Data.
277 throw TLS_Exception(Alert::UnexpectedMessage, "premature Application Data received");
278 }
279
280 return generalize_to<ReadResult>(cs->deprotect_record(std::move(record), incoming_record_size_limit()));
281 }
282}
283
285 m_incoming_records.clear();
286}
287
288} // namespace Botan::TLS
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:108
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
virtual size_t record_padding_bytes(size_t plaintext_bytes) const
uint16_t outgoing_record_size_limit() const noexcept
void set_record_size_limits(uint16_t outgoing_limit, uint16_t incoming_limit)
variant_append_t< Record, BytesNeeded > ReadResult
uint16_t incoming_record_size_limit() const noexcept
bool receiving_compat_mode() const noexcept
static std::array< uint8_t, TLS_HEADER_SIZE > serialize_header(Record_Type type, Protocol_Version legacy_version, uint16_t payload_length)
TLS_Record_Layer(Connection_Side side)
void prepare_record(const Policy &policy, Record_Type type, std::span< const uint8_t > payload, Cipher_State *cipher_state, secure_vector< uint8_t > &out) override
void copy_data(std::span< const uint8_t > data) override
uint16_t record_payload_size_limit(const Policy &policy, Cipher_State *cipher_state=nullptr) const override
ReadResult next_record(Cipher_State *cipher_state=nullptr) override
TLS_Cipher_State * as_tls_cipher_state(Cipher_State *cs)
size_t BytesNeeded
@ MAX_PLAINTEXT_SIZE
Definition tls_magic.h:37
Record annotate_record_type(Record_Content &&record)
constexpr RT checked_cast_to(AT i)
Definition int_utils.h:104
void append(std::vector< T, Alloc > &out, std::type_identity_t< std::span< const T > > in)
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
constexpr GeneralVariantT generalize_to(SpecialT &&specific)
Converts a given variant into another variant-ish whose type states are a super set of the given vari...
Definition stl_util.h:88