Coverage Report

Created: 2022-06-23 06:44

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