Coverage Report

Created: 2020-11-21 08:34

/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
2.98k
   {
35
2.98k
   m_nonce_format = suite.nonce_format();
36
2.98k
   m_nonce_bytes_from_record = suite.nonce_bytes_from_record(version);
37
2.98k
   m_nonce_bytes_from_handshake = suite.nonce_bytes_from_handshake();
38
39
2.98k
   const secure_vector<uint8_t>& aead_key = keys.aead_key(side);
40
2.98k
   m_nonce = keys.nonce(side);
41
42
2.98k
   BOTAN_ASSERT_NOMSG(m_nonce.size() == m_nonce_bytes_from_handshake);
43
44
2.98k
   if(nonce_format() == Nonce_Format::CBC_MODE)
45
1.40k
      {
46
1.40k
#if defined(BOTAN_HAS_TLS_CBC)
47
      // legacy CBC+HMAC mode
48
1.40k
      auto mac = MessageAuthenticationCode::create_or_throw("HMAC(" + suite.mac_algo() + ")");
49
1.40k
      auto cipher = BlockCipher::create_or_throw(suite.cipher_algo());
50
51
1.40k
      if(our_side)
52
858
         {
53
858
         m_aead.reset(new TLS_CBC_HMAC_AEAD_Encryption(
54
858
                         std::move(cipher),
55
858
                         std::move(mac),
56
858
                         suite.cipher_keylen(),
57
858
                         suite.mac_keylen(),
58
858
                         version,
59
858
                         uses_encrypt_then_mac));
60
858
         }
61
544
      else
62
544
         {
63
544
         m_aead.reset(new TLS_CBC_HMAC_AEAD_Decryption(
64
544
                         std::move(cipher),
65
544
                         std::move(mac),
66
544
                         suite.cipher_keylen(),
67
544
                         suite.mac_keylen(),
68
544
                         version,
69
544
                         uses_encrypt_then_mac));
70
544
         }
71
72
#else
73
      BOTAN_UNUSED(uses_encrypt_then_mac);
74
      throw Internal_Error("Negotiated disabled TLS CBC+HMAC ciphersuite");
75
#endif
76
1.40k
      }
77
1.58k
   else
78
1.58k
      {
79
808
      m_aead = AEAD_Mode::create_or_throw(suite.cipher_algo(), our_side ? ENCRYPTION : DECRYPTION);
80
1.58k
      }
81
82
2.98k
   m_aead->set_key(aead_key);
83
2.98k
   }
84
85
std::vector<uint8_t> Connection_Cipher_State::aead_nonce(uint64_t seq, RandomNumberGenerator& rng)
86
2.53k
   {
87
2.53k
   switch(m_nonce_format)
88
2.53k
      {
89
1.15k
      case Nonce_Format::CBC_MODE:
90
1.15k
         {
91
1.15k
         if(m_nonce.size())
92
858
            {
93
858
            std::vector<uint8_t> nonce;
94
858
            nonce.swap(m_nonce);
95
858
            return nonce;
96
858
            }
97
298
         std::vector<uint8_t> nonce(nonce_bytes_from_record());
98
298
         rng.randomize(nonce.data(), nonce.size());
99
298
         return nonce;
100
298
         }
101
597
      case Nonce_Format::AEAD_XOR_12:
102
597
         {
103
597
         std::vector<uint8_t> nonce(12);
104
597
         store_be(seq, nonce.data() + 4);
105
597
         xor_buf(nonce, m_nonce.data(), m_nonce.size());
106
597
         return nonce;
107
298
         }
108
778
      case Nonce_Format::AEAD_IMPLICIT_4:
109
778
         {
110
778
         BOTAN_ASSERT_NOMSG(m_nonce.size() == 4);
111
778
         std::vector<uint8_t> nonce(12);
112
778
         copy_mem(&nonce[0], m_nonce.data(), 4);
113
778
         store_be(seq, &nonce[nonce_bytes_from_handshake()]);
114
778
         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
897
   {
124
897
   switch(m_nonce_format)
125
897
      {
126
325
      case Nonce_Format::CBC_MODE:
127
325
         {
128
325
         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
325
         if(record_len < nonce_bytes_from_record())
135
10
            throw Decoding_Error("Invalid CBC packet too short to be valid");
136
315
         std::vector<uint8_t> nonce(record, record + nonce_bytes_from_record());
137
315
         return nonce;
138
315
         }
139
229
      case Nonce_Format::AEAD_XOR_12:
140
229
         {
141
229
         std::vector<uint8_t> nonce(12);
142
229
         store_be(seq, nonce.data() + 4);
143
229
         xor_buf(nonce, m_nonce.data(), m_nonce.size());
144
229
         return nonce;
145
315
         }
146
343
      case Nonce_Format::AEAD_IMPLICIT_4:
147
343
         {
148
343
         BOTAN_ASSERT_NOMSG(m_nonce.size() == 4);
149
343
         if(record_len < nonce_bytes_from_record())
150
4
            throw Decoding_Error("Invalid AEAD packet too short to be valid");
151
339
         std::vector<uint8_t> nonce(12);
152
339
         copy_mem(&nonce[0], m_nonce.data(), 4);
153
339
         copy_mem(&nonce[nonce_bytes_from_handshake()], record, nonce_bytes_from_record());
154
339
         return nonce;
155
339
         }
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
3.39k
   {
167
3.39k
   std::vector<uint8_t> ad(13);
168
169
3.39k
   store_be(msg_sequence, &ad[0]);
170
3.39k
   ad[8] = msg_type;
171
3.39k
   ad[9] = version.major_version();
172
3.39k
   ad[10] = version.minor_version();
173
3.39k
   ad[11] = get_byte(0, msg_length);
174
3.39k
   ad[12] = get_byte(1, msg_length);
175
176
3.39k
   return ad;
177
3.39k
   }
178
179
namespace {
180
181
inline void append_u16_len(secure_vector<uint8_t>& output, size_t len_field)
182
101k
   {
183
101k
   const uint16_t len16 = static_cast<uint16_t>(len_field);
184
101k
   BOTAN_ASSERT_EQUAL(len_field, len16, "No truncation");
185
101k
   output.push_back(get_byte(0, len16));
186
101k
   output.push_back(get_byte(1, len16));
187
101k
   }
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
101k
   {
194
101k
   output.clear();
195
196
101k
   output.push_back(record_type);
197
101k
   output.push_back(version.major_version());
198
101k
   output.push_back(version.minor_version());
199
200
101k
   if(version.is_datagram_protocol())
201
7.01k
      {
202
63.1k
      for(size_t i = 0; i != 8; ++i)
203
56.0k
         output.push_back(get_byte(i, record_sequence));
204
7.01k
      }
205
101k
   }
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
99.1k
   {
216
99.1k
   if(record_type == APPLICATION_DATA)
217
0
      throw Internal_Error("Writing an unencrypted TLS application data record");
218
99.1k
   write_record_header(output, record_type, version, record_sequence);
219
99.1k
   append_u16_len(output, message_len);
220
99.1k
   output.insert(output.end(), message, message + message_len);
221
99.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
2.53k
   {
232
2.53k
   write_record_header(output, record_type, version, record_sequence);
233
234
2.53k
   AEAD_Mode& aead = cs.aead();
235
2.53k
   std::vector<uint8_t> aad = cs.format_ad(record_sequence, record_type, version, static_cast<uint16_t>(message_len));
236
237
2.53k
   const size_t ctext_size = aead.output_length(message_len);
238
239
2.53k
   const size_t rec_size = ctext_size + cs.nonce_bytes_from_record();
240
241
2.53k
   aead.set_ad(aad);
242
243
2.53k
   const std::vector<uint8_t> nonce = cs.aead_nonce(record_sequence, rng);
244
245
2.53k
   append_u16_len(output, rec_size);
246
247
2.53k
   if(cs.nonce_bytes_from_record() > 0)
248
1.93k
      {
249
1.93k
      if(cs.nonce_format() == Nonce_Format::CBC_MODE)
250
1.15k
         output += nonce;
251
778
      else
252
778
         output += std::make_pair(&nonce[cs.nonce_bytes_from_handshake()], cs.nonce_bytes_from_record());
253
1.93k
      }
254
255
2.53k
   const size_t header_size = output.size();
256
2.53k
   output += std::make_pair(message, message_len);
257
258
2.53k
   aead.start(nonce);
259
2.53k
   aead.finish(output, header_size);
260
261
2.53k
   BOTAN_ASSERT(output.size() < MAX_CIPHERTEXT_SIZE,
262
2.53k
                "Produced ciphertext larger than protocol allows");
263
2.53k
   }
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
279k
   {
273
279k
   if(readbuf.size() >= desired)
274
446
      return 0; // already have it
275
276
279k
   const size_t taken = std::min(input_size, desired - readbuf.size());
277
278
279k
   readbuf.insert(readbuf.end(), input, input + taken);
279
279k
   input_consumed += taken;
280
279k
   input_size -= taken;
281
279k
   input += taken;
282
283
279k
   return (desired - readbuf.size()); // how many bytes do we still need?
284
279k
   }
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
897
   {
293
897
   AEAD_Mode& aead = cs.aead();
294
295
897
   const std::vector<uint8_t> nonce = cs.aead_nonce(record_contents, record_len, record_sequence);
296
897
   const uint8_t* msg = &record_contents[cs.nonce_bytes_from_record()];
297
897
   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
897
   if(msg_length < aead.minimum_final_size())
307
22
      throw TLS_Exception(Alert::BAD_RECORD_MAC, "AEAD packet is shorter than the tag");
308
309
875
   const size_t ptext_size = aead.output_length(msg_length);
310
311
875
   aead.set_associated_data_vec(
312
875
      cs.format_ad(record_sequence,
313
875
                   static_cast<uint8_t>(record_type),
314
875
                   record_version,
315
875
                   static_cast<uint16_t>(ptext_size))
316
875
      );
317
318
875
   aead.start(nonce);
319
320
875
   output.assign(msg, msg + msg_length);
321
875
   aead.finish(output, 0);
322
875
   }
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
139k
   {
332
139k
   if(readbuf.size() < TLS_HEADER_SIZE) // header incomplete?
333
139k
      {
334
139k
      if(size_t needed = fill_buffer_to(readbuf, input, input_len, consumed, TLS_HEADER_SIZE))
335
723
         {
336
723
         return Record_Header(needed);
337
723
         }
338
339
138k
      BOTAN_ASSERT_EQUAL(readbuf.size(), TLS_HEADER_SIZE, "Have an entire header");
340
138k
      }
341
342
138k
   const Protocol_Version version(readbuf[1], readbuf[2]);
343
344
138k
   if(version.is_datagram_protocol())
345
81
      throw TLS_Exception(Alert::PROTOCOL_VERSION,
346
81
                          "Expected TLS but got a record with DTLS version");
347
348
138k
   const size_t record_size = make_uint16(readbuf[TLS_HEADER_SIZE-2],
349
138k
                                          readbuf[TLS_HEADER_SIZE-1]);
350
351
138k
   if(record_size > MAX_CIPHERTEXT_SIZE)
352
331
      throw TLS_Exception(Alert::RECORD_OVERFLOW,
353
331
                          "Received a record that exceeds maximum size");
354
355
138k
   if(record_size == 0)
356
107
      throw TLS_Exception(Alert::DECODE_ERROR,
357
107
                          "Received a completely empty record");
358
359
138k
   if(size_t needed = fill_buffer_to(readbuf, input, input_len, consumed, TLS_HEADER_SIZE + record_size))
360
446
      {
361
446
      return Record_Header(needed);
362
446
      }
363
364
137k
   BOTAN_ASSERT_EQUAL(static_cast<size_t>(TLS_HEADER_SIZE) + record_size,
365
137k
                      readbuf.size(),
366
137k
                      "Have the full record");
367
368
137k
   const Record_Type type = static_cast<Record_Type>(readbuf[0]);
369
370
137k
   uint16_t epoch = 0;
371
372
137k
   uint64_t sequence = 0;
373
137k
   if(sequence_numbers)
374
130k
      {
375
130k
      sequence = sequence_numbers->next_read_sequence();
376
130k
      epoch = sequence_numbers->current_read_epoch();
377
130k
      }
378
6.65k
   else
379
6.65k
      {
380
      // server initial handshake case
381
6.65k
      epoch = 0;
382
6.65k
      }
383
384
137k
   if(epoch == 0) // Unencrypted initial handshake
385
136k
      {
386
136k
      recbuf.assign(readbuf.begin() + TLS_HEADER_SIZE, readbuf.begin() + TLS_HEADER_SIZE + record_size);
387
136k
      readbuf.clear();
388
136k
      return Record_Header(sequence, version, type);
389
136k
      }
390
391
   // Otherwise, decrypt, check MAC, return plaintext
392
897
   auto cs = get_cipherstate(epoch);
393
394
897
   BOTAN_ASSERT(cs, "Have cipherstate for this epoch");
395
396
897
   decrypt_record(recbuf,
397
897
                  &readbuf[TLS_HEADER_SIZE],
398
897
                  record_size,
399
897
                  sequence,
400
897
                  version,
401
897
                  type,
402
897
                  *cs);
403
404
897
   if(sequence_numbers)
405
0
      sequence_numbers->read_accept(sequence);
406
407
897
   readbuf.clear();
408
897
   return Record_Header(sequence, version, type);
409
897
   }
410
411
Record_Header read_dtls_record(secure_vector<uint8_t>& readbuf,
412
                               const uint8_t input[],
413
                               size_t input_len,
414
                               size_t& consumed,
415
                               secure_vector<uint8_t>& recbuf,
416
                               Connection_Sequence_Numbers* sequence_numbers,
417
                               get_cipherstate_fn get_cipherstate,
418
                               bool allow_epoch0_restart)
419
1.08k
   {
420
1.08k
   if(readbuf.size() < DTLS_HEADER_SIZE) // header incomplete?
421
1.08k
      {
422
1.08k
      if(fill_buffer_to(readbuf, input, input_len, consumed, DTLS_HEADER_SIZE))
423
31
         {
424
31
         readbuf.clear();
425
31
         return Record_Header(0);
426
31
         }
427
428
1.05k
      BOTAN_ASSERT_EQUAL(readbuf.size(), DTLS_HEADER_SIZE, "Have an entire header");
429
1.05k
      }
430
431
1.05k
   const Protocol_Version version(readbuf[1], readbuf[2]);
432
433
1.05k
   if(version.is_datagram_protocol() == false)
434
2
      {
435
2
      readbuf.clear();
436
2
      return Record_Header(0);
437
2
      }
438
439
1.05k
   const size_t record_size = make_uint16(readbuf[DTLS_HEADER_SIZE-2],
440
1.05k
                                          readbuf[DTLS_HEADER_SIZE-1]);
441
442
1.05k
   if(record_size > MAX_CIPHERTEXT_SIZE)
443
3
      {
444
      // Too large to be valid, ignore it
445
3
      readbuf.clear();
446
3
      return Record_Header(0);
447
3
      }
448
449
1.05k
   if(fill_buffer_to(readbuf, input, input_len, consumed, DTLS_HEADER_SIZE + record_size))
450
20
      {
451
      // Truncated packet?
452
20
      readbuf.clear();
453
20
      return Record_Header(0);
454
20
      }
455
456
1.03k
   BOTAN_ASSERT_EQUAL(static_cast<size_t>(DTLS_HEADER_SIZE) + record_size, readbuf.size(),
457
1.03k
                      "Have the full record");
458
459
1.03k
   const Record_Type type = static_cast<Record_Type>(readbuf[0]);
460
461
1.03k
   const uint64_t sequence = load_be<uint64_t>(&readbuf[3], 0);
462
1.03k
   const uint16_t epoch = (sequence >> 48);
463
464
1.03k
   const bool already_seen = sequence_numbers && sequence_numbers->already_seen(sequence);
465
466
1.03k
   if(already_seen && !(epoch == 0 && allow_epoch0_restart))
467
42
      {
468
42
      readbuf.clear();
469
42
      return Record_Header(0);
470
42
      }
471
472
991
   if(epoch == 0) // Unencrypted initial handshake
473
916
      {
474
916
      recbuf.assign(readbuf.begin() + DTLS_HEADER_SIZE, readbuf.begin() + DTLS_HEADER_SIZE + record_size);
475
916
      readbuf.clear();
476
916
      if(sequence_numbers)
477
294
         sequence_numbers->read_accept(sequence);
478
916
      return Record_Header(sequence, version, type);
479
916
      }
480
481
75
   try
482
75
      {
483
      // Otherwise, decrypt, check MAC, return plaintext
484
75
      auto cs = get_cipherstate(epoch);
485
486
75
      BOTAN_ASSERT(cs, "Have cipherstate for this epoch");
487
488
75
      decrypt_record(recbuf,
489
75
                     &readbuf[DTLS_HEADER_SIZE],
490
75
                     record_size,
491
75
                     sequence,
492
75
                     version,
493
75
                     type,
494
75
                     *cs);
495
75
      }
496
75
   catch(std::exception&)
497
75
      {
498
75
      readbuf.clear();
499
75
      return Record_Header(0);
500
75
      }
501
502
0
   if(sequence_numbers)
503
0
      sequence_numbers->read_accept(sequence);
504
505
0
   readbuf.clear();
506
0
   return Record_Header(sequence, version, type);
507
0
   }
508
509
}
510
511
Record_Header read_record(bool is_datagram,
512
                          secure_vector<uint8_t>& readbuf,
513
                          const uint8_t input[],
514
                          size_t input_len,
515
                          size_t& consumed,
516
                          secure_vector<uint8_t>& recbuf,
517
                          Connection_Sequence_Numbers* sequence_numbers,
518
                          get_cipherstate_fn get_cipherstate,
519
                          bool allow_epoch0_restart)
520
140k
   {
521
140k
   if(is_datagram)
522
1.08k
      return read_dtls_record(readbuf, input, input_len, consumed,
523
1.08k
                              recbuf, sequence_numbers, get_cipherstate, allow_epoch0_restart);
524
139k
   else
525
139k
      return read_tls_record(readbuf, input, input_len, consumed,
526
139k
                             recbuf, sequence_numbers, get_cipherstate);
527
140k
   }
528
529
}
530
531
}