aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/tls/tls_record.cpp
blob: 3edeab7e3ca3209a67371f0301b443d1eceb7be1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/*
* TLS Record Handling
* (C) 2012,2013,2014 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/tls_record.h>
#include <botan/tls_ciphersuite.h>
#include <botan/tls_exceptn.h>
#include <botan/libstate.h>
#include <botan/loadstor.h>
#include <botan/internal/tls_seq_numbers.h>
#include <botan/internal/tls_session_key.h>
#include <botan/internal/rounding.h>
#include <botan/internal/xor_buf.h>

namespace Botan {

namespace TLS {

Connection_Cipher_State::Connection_Cipher_State(Protocol_Version version,
                                                 Connection_Side side,
                                                 bool our_side,
                                                 const Ciphersuite& suite,
                                                 const Session_Keys& keys) :
   m_start_time(std::chrono::system_clock::now()),
   m_nonce_bytes_from_handshake(suite.nonce_bytes_from_handshake()),
   m_nonce_bytes_from_record(suite.nonce_bytes_from_record())
   {
   SymmetricKey mac_key, cipher_key;
   InitializationVector iv;

   if(side == CLIENT)
      {
      cipher_key = keys.client_cipher_key();
      iv = keys.client_iv();
      mac_key = keys.client_mac_key();
      }
   else
      {
      cipher_key = keys.server_cipher_key();
      iv = keys.server_iv();
      mac_key = keys.server_mac_key();
      }

   const std::string cipher_algo = suite.cipher_algo();
   const std::string mac_algo = suite.mac_algo();

   if(AEAD_Mode* aead = get_aead(cipher_algo, our_side ? ENCRYPTION : DECRYPTION))
      {
      m_aead.reset(aead);
      m_aead->set_key(cipher_key + mac_key);

      BOTAN_ASSERT_EQUAL(iv.length(), nonce_bytes_from_handshake(), "Matching nonce sizes");
      m_nonce = iv.bits_of();

      BOTAN_ASSERT(nonce_bytes_from_record() == 0 || nonce_bytes_from_record() == 8,
                   "Ciphersuite uses implemented IV length");

      m_nonce.resize(m_nonce.size() + 8);
      return;
      }

   Algorithm_Factory& af = global_state().algorithm_factory();

   if(const BlockCipher* bc = af.prototype_block_cipher(cipher_algo))
      {
      m_block_cipher.reset(bc->clone());
      m_block_cipher->set_key(cipher_key);
      m_block_cipher_cbc_state = iv.bits_of();
      m_block_size = bc->block_size();

      if(version.supports_explicit_cbc_ivs())
         m_iv_size = m_block_size;
      }
   else if(const StreamCipher* sc = af.prototype_stream_cipher(cipher_algo))
      {
      m_stream_cipher.reset(sc->clone());
      m_stream_cipher->set_key(cipher_key);
      }
   else
      throw Invalid_Argument("Unknown TLS cipher " + cipher_algo);

   m_mac.reset(af.make_mac("HMAC(" + mac_algo + ")"));

   m_mac->set_key(mac_key);
   }

const secure_vector<byte>& Connection_Cipher_State::aead_nonce(u64bit seq)
   {
   store_be(seq, &m_nonce[nonce_bytes_from_handshake()]);
   return m_nonce;
   }

const secure_vector<byte>&
Connection_Cipher_State::aead_nonce(const byte record[], size_t record_len, u64bit seq)
   {
   if(nonce_bytes_from_record())
      {
      if(record_len < nonce_bytes_from_record())
         throw Decoding_Error("Invalid AEAD packet too short to be valid");
      copy_mem(&m_nonce[nonce_bytes_from_handshake()], record, nonce_bytes_from_record());
      }
   else
      {
      /*
      nonce_len == 0 is assumed to mean no nonce in the message but
      instead the AEAD uses the seq number in network order.
      */
      store_be(seq, &m_nonce[nonce_bytes_from_handshake()]);
      }
   return m_nonce;
   }

const secure_vector<byte>&
Connection_Cipher_State::format_ad(u64bit msg_sequence,
                                   byte msg_type,
                                   Protocol_Version version,
                                   u16bit msg_length)
   {
   m_ad.clear();
   for(size_t i = 0; i != 8; ++i)
      m_ad.push_back(get_byte(i, msg_sequence));
   m_ad.push_back(msg_type);

   m_ad.push_back(version.major_version());
   m_ad.push_back(version.minor_version());

   m_ad.push_back(get_byte(0, msg_length));
   m_ad.push_back(get_byte(1, msg_length));

   return m_ad;
   }

void write_record(secure_vector<byte>& output,
                  byte msg_type, const byte msg[], size_t msg_length,
                  Protocol_Version version,
                  u64bit seq,
                  Connection_Cipher_State* cs,
                  RandomNumberGenerator& rng)
   {
   output.clear();

   output.push_back(msg_type);
   output.push_back(version.major_version());
   output.push_back(version.minor_version());

   if(version.is_datagram_protocol())
      {
      for(size_t i = 0; i != 8; ++i)
         output.push_back(get_byte(i, seq));
      }

   if(!cs) // initial unencrypted handshake records
      {
      output.push_back(get_byte<u16bit>(0, msg_length));
      output.push_back(get_byte<u16bit>(1, msg_length));

      output.insert(output.end(), &msg[0], &msg[msg_length]);

      return;
      }

   if(AEAD_Mode* aead = cs->aead())
      {
      const size_t ctext_size = aead->output_length(msg_length);

      const secure_vector<byte>& nonce = cs->aead_nonce(seq);

      // wrong if start returns something
      const size_t rec_size = ctext_size + cs->nonce_bytes_from_record();

      BOTAN_ASSERT(rec_size <= 0xFFFF, "Ciphertext length fits in field");
      output.push_back(get_byte<u16bit>(0, rec_size));
      output.push_back(get_byte<u16bit>(1, rec_size));

      aead->set_ad(cs->format_ad(seq, msg_type, version, msg_length));

      output += std::make_pair(&nonce[cs->nonce_bytes_from_handshake()], cs->nonce_bytes_from_record());
      BOTAN_ASSERT(aead->start(nonce).empty(), "AEAD doesn't return anything from start");

      const size_t offset = output.size();
      output += std::make_pair(&msg[0], msg_length);
      aead->finish(output, offset);

      BOTAN_ASSERT(output.size() == offset + ctext_size, "Expected size");

      BOTAN_ASSERT(output.size() < MAX_CIPHERTEXT_SIZE,
                   "Produced ciphertext larger than protocol allows");
      return;
      }

   cs->mac()->update(cs->format_ad(seq, msg_type, version, msg_length));

   cs->mac()->update(msg, msg_length);

   const size_t block_size = cs->block_size();
   const size_t iv_size = cs->iv_size();
   const size_t mac_size = cs->mac_size();

   const size_t buf_size = round_up(
      iv_size + msg_length + mac_size + (block_size ? 1 : 0),
      block_size);

   if(buf_size > MAX_CIPHERTEXT_SIZE)
      throw Internal_Error("Output record is larger than allowed by protocol");

   output.push_back(get_byte<u16bit>(0, buf_size));
   output.push_back(get_byte<u16bit>(1, buf_size));

   const size_t header_size = output.size();

   if(iv_size)
      {
      output.resize(output.size() + iv_size);
      rng.randomize(&output[output.size() - iv_size], iv_size);
      }

   output.insert(output.end(), &msg[0], &msg[msg_length]);

   output.resize(output.size() + mac_size);
   cs->mac()->final(&output[output.size() - mac_size]);

   if(block_size)
      {
      const size_t pad_val =
         buf_size - (iv_size + msg_length + mac_size + 1);

      for(size_t i = 0; i != pad_val + 1; ++i)
         output.push_back(pad_val);
      }

   if(buf_size > MAX_CIPHERTEXT_SIZE)
      throw Internal_Error("Produced ciphertext larger than protocol allows");

   BOTAN_ASSERT_EQUAL(buf_size + header_size, output.size(),
                      "Output buffer is sized properly");

   if(StreamCipher* sc = cs->stream_cipher())
      {
      sc->cipher1(&output[header_size], buf_size);
      }
   else if(BlockCipher* bc = cs->block_cipher())
      {
      secure_vector<byte>& cbc_state = cs->cbc_state();

      BOTAN_ASSERT(buf_size % block_size == 0,
                   "Buffer is an even multiple of block size");

      byte* buf = &output[header_size];

      const size_t blocks = buf_size / block_size;

      xor_buf(&buf[0], &cbc_state[0], block_size);
      bc->encrypt(&buf[0]);

      for(size_t i = 1; i < blocks; ++i)
         {
         xor_buf(&buf[block_size*i], &buf[block_size*(i-1)], block_size);
         bc->encrypt(&buf[block_size*i]);
         }

      cbc_state.assign(&buf[block_size*(blocks-1)],
                       &buf[block_size*blocks]);
      }
   else
      throw Internal_Error("NULL cipher not supported");
   }

namespace {

size_t fill_buffer_to(secure_vector<byte>& readbuf,
                      const byte*& input,
                      size_t& input_size,
                      size_t& input_consumed,
                      size_t desired)
   {
   if(readbuf.size() >= desired)
      return 0; // already have it

   const size_t taken = std::min(input_size, desired - readbuf.size());

   readbuf.insert(readbuf.end(), &input[0], &input[taken]);
   input_consumed += taken;
   input_size -= taken;
   input += taken;

   return (desired - readbuf.size()); // how many bytes do we still need?
   }

/*
* Checks the TLS padding. Returns 0 if the padding is invalid (we
* count the padding_length field as part of the padding size so a
* valid padding will always be at least one byte long), or the length
* of the padding otherwise. This is actually padding_length + 1
* because both the padding and padding_length fields are padding from
* our perspective.
*
* Returning 0 in the error case should ensure the MAC check will fail.
* This approach is suggested in section 6.2.3.2 of RFC 5246.
*
* Also returns 0 if block_size == 0, so can be safely called with a
* stream cipher in use.
*
* @fixme This should run in constant time
*/
size_t tls_padding_check(size_t block_size,
                         const byte record[],
                         size_t record_len)
   {
   const size_t padding_length = record[(record_len-1)];

   if(padding_length >= record_len)
      return 0;

   /*
   * TLS v1.0 and up require all the padding bytes be the same value
   * and allows up to 255 bytes.
   */
   const size_t pad_start = record_len - padding_length - 1;

   volatile size_t cmp = 0;

   for(size_t i = 0; i != padding_length; ++i)
      cmp += record[pad_start + i] ^ padding_length;

   return cmp ? 0 : padding_length + 1;
   }

void cbc_decrypt_record(byte record_contents[], size_t record_len,
                        Connection_Cipher_State& cs,
                        const BlockCipher& bc)
   {
   const size_t block_size = cs.block_size();

   BOTAN_ASSERT(record_len % block_size == 0,
                "Buffer is an even multiple of block size");

   const size_t blocks = record_len / block_size;

   BOTAN_ASSERT(blocks >= 1, "At least one ciphertext block");

   byte* buf = record_contents;

   secure_vector<byte> last_ciphertext(block_size);
   copy_mem(&last_ciphertext[0], &buf[0], block_size);

   bc.decrypt(&buf[0]);
   xor_buf(&buf[0], &cs.cbc_state()[0], block_size);

   secure_vector<byte> last_ciphertext2;

   for(size_t i = 1; i < blocks; ++i)
      {
      last_ciphertext2.assign(&buf[block_size*i], &buf[block_size*(i+1)]);
      bc.decrypt(&buf[block_size*i]);
      xor_buf(&buf[block_size*i], &last_ciphertext[0], block_size);
      std::swap(last_ciphertext, last_ciphertext2);
      }

   cs.cbc_state() = last_ciphertext;
   }

void decrypt_record(secure_vector<byte>& output,
                    byte record_contents[], size_t record_len,
                    u64bit record_sequence,
                    Protocol_Version record_version,
                    Record_Type record_type,
                    Connection_Cipher_State& cs)
   {
   if(AEAD_Mode* aead = cs.aead())
      {
      const secure_vector<byte>& nonce = cs.aead_nonce(record_contents, record_len, record_sequence);
      const byte* msg = &record_contents[cs.nonce_bytes_from_record()];
      const size_t msg_length = record_len - cs.nonce_bytes_from_record();

      const size_t ptext_size = aead->output_length(msg_length);

      aead->set_associated_data_vec(
         cs.format_ad(record_sequence, record_type, record_version, ptext_size)
         );

      output += aead->start(nonce);

      const size_t offset = output.size();
      output += std::make_pair(&msg[0], msg_length);
      aead->finish(output, offset);

      BOTAN_ASSERT(output.size() == ptext_size + offset, "Produced expected size");
      }
   else
      {
      // GenericBlockCipher / GenericStreamCipher case

      volatile bool padding_bad = false;
      size_t pad_size = 0;

      if(StreamCipher* sc = cs.stream_cipher())
         {
         sc->cipher1(record_contents, record_len);
         // no padding to check or remove
         }
      else if(BlockCipher* bc = cs.block_cipher())
         {
         cbc_decrypt_record(record_contents, record_len, cs, *bc);

         pad_size = tls_padding_check(cs.block_size(),
                                      record_contents, record_len);

         padding_bad = (pad_size == 0);
         }
      else
         {
         throw Internal_Error("No cipher state set but needed to decrypt");
         }

      const size_t mac_size = cs.mac_size();
      const size_t iv_size = cs.iv_size();

      const size_t mac_pad_iv_size = mac_size + pad_size + iv_size;

      if(record_len < mac_pad_iv_size)
         throw Decoding_Error("Record sent with invalid length");

      const byte* plaintext_block = &record_contents[iv_size];
      const u16bit plaintext_length = record_len - mac_pad_iv_size;

      cs.mac()->update(
         cs.format_ad(record_sequence, record_type, record_version, plaintext_length)
         );

      cs.mac()->update(plaintext_block, plaintext_length);

      std::vector<byte> mac_buf(mac_size);
      cs.mac()->final(&mac_buf[0]);

      const size_t mac_offset = record_len - (mac_size + pad_size);

      const bool mac_bad = !same_mem(&record_contents[mac_offset], &mac_buf[0], mac_size);

      if(mac_bad || padding_bad)
         throw TLS_Exception(Alert::BAD_RECORD_MAC, "Message authentication failure");

      output.assign(plaintext_block, plaintext_block + plaintext_length);
      }
   }

size_t read_tls_record(secure_vector<byte>& readbuf,
                       const byte input[],
                       size_t input_sz,
                       size_t& consumed,
                       secure_vector<byte>& record,
                       u64bit* record_sequence,
                       Protocol_Version* record_version,
                       Record_Type* record_type,
                       Connection_Sequence_Numbers* sequence_numbers,
                       std::function<std::shared_ptr<Connection_Cipher_State> (u16bit)> get_cipherstate)
   {
   consumed = 0;

   if(readbuf.size() < TLS_HEADER_SIZE) // header incomplete?
      {
      if(size_t needed = fill_buffer_to(readbuf,
                                        input, input_sz, consumed,
                                        TLS_HEADER_SIZE))
         return needed;

      BOTAN_ASSERT_EQUAL(readbuf.size(), TLS_HEADER_SIZE, "Have an entire header");
      }

   *record_version = Protocol_Version(readbuf[1], readbuf[2]);

   BOTAN_ASSERT(!record_version->is_datagram_protocol(), "Expected TLS");

   const size_t record_len = make_u16bit(readbuf[TLS_HEADER_SIZE-2],
                                         readbuf[TLS_HEADER_SIZE-1]);

   if(record_len > MAX_CIPHERTEXT_SIZE)
      throw TLS_Exception(Alert::RECORD_OVERFLOW,
                          "Got message that exceeds maximum size");

   if(size_t needed = fill_buffer_to(readbuf,
                                     input, input_sz, consumed,
                                     TLS_HEADER_SIZE + record_len))
      return needed;

   BOTAN_ASSERT_EQUAL(static_cast<size_t>(TLS_HEADER_SIZE) + record_len,
                      readbuf.size(),
                      "Have the full record");

   *record_type = static_cast<Record_Type>(readbuf[0]);

   u16bit epoch = 0;

   if(sequence_numbers)
      {
      *record_sequence = sequence_numbers->next_read_sequence();
      epoch = sequence_numbers->current_read_epoch();
      }
   else
      {
      // server initial handshake case
      *record_sequence = 0;
      epoch = 0;
      }

   byte* record_contents = &readbuf[TLS_HEADER_SIZE];

   if(epoch == 0) // Unencrypted initial handshake
      {
      record.assign(&readbuf[TLS_HEADER_SIZE], &readbuf[TLS_HEADER_SIZE + record_len]);
      readbuf.clear();
      return 0; // got a full record
      }

   // Otherwise, decrypt, check MAC, return plaintext
   auto cs = get_cipherstate(epoch);

   BOTAN_ASSERT(cs, "Have cipherstate for this epoch");

   decrypt_record(record,
                  record_contents,
                  record_len,
                  *record_sequence,
                  *record_version,
                  *record_type,
                  *cs);

   if(sequence_numbers)
      sequence_numbers->read_accept(*record_sequence);

   readbuf.clear();
   return 0;
   }

size_t read_dtls_record(secure_vector<byte>& readbuf,
                        const byte input[],
                        size_t input_sz,
                        size_t& consumed,
                        secure_vector<byte>& record,
                        u64bit* record_sequence,
                        Protocol_Version* record_version,
                        Record_Type* record_type,
                        Connection_Sequence_Numbers* sequence_numbers,
                        std::function<std::shared_ptr<Connection_Cipher_State> (u16bit)> get_cipherstate)
   {
   consumed = 0;

   if(readbuf.size() < DTLS_HEADER_SIZE) // header incomplete?
      {
      if(fill_buffer_to(readbuf, input, input_sz, consumed, DTLS_HEADER_SIZE))
         {
         readbuf.clear();
         return 0;
         }

      BOTAN_ASSERT_EQUAL(readbuf.size(), DTLS_HEADER_SIZE, "Have an entire header");
      }

   *record_version = Protocol_Version(readbuf[1], readbuf[2]);

   BOTAN_ASSERT(record_version->is_datagram_protocol(), "Expected DTLS");

   const size_t record_len = make_u16bit(readbuf[DTLS_HEADER_SIZE-2],
                                         readbuf[DTLS_HEADER_SIZE-1]);

   if(record_len > MAX_CIPHERTEXT_SIZE)
      throw TLS_Exception(Alert::RECORD_OVERFLOW,
                          "Got message that exceeds maximum size");

   if(fill_buffer_to(readbuf, input, input_sz, consumed, DTLS_HEADER_SIZE + record_len))
      {
      // Truncated packet?
      readbuf.clear();
      return 0;
      }

   BOTAN_ASSERT_EQUAL(static_cast<size_t>(DTLS_HEADER_SIZE) + record_len, readbuf.size(),
                      "Have the full record");

   *record_type = static_cast<Record_Type>(readbuf[0]);

   u16bit epoch = 0;

   *record_sequence = load_be<u64bit>(&readbuf[3], 0);
   epoch = (*record_sequence >> 48);

   if(sequence_numbers && sequence_numbers->already_seen(*record_sequence))
      {
      readbuf.clear();
      return 0;
      }

   byte* record_contents = &readbuf[DTLS_HEADER_SIZE];

   if(epoch == 0) // Unencrypted initial handshake
      {
      record.assign(&readbuf[DTLS_HEADER_SIZE], &readbuf[DTLS_HEADER_SIZE + record_len]);
      readbuf.clear();
      return 0; // got a full record
      }

   try
      {
      // Otherwise, decrypt, check MAC, return plaintext
      auto cs = get_cipherstate(epoch);

      BOTAN_ASSERT(cs, "Have cipherstate for this epoch");

      decrypt_record(record,
                     record_contents,
                     record_len,
                     *record_sequence,
                     *record_version,
                     *record_type,
                     *cs);
      }
   catch(std::exception)
      {
      readbuf.clear();
      *record_type = NO_RECORD;
      return 0;
      }

   if(sequence_numbers)
      sequence_numbers->read_accept(*record_sequence);

   readbuf.clear();
   return 0;
   }

}

size_t read_record(secure_vector<byte>& readbuf,
                   const byte input[],
                   size_t input_sz,
                   bool is_datagram,
                   size_t& consumed,
                   secure_vector<byte>& record,
                   u64bit* record_sequence,
                   Protocol_Version* record_version,
                   Record_Type* record_type,
                   Connection_Sequence_Numbers* sequence_numbers,
                   std::function<std::shared_ptr<Connection_Cipher_State> (u16bit)> get_cipherstate)
   {
   if(is_datagram)
      return read_dtls_record(readbuf, input, input_sz, consumed,
                              record, record_sequence, record_version, record_type,
                              sequence_numbers, get_cipherstate);
   else
      return read_tls_record(readbuf, input, input_sz, consumed,
                             record, record_sequence, record_version, record_type,
                             sequence_numbers, get_cipherstate);
   }

}

}