Coverage Report

Created: 2024-11-29 06:10

/src/botan/src/lib/tls/tls12/tls_record.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* TLS Record Handling
3
* (C) 2012,2013,2014,2015,2016,2019 Jack Lloyd
4
*     2016 Juraj Somorovsky
5
*     2016 Matthias Gierlings
6
*
7
* Botan is released under the Simplified BSD License (see license.txt)
8
*/
9
10
#include <botan/internal/tls_record.h>
11
12
#include <botan/rng.h>
13
#include <botan/tls_callbacks.h>
14
#include <botan/tls_ciphersuite.h>
15
#include <botan/tls_exceptn.h>
16
#include <botan/internal/ct_utils.h>
17
#include <botan/internal/loadstor.h>
18
#include <botan/internal/tls_seq_numbers.h>
19
#include <botan/internal/tls_session_key.h>
20
#include <sstream>
21
22
#if defined(BOTAN_HAS_TLS_CBC)
23
   #include <botan/internal/tls_cbc.h>
24
#endif
25
26
namespace Botan::TLS {
27
28
Connection_Cipher_State::Connection_Cipher_State(Protocol_Version version,
29
                                                 Connection_Side side,
30
                                                 bool our_side,
31
                                                 const Ciphersuite& suite,
32
                                                 const Session_Keys& keys,
33
388
                                                 bool uses_encrypt_then_mac) {
34
388
   m_nonce_format = suite.nonce_format();
35
388
   m_nonce_bytes_from_record = suite.nonce_bytes_from_record(version);
36
388
   m_nonce_bytes_from_handshake = suite.nonce_bytes_from_handshake();
37
38
388
   const secure_vector<uint8_t>& aead_key = keys.aead_key(side);
39
388
   m_nonce = keys.nonce(side);
40
41
388
   BOTAN_ASSERT_NOMSG(m_nonce.size() == m_nonce_bytes_from_handshake);
42
43
388
   if(nonce_format() == Nonce_Format::CBC_MODE) {
44
88
#if defined(BOTAN_HAS_TLS_CBC)
45
      // legacy CBC+HMAC mode
46
88
      auto mac = MessageAuthenticationCode::create_or_throw("HMAC(" + suite.mac_algo() + ")");
47
88
      auto cipher = BlockCipher::create_or_throw(suite.cipher_algo());
48
49
88
      if(our_side) {
50
13
         m_aead = std::make_unique<TLS_CBC_HMAC_AEAD_Encryption>(std::move(cipher),
51
13
                                                                 std::move(mac),
52
13
                                                                 suite.cipher_keylen(),
53
13
                                                                 suite.mac_keylen(),
54
13
                                                                 version,
55
13
                                                                 uses_encrypt_then_mac);
56
75
      } else {
57
75
         m_aead = std::make_unique<TLS_CBC_HMAC_AEAD_Decryption>(std::move(cipher),
58
75
                                                                 std::move(mac),
59
75
                                                                 suite.cipher_keylen(),
60
75
                                                                 suite.mac_keylen(),
61
75
                                                                 version,
62
75
                                                                 uses_encrypt_then_mac);
63
75
      }
64
65
#else
66
      BOTAN_UNUSED(uses_encrypt_then_mac);
67
      throw Internal_Error("Negotiated disabled TLS CBC+HMAC ciphersuite");
68
#endif
69
300
   } else {
70
300
      m_aead =
71
300
         AEAD_Mode::create_or_throw(suite.cipher_algo(), our_side ? Cipher_Dir::Encryption : Cipher_Dir::Decryption);
72
300
   }
73
74
388
   m_aead->set_key(aead_key);
75
388
}
76
77
141
std::vector<uint8_t> Connection_Cipher_State::aead_nonce(uint64_t seq, RandomNumberGenerator& rng) {
78
141
   switch(m_nonce_format) {
79
22
      case Nonce_Format::CBC_MODE: {
80
22
         if(!m_nonce.empty()) {
81
13
            std::vector<uint8_t> nonce;
82
13
            nonce.swap(m_nonce);
83
13
            return nonce;
84
13
         }
85
9
         std::vector<uint8_t> nonce(nonce_bytes_from_record());
86
9
         rng.randomize(nonce.data(), nonce.size());
87
9
         return nonce;
88
22
      }
89
0
      case Nonce_Format::AEAD_XOR_12: {
90
0
         std::vector<uint8_t> nonce(12);
91
0
         store_be(seq, nonce.data() + 4);
92
0
         xor_buf(nonce, m_nonce.data(), m_nonce.size());
93
0
         return nonce;
94
22
      }
95
119
      case Nonce_Format::AEAD_IMPLICIT_4: {
96
119
         BOTAN_ASSERT_NOMSG(m_nonce.size() == 4);
97
119
         std::vector<uint8_t> nonce(12);
98
119
         copy_mem(&nonce[0], m_nonce.data(), 4);
99
119
         store_be(seq, &nonce[nonce_bytes_from_handshake()]);
100
119
         return nonce;
101
22
      }
102
141
   }
103
104
0
   throw Invalid_State("Unknown nonce format specified");
105
141
}
106
107
237
std::vector<uint8_t> Connection_Cipher_State::aead_nonce(const uint8_t record[], size_t record_len, uint64_t seq) {
108
237
   switch(m_nonce_format) {
109
58
      case Nonce_Format::CBC_MODE: {
110
58
         if(nonce_bytes_from_record() == 0 && !m_nonce.empty()) {
111
0
            std::vector<uint8_t> nonce;
112
0
            nonce.swap(m_nonce);
113
0
            return nonce;
114
0
         }
115
58
         if(record_len < nonce_bytes_from_record()) {
116
1
            throw Decoding_Error("Invalid CBC packet too short to be valid");
117
1
         }
118
57
         std::vector<uint8_t> nonce(record, record + nonce_bytes_from_record());
119
57
         return nonce;
120
58
      }
121
31
      case Nonce_Format::AEAD_XOR_12: {
122
31
         std::vector<uint8_t> nonce(12);
123
31
         store_be(seq, nonce.data() + 4);
124
31
         xor_buf(nonce, m_nonce.data(), m_nonce.size());
125
31
         return nonce;
126
58
      }
127
148
      case Nonce_Format::AEAD_IMPLICIT_4: {
128
148
         BOTAN_ASSERT_NOMSG(m_nonce.size() == 4);
129
148
         if(record_len < nonce_bytes_from_record()) {
130
2
            throw Decoding_Error("Invalid AEAD packet too short to be valid");
131
2
         }
132
146
         std::vector<uint8_t> nonce(12);
133
146
         copy_mem(&nonce[0], m_nonce.data(), 4);
134
146
         copy_mem(&nonce[nonce_bytes_from_handshake()], record, nonce_bytes_from_record());
135
146
         return nonce;
136
148
      }
137
237
   }
138
139
0
   throw Invalid_State("Unknown nonce format specified");
140
237
}
141
142
std::vector<uint8_t> Connection_Cipher_State::format_ad(uint64_t msg_sequence,
143
                                                        Record_Type msg_type,
144
                                                        Protocol_Version version,
145
372
                                                        uint16_t msg_length) {
146
372
   std::vector<uint8_t> ad(13);
147
148
372
   store_be(msg_sequence, &ad[0]);
149
372
   ad[8] = static_cast<uint8_t>(msg_type);
150
372
   ad[9] = version.major_version();
151
372
   ad[10] = version.minor_version();
152
372
   ad[11] = get_byte<0>(msg_length);
153
372
   ad[12] = get_byte<1>(msg_length);
154
155
372
   return ad;
156
372
}
157
158
namespace {
159
160
67.8k
inline void append_u16_len(secure_vector<uint8_t>& output, size_t len_field) {
161
67.8k
   const uint16_t len16 = static_cast<uint16_t>(len_field);
162
67.8k
   BOTAN_ASSERT_EQUAL(len_field, len16, "No truncation");
163
67.8k
   output.push_back(get_byte<0>(len16));
164
67.8k
   output.push_back(get_byte<1>(len16));
165
67.8k
}
166
167
void write_record_header(secure_vector<uint8_t>& output,
168
                         Record_Type record_type,
169
                         Protocol_Version version,
170
67.8k
                         uint64_t record_sequence) {
171
67.8k
   output.clear();
172
173
67.8k
   output.push_back(static_cast<uint8_t>(record_type));
174
67.8k
   output.push_back(version.major_version());
175
67.8k
   output.push_back(version.minor_version());
176
177
67.8k
   if(version.is_datagram_protocol()) {
178
63.7k
      for(size_t i = 0; i != 8; ++i) {
179
56.6k
         output.push_back(get_byte_var(i, record_sequence));
180
56.6k
      }
181
7.08k
   }
182
67.8k
}
183
184
}  // namespace
185
186
void write_unencrypted_record(secure_vector<uint8_t>& output,
187
                              Record_Type record_type,
188
                              Protocol_Version version,
189
                              uint64_t record_sequence,
190
                              const uint8_t* message,
191
67.6k
                              size_t message_len) {
192
67.6k
   if(record_type == Record_Type::ApplicationData) {
193
0
      throw Internal_Error("Writing an unencrypted TLS application data record");
194
0
   }
195
67.6k
   write_record_header(output, record_type, version, record_sequence);
196
67.6k
   append_u16_len(output, message_len);
197
67.6k
   output.insert(output.end(), message, message + message_len);
198
67.6k
}
199
200
void write_record(secure_vector<uint8_t>& output,
201
                  Record_Type record_type,
202
                  Protocol_Version version,
203
                  uint64_t record_sequence,
204
                  const uint8_t* message,
205
                  size_t message_len,
206
                  Connection_Cipher_State& cs,
207
141
                  RandomNumberGenerator& rng) {
208
141
   write_record_header(output, record_type, version, record_sequence);
209
210
141
   AEAD_Mode& aead = cs.aead();
211
141
   std::vector<uint8_t> aad = cs.format_ad(record_sequence, record_type, version, static_cast<uint16_t>(message_len));
212
213
141
   const size_t ctext_size = aead.output_length(message_len);
214
215
141
   const size_t rec_size = ctext_size + cs.nonce_bytes_from_record();
216
217
141
   aead.set_associated_data(aad);
218
219
141
   const std::vector<uint8_t> nonce = cs.aead_nonce(record_sequence, rng);
220
221
141
   append_u16_len(output, rec_size);
222
223
141
   if(cs.nonce_bytes_from_record() > 0) {
224
141
      if(cs.nonce_format() == Nonce_Format::CBC_MODE) {
225
22
         output += nonce;
226
119
      } else {
227
119
         output += std::make_pair(&nonce[cs.nonce_bytes_from_handshake()], cs.nonce_bytes_from_record());
228
119
      }
229
141
   }
230
231
141
   const size_t header_size = output.size();
232
141
   output += std::make_pair(message, message_len);
233
234
141
   aead.start(nonce);
235
141
   aead.finish(output, header_size);
236
237
141
   BOTAN_ASSERT(output.size() < MAX_CIPHERTEXT_SIZE, "Produced ciphertext larger than protocol allows");
238
141
}
239
240
namespace {
241
242
size_t fill_buffer_to(
243
128k
   secure_vector<uint8_t>& readbuf, const uint8_t*& input, size_t& input_size, size_t& input_consumed, size_t desired) {
244
128k
   if(readbuf.size() >= desired) {
245
710
      return 0;  // already have it
246
710
   }
247
248
127k
   const size_t taken = std::min(input_size, desired - readbuf.size());
249
250
127k
   readbuf.insert(readbuf.end(), input, input + taken);
251
127k
   input_consumed += taken;
252
127k
   input_size -= taken;
253
127k
   input += taken;
254
255
127k
   return (desired - readbuf.size());  // how many bytes do we still need?
256
128k
}
257
258
void decrypt_record(secure_vector<uint8_t>& output,
259
                    uint8_t record_contents[],
260
                    size_t record_len,
261
                    uint64_t record_sequence,
262
                    Protocol_Version record_version,
263
                    Record_Type record_type,
264
237
                    Connection_Cipher_State& cs) {
265
237
   AEAD_Mode& aead = cs.aead();
266
267
237
   const std::vector<uint8_t> nonce = cs.aead_nonce(record_contents, record_len, record_sequence);
268
237
   const uint8_t* msg = &record_contents[cs.nonce_bytes_from_record()];
269
237
   const size_t msg_length = record_len - cs.nonce_bytes_from_record();
270
271
   /*
272
   * This early rejection is based just on public information (length of the
273
   * encrypted packet) and so does not leak any information. We used to use
274
   * decode_error here which really is more appropriate, but that confuses some
275
   * tools which are attempting automated detection of padding oracles,
276
   * including older versions of TLS-Attacker.
277
   */
278
237
   if(msg_length < aead.minimum_final_size()) {
279
3
      throw TLS_Exception(Alert::BadRecordMac, "AEAD packet is shorter than the tag");
280
3
   }
281
282
234
   const size_t ptext_size = aead.output_length(msg_length);
283
284
234
   aead.set_associated_data(
285
234
      cs.format_ad(record_sequence, record_type, record_version, static_cast<uint16_t>(ptext_size)));
286
287
234
   aead.start(nonce);
288
289
234
   output.assign(msg, msg + msg_length);
290
234
   aead.finish(output, 0);
291
234
}
292
293
Record_Header read_tls_record(secure_vector<uint8_t>& readbuf,
294
                              const uint8_t input[],
295
                              size_t input_len,
296
                              size_t& consumed,
297
                              secure_vector<uint8_t>& recbuf,
298
                              Connection_Sequence_Numbers* sequence_numbers,
299
62.5k
                              const get_cipherstate_fn& get_cipherstate) {
300
62.5k
   if(readbuf.size() < TLS_HEADER_SIZE) {
301
      // header incomplete
302
62.5k
      if(size_t needed = fill_buffer_to(readbuf, input, input_len, consumed, TLS_HEADER_SIZE)) {
303
170
         return Record_Header(needed);
304
170
      }
305
306
62.3k
      BOTAN_ASSERT_EQUAL(readbuf.size(), TLS_HEADER_SIZE, "Have an entire header");
307
62.3k
   }
308
309
   /*
310
   Verify that the record type and record version are within some expected
311
   range, so we can quickly reject totally invalid packets.
312
313
   The version check is a little hacky but given how TLS 1.3 versioning works
314
   this is probably safe
315
316
   - The first byte is the record version which in TLS 1.2 is always in [20..23)
317
   - The second byte is the TLS major version which is effectively fossilized at 3
318
   - The third byte is the TLS minor version which (due to TLS 1.3 versioning changes)
319
     will never be more than 3 (signifying TLS 1.2)
320
   */
321
62.3k
   const bool bad_record_type = readbuf[0] < 20 || readbuf[0] > 23;
322
62.3k
   const bool bad_record_version = readbuf[1] != 3 || readbuf[2] >= 4;
323
324
62.3k
   if(bad_record_type || bad_record_version) {
325
      // We know we read up to at least the 5 byte TLS header
326
271
      const std::string first5 = std::string(reinterpret_cast<const char*>(readbuf.data()), 5);
327
328
271
      if(first5 == "GET /" || first5 == "PUT /" || first5 == "POST " || first5 == "HEAD ") {
329
11
         throw TLS_Exception(Alert::ProtocolVersion, "Client sent plaintext HTTP request instead of TLS handshake");
330
11
      }
331
332
260
      if(first5 == "CONNE") {
333
2
         throw TLS_Exception(Alert::ProtocolVersion,
334
2
                             "Client sent plaintext HTTP proxy CONNECT request instead of TLS handshake");
335
2
      }
336
337
258
      if(bad_record_type) {
338
         // RFC 5246 Section 6.
339
         //   If a TLS implementation receives an unexpected record type, it MUST
340
         //   send an unexpected_message alert.
341
213
         throw TLS_Exception(Alert::UnexpectedMessage, "TLS record type had unexpected value");
342
213
      }
343
45
      throw TLS_Exception(Alert::ProtocolVersion, "TLS record version had unexpected value");
344
258
   }
345
346
62.0k
   const Protocol_Version version(readbuf[1], readbuf[2]);
347
348
62.0k
   if(version.is_datagram_protocol()) {
349
0
      throw TLS_Exception(Alert::ProtocolVersion, "Expected TLS but got a record with DTLS version");
350
0
   }
351
352
62.0k
   const size_t record_size = make_uint16(readbuf[TLS_HEADER_SIZE - 2], readbuf[TLS_HEADER_SIZE - 1]);
353
354
62.0k
   if(record_size > MAX_CIPHERTEXT_SIZE) {
355
10
      throw TLS_Exception(Alert::RecordOverflow, "Received a record that exceeds maximum size");
356
10
   }
357
358
62.0k
   if(record_size == 0) {
359
16
      throw TLS_Exception(Alert::DecodeError, "Received a completely empty record");
360
16
   }
361
362
62.0k
   if(size_t needed = fill_buffer_to(readbuf, input, input_len, consumed, TLS_HEADER_SIZE + record_size)) {
363
201
      return Record_Header(needed);
364
201
   }
365
366
61.8k
   BOTAN_ASSERT_EQUAL(static_cast<size_t>(TLS_HEADER_SIZE) + record_size, readbuf.size(), "Have the full record");
367
368
61.8k
   const Record_Type type = static_cast<Record_Type>(readbuf[0]);
369
370
61.8k
   uint16_t epoch = 0;
371
372
61.8k
   uint64_t sequence = 0;
373
61.8k
   if(sequence_numbers) {
374
56.7k
      sequence = sequence_numbers->next_read_sequence();
375
56.7k
      epoch = sequence_numbers->current_read_epoch();
376
56.7k
   } else {
377
      // server initial handshake case
378
5.11k
      epoch = 0;
379
5.11k
   }
380
381
61.8k
   if(epoch == 0) {
382
      // Unencrypted initial handshake
383
61.5k
      recbuf.assign(readbuf.begin() + TLS_HEADER_SIZE, readbuf.begin() + TLS_HEADER_SIZE + record_size);
384
61.5k
      readbuf.clear();
385
61.5k
      return Record_Header(sequence, version, type);
386
61.5k
   }
387
388
   // Otherwise, decrypt, check MAC, return plaintext
389
237
   auto cs = get_cipherstate(epoch);
390
391
237
   BOTAN_ASSERT(cs, "Have cipherstate for this epoch");
392
393
237
   decrypt_record(recbuf, &readbuf[TLS_HEADER_SIZE], record_size, sequence, version, type, *cs);
394
395
237
   if(sequence_numbers) {
396
0
      sequence_numbers->read_accept(sequence);
397
0
   }
398
399
237
   readbuf.clear();
400
237
   return Record_Header(sequence, version, type);
401
61.8k
}
402
403
Record_Header read_dtls_record(secure_vector<uint8_t>& readbuf,
404
                               const uint8_t input[],
405
                               size_t input_len,
406
                               size_t& consumed,
407
                               secure_vector<uint8_t>& recbuf,
408
                               Connection_Sequence_Numbers* sequence_numbers,
409
                               const get_cipherstate_fn& get_cipherstate,
410
1.81k
                               bool allow_epoch0_restart) {
411
1.81k
   if(readbuf.size() < DTLS_HEADER_SIZE) {
412
      // header incomplete
413
1.81k
      if(fill_buffer_to(readbuf, input, input_len, consumed, DTLS_HEADER_SIZE)) {
414
20
         readbuf.clear();
415
20
         return Record_Header(0);
416
20
      }
417
418
1.79k
      BOTAN_ASSERT_EQUAL(readbuf.size(), DTLS_HEADER_SIZE, "Have an entire header");
419
1.79k
   }
420
421
1.79k
   const Protocol_Version version(readbuf[1], readbuf[2]);
422
423
1.79k
   if(version.is_datagram_protocol() == false) {
424
14
      readbuf.clear();
425
14
      return Record_Header(0);
426
14
   }
427
428
1.78k
   const size_t record_size = make_uint16(readbuf[DTLS_HEADER_SIZE - 2], readbuf[DTLS_HEADER_SIZE - 1]);
429
430
1.78k
   if(record_size > MAX_CIPHERTEXT_SIZE) {
431
      // Too large to be valid, ignore it
432
3
      readbuf.clear();
433
3
      return Record_Header(0);
434
3
   }
435
436
1.77k
   if(fill_buffer_to(readbuf, input, input_len, consumed, DTLS_HEADER_SIZE + record_size)) {
437
      // Truncated packet?
438
35
      readbuf.clear();
439
35
      return Record_Header(0);
440
35
   }
441
442
1.74k
   BOTAN_ASSERT_EQUAL(static_cast<size_t>(DTLS_HEADER_SIZE) + record_size, readbuf.size(), "Have the full record");
443
444
1.74k
   const Record_Type type = static_cast<Record_Type>(readbuf[0]);
445
446
1.74k
   const uint64_t sequence = load_be<uint64_t>(&readbuf[3], 0);
447
1.74k
   const uint16_t epoch = (sequence >> 48);
448
449
1.74k
   const bool already_seen = sequence_numbers && sequence_numbers->already_seen(sequence);
450
451
1.74k
   if(already_seen && !(epoch == 0 && allow_epoch0_restart)) {
452
79
      readbuf.clear();
453
79
      return Record_Header(0);
454
79
   }
455
456
1.66k
   if(epoch == 0) {
457
      // Unencrypted initial handshake
458
1.56k
      recbuf.assign(readbuf.begin() + DTLS_HEADER_SIZE, readbuf.begin() + DTLS_HEADER_SIZE + record_size);
459
1.56k
      readbuf.clear();
460
1.56k
      if(sequence_numbers) {
461
370
         sequence_numbers->read_accept(sequence);
462
370
      }
463
1.56k
      return Record_Header(sequence, version, type);
464
1.56k
   }
465
466
97
   try {
467
      // Otherwise, decrypt, check MAC, return plaintext
468
97
      auto cs = get_cipherstate(epoch);
469
470
97
      BOTAN_ASSERT(cs, "Have cipherstate for this epoch");
471
472
97
      decrypt_record(recbuf, &readbuf[DTLS_HEADER_SIZE], record_size, sequence, version, type, *cs);
473
97
   } catch(std::exception&) {
474
97
      readbuf.clear();
475
97
      return Record_Header(0);
476
97
   }
477
478
0
   if(sequence_numbers) {
479
0
      sequence_numbers->read_accept(sequence);
480
0
   }
481
482
0
   readbuf.clear();
483
0
   return Record_Header(sequence, version, type);
484
97
}
485
486
}  // namespace
487
488
Record_Header read_record(bool is_datagram,
489
                          secure_vector<uint8_t>& readbuf,
490
                          const uint8_t input[],
491
                          size_t input_len,
492
                          size_t& consumed,
493
                          secure_vector<uint8_t>& recbuf,
494
                          Connection_Sequence_Numbers* sequence_numbers,
495
                          const get_cipherstate_fn& get_cipherstate,
496
64.3k
                          bool allow_epoch0_restart) {
497
64.3k
   if(is_datagram) {
498
1.81k
      return read_dtls_record(
499
1.81k
         readbuf, input, input_len, consumed, recbuf, sequence_numbers, get_cipherstate, allow_epoch0_restart);
500
62.5k
   } else {
501
62.5k
      return read_tls_record(readbuf, input, input_len, consumed, recbuf, sequence_numbers, get_cipherstate);
502
62.5k
   }
503
64.3k
}
504
505
}  // namespace Botan::TLS