Coverage Report

Created: 2019-09-11 14:12

/src/botan/src/lib/tls/tls_channel.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* TLS Channels
3
* (C) 2011,2012,2014,2015,2016 Jack Lloyd
4
*     2016 Matthias Gierlings
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8
9
#include <botan/tls_channel.h>
10
#include <botan/tls_policy.h>
11
#include <botan/tls_messages.h>
12
#include <botan/kdf.h>
13
#include <botan/internal/tls_handshake_state.h>
14
#include <botan/internal/tls_record.h>
15
#include <botan/internal/tls_seq_numbers.h>
16
#include <botan/internal/rounding.h>
17
#include <botan/internal/stl_util.h>
18
#include <botan/loadstor.h>
19
20
namespace Botan {
21
22
namespace TLS {
23
24
size_t TLS::Channel::IO_BUF_DEFAULT_SIZE = 10*1024;
25
26
Channel::Channel(Callbacks& callbacks,
27
                 Session_Manager& session_manager,
28
                 RandomNumberGenerator& rng,
29
                 const Policy& policy,
30
                 bool is_server,
31
                 bool is_datagram,
32
                 size_t reserved_io_buffer_size) :
33
   m_is_server(is_server),
34
   m_is_datagram(is_datagram),
35
   m_callbacks(callbacks),
36
   m_session_manager(session_manager),
37
   m_policy(policy),
38
   m_rng(rng),
39
   m_has_been_closed(false)
40
10.8k
   {
41
10.8k
   init(reserved_io_buffer_size);
42
10.8k
   }
43
44
Channel::Channel(output_fn out,
45
                 data_cb app_data_cb,
46
                 alert_cb recv_alert_cb,
47
                 handshake_cb hs_cb,
48
                 handshake_msg_cb hs_msg_cb,
49
                 Session_Manager& session_manager,
50
                 RandomNumberGenerator& rng,
51
                 const Policy& policy,
52
                 bool is_server,
53
                 bool is_datagram,
54
                 size_t io_buf_sz) :
55
    m_is_server(is_server),
56
    m_is_datagram(is_datagram),
57
    m_compat_callbacks(new Compat_Callbacks(
58
                          /*
59
                          this Channel constructor is also deprecated so its ok that it
60
                          relies on a deprecated API
61
                          */
62
                          Compat_Callbacks::SILENCE_DEPRECATION_WARNING::PLEASE,
63
                          out, app_data_cb, recv_alert_cb, hs_cb, hs_msg_cb)),
64
    m_callbacks(*m_compat_callbacks.get()),
65
    m_session_manager(session_manager),
66
    m_policy(policy),
67
    m_rng(rng),
68
    m_has_been_closed(false)
69
0
    {
70
0
    init(io_buf_sz);
71
0
    }
72
73
void Channel::init(size_t io_buf_sz)
74
10.8k
   {
75
10.8k
   /* epoch 0 is plaintext, thus null cipher state */
76
10.8k
   m_write_cipher_states[0] = nullptr;
77
10.8k
   m_read_cipher_states[0] = nullptr;
78
10.8k
79
10.8k
   m_writebuf.reserve(io_buf_sz);
80
10.8k
   m_readbuf.reserve(io_buf_sz);
81
10.8k
   }
82
83
void Channel::reset_state()
84
7.72k
   {
85
7.72k
   m_active_state.reset();
86
7.72k
   m_pending_state.reset();
87
7.72k
   m_readbuf.clear();
88
7.72k
   m_write_cipher_states.clear();
89
7.72k
   m_read_cipher_states.clear();
90
7.72k
   }
91
92
void Channel::reset_active_association_state()
93
0
   {
94
0
   // This operation only makes sense for DTLS
95
0
   BOTAN_ASSERT_NOMSG(m_is_datagram);
96
0
   m_active_state.reset();
97
0
   m_read_cipher_states.clear();
98
0
   m_write_cipher_states.clear();
99
0
100
0
   m_write_cipher_states[0] = nullptr;
101
0
   m_read_cipher_states[0] = nullptr;
102
0
103
0
   if(m_sequence_numbers)
104
0
      m_sequence_numbers->reset();
105
0
   }
106
107
Channel::~Channel()
108
10.8k
   {
109
10.8k
   // So unique_ptr destructors run correctly
110
10.8k
   }
111
112
Connection_Sequence_Numbers& Channel::sequence_numbers() const
113
160k
   {
114
160k
   BOTAN_ASSERT(m_sequence_numbers, "Have a sequence numbers object");
115
160k
   return *m_sequence_numbers;
116
160k
   }
117
118
std::shared_ptr<Connection_Cipher_State> Channel::read_cipher_state_epoch(uint16_t epoch) const
119
1.06k
   {
120
1.06k
   auto i = m_read_cipher_states.find(epoch);
121
1.06k
   if(i == m_read_cipher_states.end())
122
78
      throw Internal_Error("TLS::Channel No read cipherstate for epoch " + std::to_string(epoch));
123
982
   return i->second;
124
982
   }
125
126
std::shared_ptr<Connection_Cipher_State> Channel::write_cipher_state_epoch(uint16_t epoch) const
127
76.8k
   {
128
76.8k
   auto i = m_write_cipher_states.find(epoch);
129
76.8k
   if(i == m_write_cipher_states.end())
130
0
      throw Internal_Error("TLS::Channel No write cipherstate for epoch " + std::to_string(epoch));
131
76.8k
   return i->second;
132
76.8k
   }
133
134
std::vector<X509_Certificate> Channel::peer_cert_chain() const
135
0
   {
136
0
   if(auto active = active_state())
137
0
      return get_peer_cert_chain(*active);
138
0
   return std::vector<X509_Certificate>();
139
0
   }
140
141
bool Channel::save_session(const Session& session)
142
598
   {
143
598
   return callbacks().tls_session_established(session);
144
598
   }
145
146
Handshake_State& Channel::create_handshake_state(Protocol_Version version)
147
36.9k
   {
148
36.9k
   if(pending_state())
149
0
      throw Internal_Error("create_handshake_state called during handshake");
150
36.9k
151
36.9k
   if(auto active = active_state())
152
0
      {
153
0
      Protocol_Version active_version = active->version();
154
0
155
0
      if(active_version.is_datagram_protocol() != version.is_datagram_protocol())
156
0
         {
157
0
         throw TLS_Exception(Alert::PROTOCOL_VERSION,
158
0
                             "Active state using version " + active_version.to_string() +
159
0
                             " cannot change to " + version.to_string() + " in pending");
160
0
         }
161
36.9k
      }
162
36.9k
163
36.9k
   if(!m_sequence_numbers)
164
10.6k
      {
165
10.6k
      if(version.is_datagram_protocol())
166
586
         m_sequence_numbers.reset(new Datagram_Sequence_Numbers);
167
10.0k
      else
168
10.0k
         m_sequence_numbers.reset(new Stream_Sequence_Numbers);
169
10.6k
      }
170
36.9k
171
36.9k
   using namespace std::placeholders;
172
36.9k
173
36.9k
   std::unique_ptr<Handshake_IO> io;
174
36.9k
   if(version.is_datagram_protocol())
175
586
      {
176
586
      io.reset(new Datagram_Handshake_IO(
177
586
                  std::bind(&Channel::send_record_under_epoch, this, _1, _2, _3),
178
586
                  sequence_numbers(),
179
586
                  static_cast<uint16_t>(m_policy.dtls_default_mtu()),
180
586
                  m_policy.dtls_initial_timeout(),
181
586
                  m_policy.dtls_maximum_timeout()));
182
586
      }
183
36.3k
   else
184
36.3k
      {
185
36.3k
      io.reset(new Stream_Handshake_IO(std::bind(&Channel::send_record, this, _1, _2)));
186
36.3k
      }
187
36.9k
188
36.9k
   m_pending_state.reset(new_handshake_state(io.release()));
189
36.9k
190
36.9k
   if(auto active = active_state())
191
0
      m_pending_state->set_version(active->version());
192
36.9k
193
36.9k
   return *m_pending_state.get();
194
36.9k
   }
195
196
bool Channel::timeout_check()
197
0
   {
198
0
   if(m_pending_state)
199
0
      return m_pending_state->handshake_io().timeout_check();
200
0
201
0
   //FIXME: scan cipher suites and remove epochs older than 2*MSL
202
0
   return false;
203
0
   }
204
205
void Channel::renegotiate(bool force_full_renegotiation)
206
0
   {
207
0
   if(pending_state()) // currently in handshake?
208
0
      return;
209
0
210
0
   if(auto active = active_state())
211
0
      {
212
0
      if(force_full_renegotiation == false)
213
0
         force_full_renegotiation = !policy().allow_resumption_for_renegotiation();
214
0
215
0
      initiate_handshake(create_handshake_state(active->version()),
216
0
                         force_full_renegotiation);
217
0
      }
218
0
   else
219
0
      throw Invalid_State("Cannot renegotiate on inactive connection");
220
0
   }
221
222
void Channel::change_cipher_spec_reader(Connection_Side side)
223
1.46k
   {
224
1.46k
   auto pending = pending_state();
225
1.46k
226
1.46k
   BOTAN_ASSERT(pending && pending->server_hello(),
227
1.46k
                "Have received server hello");
228
1.46k
229
1.46k
   if(pending->server_hello()->compression_method() != 0)
230
0
      throw Internal_Error("Negotiated unknown compression algorithm");
231
1.46k
232
1.46k
   sequence_numbers().new_read_cipher_state();
233
1.46k
234
1.46k
   const uint16_t epoch = sequence_numbers().current_read_epoch();
235
1.46k
236
1.46k
   BOTAN_ASSERT(m_read_cipher_states.count(epoch) == 0,
237
1.46k
                "No read cipher state currently set for next epoch");
238
1.46k
239
1.46k
   // flip side as we are reading
240
1.46k
   std::shared_ptr<Connection_Cipher_State> read_state(
241
1.46k
      new Connection_Cipher_State(pending->version(),
242
1.46k
                                  (side == CLIENT) ? SERVER : CLIENT,
243
1.46k
                                  false,
244
1.46k
                                  pending->ciphersuite(),
245
1.46k
                                  pending->session_keys(),
246
1.46k
                                  pending->server_hello()->supports_encrypt_then_mac()));
247
1.46k
248
1.46k
   m_read_cipher_states[epoch] = read_state;
249
1.46k
   }
250
251
void Channel::change_cipher_spec_writer(Connection_Side side)
252
1.40k
   {
253
1.40k
   auto pending = pending_state();
254
1.40k
255
1.40k
   BOTAN_ASSERT(pending && pending->server_hello(),
256
1.40k
                "Have received server hello");
257
1.40k
258
1.40k
   if(pending->server_hello()->compression_method() != 0)
259
0
      throw Internal_Error("Negotiated unknown compression algorithm");
260
1.40k
261
1.40k
   sequence_numbers().new_write_cipher_state();
262
1.40k
263
1.40k
   const uint16_t epoch = sequence_numbers().current_write_epoch();
264
1.40k
265
1.40k
   BOTAN_ASSERT(m_write_cipher_states.count(epoch) == 0,
266
1.40k
                "No write cipher state currently set for next epoch");
267
1.40k
268
1.40k
   std::shared_ptr<Connection_Cipher_State> write_state(
269
1.40k
      new Connection_Cipher_State(pending->version(),
270
1.40k
                                  side,
271
1.40k
                                  true,
272
1.40k
                                  pending->ciphersuite(),
273
1.40k
                                  pending->session_keys(),
274
1.40k
                                  pending->server_hello()->supports_encrypt_then_mac()));
275
1.40k
276
1.40k
   m_write_cipher_states[epoch] = write_state;
277
1.40k
   }
278
279
bool Channel::is_active() const
280
0
   {
281
0
   return (active_state() != nullptr);
282
0
   }
283
284
bool Channel::is_closed() const
285
10.1k
   {
286
10.1k
   return m_has_been_closed;
287
10.1k
   }
288
289
void Channel::activate_session()
290
598
   {
291
598
   std::swap(m_active_state, m_pending_state);
292
598
   m_pending_state.reset();
293
598
294
598
   if(!m_active_state->version().is_datagram_protocol())
295
598
      {
296
598
      // TLS is easy just remove all but the current state
297
598
      const uint16_t current_epoch = sequence_numbers().current_write_epoch();
298
598
299
598
      const auto not_current_epoch =
300
2.39k
         [current_epoch](uint16_t epoch) { return (epoch != current_epoch); };
301
598
302
598
      map_remove_if(not_current_epoch, m_write_cipher_states);
303
598
      map_remove_if(not_current_epoch, m_read_cipher_states);
304
598
      }
305
598
306
598
   callbacks().tls_session_activated();
307
598
   }
308
309
size_t Channel::received_data(const std::vector<uint8_t>& buf)
310
0
   {
311
0
   return this->received_data(buf.data(), buf.size());
312
0
   }
313
314
size_t Channel::received_data(const uint8_t input[], size_t input_size)
315
10.8k
   {
316
10.8k
   const bool allow_epoch0_restart = m_is_datagram && m_is_server && policy().allow_dtls_epoch0_restart();
317
10.8k
318
10.8k
   try
319
10.8k
      {
320
167k
      while(input_size)
321
158k
         {
322
158k
         size_t consumed = 0;
323
158k
324
158k
         auto get_epoch = [this](uint16_t epoch) { return read_cipher_state_epoch(epoch); };
325
158k
326
158k
         const Record_Header record =
327
158k
            read_record(m_is_datagram,
328
158k
                        m_readbuf,
329
158k
                        input,
330
158k
                        input_size,
331
158k
                        consumed,
332
158k
                        m_record_buf,
333
158k
                        m_sequence_numbers.get(),
334
158k
                        get_epoch,
335
158k
                        allow_epoch0_restart);
336
158k
337
158k
         const size_t needed = record.needed();
338
158k
339
158k
         BOTAN_ASSERT(consumed > 0, "Got to eat something");
340
158k
341
158k
         BOTAN_ASSERT(consumed <= input_size,
342
158k
                      "Record reader consumed sane amount");
343
158k
344
158k
         input += consumed;
345
158k
         input_size -= consumed;
346
158k
347
158k
         BOTAN_ASSERT(input_size == 0 || needed == 0,
348
158k
                      "Got a full record or consumed all input");
349
158k
350
158k
         if(input_size == 0 && needed != 0)
351
1.16k
            return needed; // need more data to complete record
352
156k
353
156k
         // Ignore invalid records in DTLS
354
156k
         if(m_is_datagram && record.type() == NO_RECORD)
355
181
            {
356
181
            return 0;
357
181
            }
358
156k
359
156k
         if(m_record_buf.size() > MAX_PLAINTEXT_SIZE)
360
0
            throw TLS_Exception(Alert::RECORD_OVERFLOW,
361
0
                                "TLS plaintext record is larger than allowed maximum");
362
156k
363
156k
364
156k
         const bool epoch0_restart = m_is_datagram && record.epoch() == 0 && active_state();
365
156k
         BOTAN_ASSERT_IMPLICATION(epoch0_restart, allow_epoch0_restart, "Allowed state");
366
156k
367
156k
         const bool initial_record = epoch0_restart || (!pending_state() && !active_state());
368
156k
369
156k
         if(record.type() != ALERT)
370
84.9k
            {
371
84.9k
            if(initial_record)
372
31.2k
               {
373
31.2k
               // For initial records just check for basic sanity
374
31.2k
               if(record.version().major_version() != 3 &&
375
31.2k
                  record.version().major_version() != 0xFE)
376
30
                  {
377
30
                  throw TLS_Exception(Alert::PROTOCOL_VERSION,
378
30
                                      "Received unexpected record version in initial record");
379
30
                  }
380
53.7k
               }
381
53.7k
            else if(auto pending = pending_state())
382
53.7k
               {
383
53.7k
               if(pending->server_hello() != nullptr && record.version() != pending->version())
384
81
                  {
385
81
                  if(record.version() != pending->version())
386
81
                     {
387
81
                     throw TLS_Exception(Alert::PROTOCOL_VERSION,
388
81
                                         "Received unexpected record version");
389
81
                     }
390
0
                  }
391
0
               }
392
0
            else if(auto active = active_state())
393
0
               {
394
0
               if(record.version() != active->version())
395
0
                  {
396
0
                  throw TLS_Exception(Alert::PROTOCOL_VERSION,
397
0
                                      "Received unexpected record version");
398
0
                  }
399
156k
               }
400
84.9k
            }
401
156k
402
156k
         if(record.type() == HANDSHAKE || record.type() == CHANGE_CIPHER_SPEC)
403
84.7k
            {
404
84.7k
            if(m_has_been_closed)
405
2
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Received handshake data after connection closure");
406
84.7k
            process_handshake_ccs(m_record_buf, record.sequence(), record.type(), record.version(), epoch0_restart);
407
84.7k
            }
408
71.8k
         else if(record.type() == APPLICATION_DATA)
409
11
            {
410
11
            if(m_has_been_closed)
411
2
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Received application data after connection closure");
412
9
            if(pending_state() != nullptr)
413
6
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Can't interleave application and handshake data");
414
3
            process_application_data(record.sequence(), m_record_buf);
415
3
            }
416
71.8k
         else if(record.type() == ALERT)
417
70.2k
            {
418
70.2k
            process_alert(m_record_buf);
419
70.2k
            }
420
1.64k
         else if(record.type() != NO_RECORD)
421
119
            throw Unexpected_Message("Unexpected record type " +
422
119
                                     std::to_string(record.type()) +
423
119
                                     " from counterparty");
424
156k
         }
425
10.8k
426
10.8k
      return 0; // on a record boundary
427
2.82k
      }
428
2.82k
   catch(TLS_Exception& e)
429
2.82k
      {
430
2.82k
      send_fatal_alert(e.type());
431
2.82k
      throw;
432
2.82k
      }
433
571
   catch(Invalid_Authentication_Tag&)
434
571
      {
435
571
      send_fatal_alert(Alert::BAD_RECORD_MAC);
436
571
      throw;
437
571
      }
438
3.95k
   catch(Decoding_Error&)
439
3.95k
      {
440
3.95k
      send_fatal_alert(Alert::DECODE_ERROR);
441
3.95k
      throw;
442
3.95k
      }
443
366
   catch(...)
444
366
      {
445
366
      send_fatal_alert(Alert::INTERNAL_ERROR);
446
366
      throw;
447
366
      }
448
10.8k
   }
449
450
void Channel::process_handshake_ccs(const secure_vector<uint8_t>& record,
451
                                    uint64_t record_sequence,
452
                                    Record_Type record_type,
453
                                    Protocol_Version record_version,
454
                                    bool epoch0_restart)
455
84.7k
   {
456
84.7k
   if(!m_pending_state)
457
31.1k
      {
458
31.1k
      // No pending handshake, possibly new:
459
31.1k
      if(record_version.is_datagram_protocol() && !epoch0_restart)
460
586
         {
461
586
         if(m_sequence_numbers)
462
0
            {
463
0
            /*
464
0
            * Might be a peer retransmit under epoch - 1 in which
465
0
            * case we must retransmit last flight
466
0
            */
467
0
            sequence_numbers().read_accept(record_sequence);
468
0
469
0
            const uint16_t epoch = record_sequence >> 48;
470
0
471
0
            if(epoch == sequence_numbers().current_read_epoch())
472
0
               {
473
0
               create_handshake_state(record_version);
474
0
               }
475
0
            else if(epoch == sequence_numbers().current_read_epoch() - 1)
476
0
               {
477
0
               BOTAN_ASSERT(m_active_state, "Have active state here");
478
0
               m_active_state->handshake_io().add_record(record.data(),
479
0
                                                         record.size(),
480
0
                                                         record_type,
481
0
                                                         record_sequence);
482
0
               }
483
0
            }
484
586
         else
485
586
            {
486
586
            create_handshake_state(record_version);
487
586
            }
488
586
         }
489
30.5k
      else
490
30.5k
         {
491
30.5k
         create_handshake_state(record_version);
492
30.5k
         }
493
31.1k
      }
494
84.7k
495
84.7k
   // May have been created in above conditional
496
84.7k
   if(m_pending_state)
497
84.7k
      {
498
84.7k
      m_pending_state->handshake_io().add_record(record.data(),
499
84.7k
                                                 record.size(),
500
84.7k
                                                 record_type,
501
84.7k
                                                 record_sequence);
502
84.7k
503
136k
      while(auto pending = m_pending_state.get())
504
130k
         {
505
130k
         auto msg = pending->get_next_handshake_msg();
506
130k
507
130k
         if(msg.first == HANDSHAKE_NONE) // no full handshake yet
508
78.3k
            break;
509
52.2k
510
52.2k
         process_handshake_msg(active_state(), *pending,
511
52.2k
                               msg.first, msg.second, epoch0_restart);
512
52.2k
513
52.2k
         if(!m_pending_state)
514
598
            break;
515
52.2k
         }
516
84.7k
      }
517
84.7k
   }
518
519
void Channel::process_application_data(uint64_t seq_no, const secure_vector<uint8_t>& record)
520
3
   {
521
3
   if(!active_state())
522
3
      throw Unexpected_Message("Application data before handshake done");
523
0
524
0
   callbacks().tls_record_received(seq_no, record.data(), record.size());
525
0
   }
526
527
void Channel::process_alert(const secure_vector<uint8_t>& record)
528
70.2k
    {
529
70.2k
    Alert alert_msg(record);
530
70.2k
531
70.2k
    if(alert_msg.type() == Alert::NO_RENEGOTIATION)
532
51.5k
       m_pending_state.reset();
533
70.2k
534
70.2k
    callbacks().tls_alert(alert_msg);
535
70.2k
536
70.2k
    if(alert_msg.is_fatal())
537
2.22k
       {
538
2.22k
       if(auto active = active_state())
539
0
          m_session_manager.remove_entry(active->server_hello()->session_id());
540
2.22k
       }
541
70.2k
542
70.2k
    if(alert_msg.type() == Alert::CLOSE_NOTIFY)
543
2.40k
       send_warning_alert(Alert::CLOSE_NOTIFY); // reply in kind
544
70.2k
545
70.2k
    if(alert_msg.type() == Alert::CLOSE_NOTIFY || alert_msg.is_fatal())
546
2.90k
       {
547
2.90k
       m_has_been_closed = true;
548
2.90k
       }
549
70.2k
    }
550
551
void Channel::write_record(Connection_Cipher_State* cipher_state, uint16_t epoch,
552
                           uint8_t record_type, const uint8_t input[], size_t length)
553
76.8k
   {
554
76.8k
   BOTAN_ASSERT(m_pending_state || m_active_state, "Some connection state exists");
555
76.8k
556
76.8k
   const Protocol_Version record_version =
557
76.7k
      (m_pending_state) ? (m_pending_state->version()) : (m_active_state->version());
558
76.7k
559
76.7k
   TLS::write_record(m_writebuf,
560
76.7k
                     record_type,
561
76.7k
                     record_version,
562
76.7k
                     sequence_numbers().next_write_sequence(epoch),
563
76.7k
                     input,
564
76.7k
                     length,
565
76.7k
                     cipher_state,
566
76.7k
                     m_rng);
567
76.7k
568
76.7k
   callbacks().tls_emit_data(m_writebuf.data(), m_writebuf.size());
569
76.7k
   }
570
571
void Channel::send_record_array(uint16_t epoch, uint8_t type, const uint8_t input[], size_t length)
572
76.8k
   {
573
76.8k
   if(length == 0)
574
0
      return;
575
76.8k
576
76.8k
   /*
577
76.8k
   * In versions without an explicit IV field (only TLS v1.0 now that
578
76.8k
   * SSLv3 has been removed) send a single byte record first to randomize
579
76.8k
   * the following (implicit) IV of the following record.
580
76.8k
   *
581
76.8k
   * This isn't needed in TLS v1.1 or higher.
582
76.8k
   *
583
76.8k
   * An empty record also works but apparently some implementations do
584
76.8k
   * not like this (https://bugzilla.mozilla.org/show_bug.cgi?id=665814)
585
76.8k
   *
586
76.8k
   * See https://www.openssl.org/~bodo/tls-cbc.txt for background.
587
76.8k
   */
588
76.8k
589
76.8k
   auto cipher_state = write_cipher_state_epoch(epoch);
590
76.8k
591
76.8k
   if(type == APPLICATION_DATA && m_active_state->version().supports_explicit_cbc_ivs() == false)
592
0
      {
593
0
      while(length)
594
0
         {
595
0
         write_record(cipher_state.get(), epoch, type, input, 1);
596
0
         input += 1;
597
0
         length -= 1;
598
0
599
0
         const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
600
0
         write_record(cipher_state.get(), epoch, type, input, sending);
601
0
602
0
         input += sending;
603
0
         length -= sending;
604
0
         }
605
0
      }
606
76.8k
   else
607
76.8k
      {
608
153k
      while(length)
609
76.8k
         {
610
76.8k
         const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
611
76.8k
         write_record(cipher_state.get(), epoch, type, input, sending);
612
76.8k
613
76.8k
         input += sending;
614
76.8k
         length -= sending;
615
76.8k
         }
616
76.8k
      }
617
76.8k
   }
618
619
void Channel::send_record(uint8_t record_type, const std::vector<uint8_t>& record)
620
76.9k
   {
621
76.9k
   send_record_array(sequence_numbers().current_write_epoch(),
622
76.9k
                     record_type, record.data(), record.size());
623
76.9k
   }
624
625
void Channel::send_record_under_epoch(uint16_t epoch, uint8_t record_type,
626
                                      const std::vector<uint8_t>& record)
627
0
   {
628
0
   send_record_array(epoch, record_type, record.data(), record.size());
629
0
   }
630
631
void Channel::send(const uint8_t buf[], size_t buf_size)
632
0
   {
633
0
   if(!is_active())
634
0
      throw Invalid_State("Data cannot be sent on inactive TLS connection");
635
0
636
0
   send_record_array(sequence_numbers().current_write_epoch(),
637
0
                     APPLICATION_DATA, buf, buf_size);
638
0
   }
639
640
void Channel::send(const std::string& string)
641
0
   {
642
0
   this->send(cast_char_ptr_to_uint8(string.data()), string.size());
643
0
   }
644
645
void Channel::send_alert(const Alert& alert)
646
10.1k
   {
647
10.1k
   if(alert.is_valid() && !is_closed())
648
7.74k
      {
649
7.74k
      try
650
7.74k
         {
651
7.74k
         send_record(ALERT, alert.serialize());
652
7.74k
         }
653
7.74k
      catch(...) { /* swallow it */ }
654
7.74k
      }
655
10.1k
656
10.1k
   if(alert.type() == Alert::NO_RENEGOTIATION)
657
0
      m_pending_state.reset();
658
10.1k
659
10.1k
   if(alert.is_fatal())
660
7.72k
      if(auto active = active_state())
661
344
         m_session_manager.remove_entry(active->server_hello()->session_id());
662
10.1k
663
10.1k
   if(alert.is_fatal())
664
7.72k
      reset_state();
665
10.1k
666
10.1k
   if(alert.type() == Alert::CLOSE_NOTIFY || alert.is_fatal())
667
10.1k
      {
668
10.1k
      m_has_been_closed = true;
669
10.1k
      }
670
10.1k
   }
671
672
void Channel::secure_renegotiation_check(const Client_Hello* client_hello)
673
22.1k
   {
674
22.1k
   const bool secure_renegotiation = client_hello->secure_renegotiation();
675
22.1k
676
22.1k
   if(auto active = active_state())
677
0
      {
678
0
      const bool active_sr = active->client_hello()->secure_renegotiation();
679
0
680
0
      if(active_sr != secure_renegotiation)
681
0
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
682
0
                             "Client changed its mind about secure renegotiation");
683
22.1k
      }
684
22.1k
685
22.1k
   if(secure_renegotiation)
686
6.89k
      {
687
6.89k
      const std::vector<uint8_t>& data = client_hello->renegotiation_info();
688
6.89k
689
6.89k
      if(data != secure_renegotiation_data_for_client_hello())
690
1
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
691
1
                             "Client sent bad values for secure renegotiation");
692
6.89k
      }
693
22.1k
   }
694
695
void Channel::secure_renegotiation_check(const Server_Hello* server_hello)
696
20.5k
   {
697
20.5k
   const bool secure_renegotiation = server_hello->secure_renegotiation();
698
20.5k
699
20.5k
   if(auto active = active_state())
700
0
      {
701
0
      const bool active_sr = active->server_hello()->secure_renegotiation();
702
0
703
0
      if(active_sr != secure_renegotiation)
704
0
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
705
0
                             "Server changed its mind about secure renegotiation");
706
20.5k
      }
707
20.5k
708
20.5k
   if(secure_renegotiation)
709
4.47k
      {
710
4.47k
      const std::vector<uint8_t>& data = server_hello->renegotiation_info();
711
4.47k
712
4.47k
      if(data != secure_renegotiation_data_for_server_hello())
713
1
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
714
1
                             "Server sent bad values for secure renegotiation");
715
4.47k
      }
716
20.5k
   }
717
718
std::vector<uint8_t> Channel::secure_renegotiation_data_for_client_hello() const
719
12.7k
   {
720
12.7k
   if(auto active = active_state())
721
0
      return active->client_finished()->verify_data();
722
12.7k
   return std::vector<uint8_t>();
723
12.7k
   }
724
725
std::vector<uint8_t> Channel::secure_renegotiation_data_for_server_hello() const
726
20.6k
   {
727
20.6k
   if(auto active = active_state())
728
0
      {
729
0
      std::vector<uint8_t> buf = active->client_finished()->verify_data();
730
0
      buf += active->server_finished()->verify_data();
731
0
      return buf;
732
0
      }
733
20.6k
734
20.6k
   return std::vector<uint8_t>();
735
20.6k
   }
736
737
bool Channel::secure_renegotiation_supported() const
738
0
   {
739
0
   if(auto active = active_state())
740
0
      return active->server_hello()->secure_renegotiation();
741
0
742
0
   if(auto pending = pending_state())
743
0
      if(auto hello = pending->server_hello())
744
0
         return hello->secure_renegotiation();
745
0
746
0
   return false;
747
0
   }
748
749
SymmetricKey Channel::key_material_export(const std::string& label,
750
                                          const std::string& context,
751
                                          size_t length) const
752
0
   {
753
0
   if(auto active = active_state())
754
0
      {
755
0
      if(pending_state() != nullptr)
756
0
         throw Invalid_State("Channel::key_material_export cannot export during renegotiation");
757
0
758
0
      std::unique_ptr<KDF> prf(active->protocol_specific_prf());
759
0
760
0
      const secure_vector<uint8_t>& master_secret =
761
0
         active->session_keys().master_secret();
762
0
763
0
      std::vector<uint8_t> salt;
764
0
      salt += active->client_hello()->random();
765
0
      salt += active->server_hello()->random();
766
0
767
0
      if(context != "")
768
0
         {
769
0
         size_t context_size = context.length();
770
0
         if(context_size > 0xFFFF)
771
0
            throw Invalid_Argument("key_material_export context is too long");
772
0
         salt.push_back(get_byte(0, static_cast<uint16_t>(context_size)));
773
0
         salt.push_back(get_byte(1, static_cast<uint16_t>(context_size)));
774
0
         salt += to_byte_vector(context);
775
0
         }
776
0
777
0
      return prf->derive_key(length, master_secret, salt, to_byte_vector(label));
778
0
      }
779
0
   else
780
0
      {
781
0
      throw Invalid_State("Channel::key_material_export connection not active");
782
0
      }
783
0
   }
784
785
}
786
787
}