Coverage Report

Created: 2021-05-04 09:02

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