Coverage Report

Created: 2020-06-30 13:58

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