Coverage Report

Created: 2020-02-14 15:38

/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
11.2k
   {
41
11.2k
   init(reserved_io_buffer_size);
42
11.2k
   }
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
11.2k
   {
75
11.2k
   /* epoch 0 is plaintext, thus null cipher state */
76
11.2k
   m_write_cipher_states[0] = nullptr;
77
11.2k
   m_read_cipher_states[0] = nullptr;
78
11.2k
79
11.2k
   m_writebuf.reserve(io_buf_sz);
80
11.2k
   m_readbuf.reserve(io_buf_sz);
81
11.2k
   }
82
83
void Channel::reset_state()
84
7.94k
   {
85
7.94k
   m_active_state.reset();
86
7.94k
   m_pending_state.reset();
87
7.94k
   m_readbuf.clear();
88
7.94k
   m_write_cipher_states.clear();
89
7.94k
   m_read_cipher_states.clear();
90
7.94k
   }
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
11.2k
   {
109
11.2k
   // So unique_ptr destructors run correctly
110
11.2k
   }
111
112
Connection_Sequence_Numbers& Channel::sequence_numbers() const
113
194k
   {
114
194k
   BOTAN_ASSERT(m_sequence_numbers, "Have a sequence numbers object");
115
194k
   return *m_sequence_numbers;
116
194k
   }
117
118
std::shared_ptr<Connection_Cipher_State> Channel::read_cipher_state_epoch(uint16_t epoch) const
119
1.10k
   {
120
1.10k
   auto i = m_read_cipher_states.find(epoch);
121
1.10k
   if(i == m_read_cipher_states.end())
122
80
      throw Internal_Error("TLS::Channel No read cipherstate for epoch " + std::to_string(epoch));
123
1.02k
   return i->second;
124
1.02k
   }
125
126
std::shared_ptr<Connection_Cipher_State> Channel::write_cipher_state_epoch(uint16_t epoch) const
127
94.2k
   {
128
94.2k
   auto i = m_write_cipher_states.find(epoch);
129
94.2k
   if(i == m_write_cipher_states.end())
130
0
      throw Internal_Error("TLS::Channel No write cipherstate for epoch " + std::to_string(epoch));
131
94.2k
   return i->second;
132
94.2k
   }
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
461
   {
143
461
   return callbacks().tls_session_established(session);
144
461
   }
145
146
Handshake_State& Channel::create_handshake_state(Protocol_Version version)
147
46.3k
   {
148
46.3k
   if(pending_state())
149
0
      throw Internal_Error("create_handshake_state called during handshake");
150
46.3k
151
46.3k
   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
46.3k
      }
162
46.3k
163
46.3k
   if(!m_sequence_numbers)
164
11.0k
      {
165
11.0k
      if(version.is_datagram_protocol())
166
600
         m_sequence_numbers.reset(new Datagram_Sequence_Numbers);
167
10.4k
      else
168
10.4k
         m_sequence_numbers.reset(new Stream_Sequence_Numbers);
169
11.0k
      }
170
46.3k
171
46.3k
   using namespace std::placeholders;
172
46.3k
173
46.3k
   std::unique_ptr<Handshake_IO> io;
174
46.3k
   if(version.is_datagram_protocol())
175
600
      {
176
600
      io.reset(new Datagram_Handshake_IO(
177
600
                  std::bind(&Channel::send_record_under_epoch, this, _1, _2, _3),
178
600
                  sequence_numbers(),
179
600
                  static_cast<uint16_t>(m_policy.dtls_default_mtu()),
180
600
                  m_policy.dtls_initial_timeout(),
181
600
                  m_policy.dtls_maximum_timeout()));
182
600
      }
183
45.7k
   else
184
45.7k
      {
185
45.7k
      io.reset(new Stream_Handshake_IO(std::bind(&Channel::send_record, this, _1, _2)));
186
45.7k
      }
187
46.3k
188
46.3k
   m_pending_state.reset(new_handshake_state(io.release()));
189
46.3k
190
46.3k
   if(auto active = active_state())
191
0
      m_pending_state->set_version(active->version());
192
46.3k
193
46.3k
   return *m_pending_state.get();
194
46.3k
   }
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.37k
   {
224
1.37k
   auto pending = pending_state();
225
1.37k
226
1.37k
   BOTAN_ASSERT(pending && pending->server_hello(),
227
1.37k
                "Have received server hello");
228
1.37k
229
1.37k
   if(pending->server_hello()->compression_method() != 0)
230
0
      throw Internal_Error("Negotiated unknown compression algorithm");
231
1.37k
232
1.37k
   sequence_numbers().new_read_cipher_state();
233
1.37k
234
1.37k
   const uint16_t epoch = sequence_numbers().current_read_epoch();
235
1.37k
236
1.37k
   BOTAN_ASSERT(m_read_cipher_states.count(epoch) == 0,
237
1.37k
                "No read cipher state currently set for next epoch");
238
1.37k
239
1.37k
   // flip side as we are reading
240
1.37k
   std::shared_ptr<Connection_Cipher_State> read_state(
241
1.37k
      new Connection_Cipher_State(pending->version(),
242
1.37k
                                  (side == CLIENT) ? SERVER : CLIENT,
243
1.37k
                                  false,
244
1.37k
                                  pending->ciphersuite(),
245
1.37k
                                  pending->session_keys(),
246
1.37k
                                  pending->server_hello()->supports_encrypt_then_mac()));
247
1.37k
248
1.37k
   m_read_cipher_states[epoch] = read_state;
249
1.37k
   }
250
251
void Channel::change_cipher_spec_writer(Connection_Side side)
252
1.29k
   {
253
1.29k
   auto pending = pending_state();
254
1.29k
255
1.29k
   BOTAN_ASSERT(pending && pending->server_hello(),
256
1.29k
                "Have received server hello");
257
1.29k
258
1.29k
   if(pending->server_hello()->compression_method() != 0)
259
0
      throw Internal_Error("Negotiated unknown compression algorithm");
260
1.29k
261
1.29k
   sequence_numbers().new_write_cipher_state();
262
1.29k
263
1.29k
   const uint16_t epoch = sequence_numbers().current_write_epoch();
264
1.29k
265
1.29k
   BOTAN_ASSERT(m_write_cipher_states.count(epoch) == 0,
266
1.29k
                "No write cipher state currently set for next epoch");
267
1.29k
268
1.29k
   std::shared_ptr<Connection_Cipher_State> write_state(
269
1.29k
      new Connection_Cipher_State(pending->version(),
270
1.29k
                                  side,
271
1.29k
                                  true,
272
1.29k
                                  pending->ciphersuite(),
273
1.29k
                                  pending->session_keys(),
274
1.29k
                                  pending->server_hello()->supports_encrypt_then_mac()));
275
1.29k
276
1.29k
   m_write_cipher_states[epoch] = write_state;
277
1.29k
   }
278
279
bool Channel::is_active() const
280
0
   {
281
0
   if(is_closed())
282
0
      return false;
283
0
   return (active_state() != nullptr);
284
0
   }
285
286
bool Channel::is_closed() const
287
10.2k
   {
288
10.2k
   return m_has_been_closed;
289
10.2k
   }
290
291
void Channel::activate_session()
292
461
   {
293
461
   std::swap(m_active_state, m_pending_state);
294
461
   m_pending_state.reset();
295
461
296
461
   if(!m_active_state->version().is_datagram_protocol())
297
461
      {
298
461
      // TLS is easy just remove all but the current state
299
461
      const uint16_t current_epoch = sequence_numbers().current_write_epoch();
300
461
301
461
      const auto not_current_epoch =
302
1.84k
         [current_epoch](uint16_t epoch) { return (epoch != current_epoch); };
303
461
304
461
      map_remove_if(not_current_epoch, m_write_cipher_states);
305
461
      map_remove_if(not_current_epoch, m_read_cipher_states);
306
461
      }
307
461
308
461
   callbacks().tls_session_activated();
309
461
   }
310
311
size_t Channel::received_data(const std::vector<uint8_t>& buf)
312
0
   {
313
0
   return this->received_data(buf.data(), buf.size());
314
0
   }
315
316
size_t Channel::received_data(const uint8_t input[], size_t input_size)
317
11.2k
   {
318
11.2k
   const bool allow_epoch0_restart = m_is_datagram && m_is_server && policy().allow_dtls_epoch0_restart();
319
11.2k
320
11.2k
   try
321
11.2k
      {
322
161k
      while(input_size)
323
151k
         {
324
151k
         size_t consumed = 0;
325
151k
326
151k
         auto get_epoch = [this](uint16_t epoch) { return read_cipher_state_epoch(epoch); };
327
151k
328
151k
         const Record_Header record =
329
151k
            read_record(m_is_datagram,
330
151k
                        m_readbuf,
331
151k
                        input,
332
151k
                        input_size,
333
151k
                        consumed,
334
151k
                        m_record_buf,
335
151k
                        m_sequence_numbers.get(),
336
151k
                        get_epoch,
337
151k
                        allow_epoch0_restart);
338
151k
339
151k
         const size_t needed = record.needed();
340
151k
341
151k
         BOTAN_ASSERT(consumed > 0, "Got to eat something");
342
151k
343
151k
         BOTAN_ASSERT(consumed <= input_size,
344
151k
                      "Record reader consumed sane amount");
345
151k
346
151k
         input += consumed;
347
151k
         input_size -= consumed;
348
151k
349
151k
         BOTAN_ASSERT(input_size == 0 || needed == 0,
350
151k
                      "Got a full record or consumed all input");
351
151k
352
151k
         if(input_size == 0 && needed != 0)
353
1.16k
            return needed; // need more data to complete record
354
150k
355
150k
         // Ignore invalid records in DTLS
356
150k
         if(m_is_datagram && record.type() == NO_RECORD)
357
171
            {
358
171
            return 0;
359
171
            }
360
150k
361
150k
         if(m_record_buf.size() > MAX_PLAINTEXT_SIZE)
362
0
            throw TLS_Exception(Alert::RECORD_OVERFLOW,
363
0
                                "TLS plaintext record is larger than allowed maximum");
364
150k
365
150k
366
150k
         const bool epoch0_restart = m_is_datagram && record.epoch() == 0 && active_state();
367
150k
         BOTAN_ASSERT_IMPLICATION(epoch0_restart, allow_epoch0_restart, "Allowed state");
368
150k
369
150k
         const bool initial_record = epoch0_restart || (!pending_state() && !active_state());
370
150k
371
150k
         if(record.type() != ALERT)
372
82.3k
            {
373
82.3k
            if(initial_record)
374
40.5k
               {
375
40.5k
               // For initial records just check for basic sanity
376
40.5k
               if(record.version().major_version() != 3 &&
377
40.5k
                  record.version().major_version() != 0xFE)
378
20
                  {
379
20
                  throw TLS_Exception(Alert::PROTOCOL_VERSION,
380
20
                                      "Received unexpected record version in initial record");
381
20
                  }
382
41.8k
               }
383
41.8k
            else if(auto pending = pending_state())
384
41.8k
               {
385
41.8k
               if(pending->server_hello() != nullptr && record.version() != pending->version())
386
81
                  {
387
81
                  if(record.version() != pending->version())
388
81
                     {
389
81
                     throw TLS_Exception(Alert::PROTOCOL_VERSION,
390
81
                                         "Received unexpected record version");
391
81
                     }
392
0
                  }
393
0
               }
394
0
            else if(auto active = active_state())
395
0
               {
396
0
               if(record.version() != active->version())
397
0
                  {
398
0
                  throw TLS_Exception(Alert::PROTOCOL_VERSION,
399
0
                                      "Received unexpected record version");
400
0
                  }
401
150k
               }
402
82.3k
            }
403
150k
404
150k
         if(record.type() == HANDSHAKE || record.type() == CHANGE_CIPHER_SPEC)
405
82.1k
            {
406
82.1k
            if(m_has_been_closed)
407
4
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Received handshake data after connection closure");
408
82.1k
            process_handshake_ccs(m_record_buf, record.sequence(), record.type(), record.version(), epoch0_restart);
409
82.1k
            }
410
68.2k
         else if(record.type() == APPLICATION_DATA)
411
12
            {
412
12
            if(m_has_been_closed)
413
2
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Received application data after connection closure");
414
10
            if(pending_state() != nullptr)
415
6
               throw TLS_Exception(Alert::UNEXPECTED_MESSAGE, "Can't interleave application and handshake data");
416
4
            process_application_data(record.sequence(), m_record_buf);
417
4
            }
418
68.2k
         else if(record.type() == ALERT)
419
66.6k
            {
420
66.6k
            process_alert(m_record_buf);
421
66.6k
            }
422
1.63k
         else if(record.type() != NO_RECORD)
423
96
            throw Unexpected_Message("Unexpected record type " +
424
96
                                     std::to_string(record.type()) +
425
96
                                     " from counterparty");
426
150k
         }
427
11.2k
428
11.2k
      return 0; // on a record boundary
429
2.83k
      }
430
2.83k
   catch(TLS_Exception& e)
431
2.83k
      {
432
2.83k
      send_fatal_alert(e.type());
433
2.83k
      throw;
434
2.83k
      }
435
633
   catch(Invalid_Authentication_Tag&)
436
633
      {
437
633
      send_fatal_alert(Alert::BAD_RECORD_MAC);
438
633
      throw;
439
633
      }
440
4.08k
   catch(Decoding_Error&)
441
4.08k
      {
442
4.08k
      send_fatal_alert(Alert::DECODE_ERROR);
443
4.08k
      throw;
444
4.08k
      }
445
388
   catch(...)
446
388
      {
447
388
      send_fatal_alert(Alert::INTERNAL_ERROR);
448
388
      throw;
449
388
      }
450
11.2k
   }
451
452
void Channel::process_handshake_ccs(const secure_vector<uint8_t>& record,
453
                                    uint64_t record_sequence,
454
                                    Record_Type record_type,
455
                                    Protocol_Version record_version,
456
                                    bool epoch0_restart)
457
82.1k
   {
458
82.1k
   if(!m_pending_state)
459
40.5k
      {
460
40.5k
      // No pending handshake, possibly new:
461
40.5k
      if(record_version.is_datagram_protocol() && !epoch0_restart)
462
600
         {
463
600
         if(m_sequence_numbers)
464
0
            {
465
0
            /*
466
0
            * Might be a peer retransmit under epoch - 1 in which
467
0
            * case we must retransmit last flight
468
0
            */
469
0
            sequence_numbers().read_accept(record_sequence);
470
0
471
0
            const uint16_t epoch = record_sequence >> 48;
472
0
473
0
            if(epoch == sequence_numbers().current_read_epoch())
474
0
               {
475
0
               create_handshake_state(record_version);
476
0
               }
477
0
            else if(epoch == sequence_numbers().current_read_epoch() - 1)
478
0
               {
479
0
               BOTAN_ASSERT(m_active_state, "Have active state here");
480
0
               m_active_state->handshake_io().add_record(record.data(),
481
0
                                                         record.size(),
482
0
                                                         record_type,
483
0
                                                         record_sequence);
484
0
               }
485
0
            }
486
600
         else
487
600
            {
488
600
            create_handshake_state(record_version);
489
600
            }
490
600
         }
491
39.9k
      else
492
39.9k
         {
493
39.9k
         create_handshake_state(record_version);
494
39.9k
         }
495
40.5k
      }
496
82.1k
497
82.1k
   // May have been created in above conditional
498
82.1k
   if(m_pending_state)
499
82.1k
      {
500
82.1k
      m_pending_state->handshake_io().add_record(record.data(),
501
82.1k
                                                 record.size(),
502
82.1k
                                                 record_type,
503
82.1k
                                                 record_sequence);
504
82.1k
505
140k
      while(auto pending = m_pending_state.get())
506
133k
         {
507
133k
         auto msg = pending->get_next_handshake_msg();
508
133k
509
133k
         if(msg.first == HANDSHAKE_NONE) // no full handshake yet
510
75.6k
            break;
511
58.3k
512
58.3k
         process_handshake_msg(active_state(), *pending,
513
58.3k
                               msg.first, msg.second, epoch0_restart);
514
58.3k
515
58.3k
         if(!m_pending_state)
516
461
            break;
517
58.3k
         }
518
82.1k
      }
519
82.1k
   }
520
521
void Channel::process_application_data(uint64_t seq_no, const secure_vector<uint8_t>& record)
522
4
   {
523
4
   if(!active_state())
524
4
      throw Unexpected_Message("Application data before handshake done");
525
0
526
0
   callbacks().tls_record_received(seq_no, record.data(), record.size());
527
0
   }
528
529
void Channel::process_alert(const secure_vector<uint8_t>& record)
530
66.6k
    {
531
66.6k
    Alert alert_msg(record);
532
66.6k
533
66.6k
    if(alert_msg.type() == Alert::NO_RENEGOTIATION)
534
41.6k
       m_pending_state.reset();
535
66.6k
536
66.6k
    callbacks().tls_alert(alert_msg);
537
66.6k
538
66.6k
    if(alert_msg.is_fatal())
539
2.07k
       {
540
2.07k
       if(auto active = active_state())
541
0
          m_session_manager.remove_entry(active->server_hello()->session_id());
542
2.07k
       }
543
66.6k
544
66.6k
    if(alert_msg.type() == Alert::CLOSE_NOTIFY)
545
2.33k
       send_warning_alert(Alert::CLOSE_NOTIFY); // reply in kind
546
66.6k
547
66.6k
    if(alert_msg.type() == Alert::CLOSE_NOTIFY || alert_msg.is_fatal())
548
2.86k
       {
549
2.86k
       m_has_been_closed = true;
550
2.86k
       }
551
66.6k
    }
552
553
void Channel::write_record(Connection_Cipher_State* cipher_state, uint16_t epoch,
554
                           uint8_t record_type, const uint8_t input[], size_t length)
555
94.2k
   {
556
94.2k
   BOTAN_ASSERT(m_pending_state || m_active_state, "Some connection state exists");
557
94.2k
558
94.2k
   const Protocol_Version record_version =
559
94.1k
      (m_pending_state) ? (m_pending_state->version()) : (m_active_state->version());
560
94.1k
561
94.1k
   TLS::write_record(m_writebuf,
562
94.1k
                     record_type,
563
94.1k
                     record_version,
564
94.1k
                     sequence_numbers().next_write_sequence(epoch),
565
94.1k
                     input,
566
94.1k
                     length,
567
94.1k
                     cipher_state,
568
94.1k
                     m_rng);
569
94.1k
570
94.1k
   callbacks().tls_emit_data(m_writebuf.data(), m_writebuf.size());
571
94.1k
   }
572
573
void Channel::send_record_array(uint16_t epoch, uint8_t type, const uint8_t input[], size_t length)
574
94.2k
   {
575
94.2k
   if(length == 0)
576
0
      return;
577
94.2k
578
94.2k
   /*
579
94.2k
   * In versions without an explicit IV field (only TLS v1.0 now that
580
94.2k
   * SSLv3 has been removed) send a single byte record first to randomize
581
94.2k
   * the following (implicit) IV of the following record.
582
94.2k
   *
583
94.2k
   * This isn't needed in TLS v1.1 or higher.
584
94.2k
   *
585
94.2k
   * An empty record also works but apparently some implementations do
586
94.2k
   * not like this (https://bugzilla.mozilla.org/show_bug.cgi?id=665814)
587
94.2k
   *
588
94.2k
   * See https://www.openssl.org/~bodo/tls-cbc.txt for background.
589
94.2k
   */
590
94.2k
591
94.2k
   auto cipher_state = write_cipher_state_epoch(epoch);
592
94.2k
593
94.2k
   if(type == APPLICATION_DATA && m_active_state->version().supports_explicit_cbc_ivs() == false)
594
0
      {
595
0
      while(length)
596
0
         {
597
0
         write_record(cipher_state.get(), epoch, type, input, 1);
598
0
         input += 1;
599
0
         length -= 1;
600
0
601
0
         const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
602
0
         write_record(cipher_state.get(), epoch, type, input, sending);
603
0
604
0
         input += sending;
605
0
         length -= sending;
606
0
         }
607
0
      }
608
94.2k
   else
609
94.2k
      {
610
188k
      while(length)
611
94.2k
         {
612
94.2k
         const size_t sending = std::min<size_t>(length, MAX_PLAINTEXT_SIZE);
613
94.2k
         write_record(cipher_state.get(), epoch, type, input, sending);
614
94.2k
615
94.2k
         input += sending;
616
94.2k
         length -= sending;
617
94.2k
         }
618
94.2k
      }
619
94.2k
   }
620
621
void Channel::send_record(uint8_t record_type, const std::vector<uint8_t>& record)
622
94.3k
   {
623
94.3k
   send_record_array(sequence_numbers().current_write_epoch(),
624
94.3k
                     record_type, record.data(), record.size());
625
94.3k
   }
626
627
void Channel::send_record_under_epoch(uint16_t epoch, uint8_t record_type,
628
                                      const std::vector<uint8_t>& record)
629
0
   {
630
0
   send_record_array(epoch, record_type, record.data(), record.size());
631
0
   }
632
633
void Channel::send(const uint8_t buf[], size_t buf_size)
634
0
   {
635
0
   if(!is_active())
636
0
      throw Invalid_State("Data cannot be sent on inactive TLS connection");
637
0
638
0
   send_record_array(sequence_numbers().current_write_epoch(),
639
0
                     APPLICATION_DATA, buf, buf_size);
640
0
   }
641
642
void Channel::send(const std::string& string)
643
0
   {
644
0
   this->send(cast_char_ptr_to_uint8(string.data()), string.size());
645
0
   }
646
647
void Channel::send_alert(const Alert& alert)
648
10.2k
   {
649
10.2k
   if(alert.is_valid() && !is_closed())
650
7.97k
      {
651
7.97k
      try
652
7.97k
         {
653
7.97k
         send_record(ALERT, alert.serialize());
654
7.97k
         }
655
7.97k
      catch(...) { /* swallow it */ }
656
7.97k
      }
657
10.2k
658
10.2k
   if(alert.type() == Alert::NO_RENEGOTIATION)
659
0
      m_pending_state.reset();
660
10.2k
661
10.2k
   if(alert.is_fatal())
662
7.94k
      if(auto active = active_state())
663
292
         m_session_manager.remove_entry(active->server_hello()->session_id());
664
10.2k
665
10.2k
   if(alert.is_fatal())
666
7.94k
      reset_state();
667
10.2k
668
10.2k
   if(alert.type() == Alert::CLOSE_NOTIFY || alert.is_fatal())
669
10.2k
      {
670
10.2k
      m_has_been_closed = true;
671
10.2k
      }
672
10.2k
   }
673
674
void Channel::secure_renegotiation_check(const Client_Hello* client_hello)
675
29.5k
   {
676
29.5k
   const bool secure_renegotiation = client_hello->secure_renegotiation();
677
29.5k
678
29.5k
   if(auto active = active_state())
679
0
      {
680
0
      const bool active_sr = active->client_hello()->secure_renegotiation();
681
0
682
0
      if(active_sr != secure_renegotiation)
683
0
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
684
0
                             "Client changed its mind about secure renegotiation");
685
29.5k
      }
686
29.5k
687
29.5k
   if(secure_renegotiation)
688
9.88k
      {
689
9.88k
      const std::vector<uint8_t>& data = client_hello->renegotiation_info();
690
9.88k
691
9.88k
      if(data != secure_renegotiation_data_for_client_hello())
692
1
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
693
1
                             "Client sent bad values for secure renegotiation");
694
9.88k
      }
695
29.5k
   }
696
697
void Channel::secure_renegotiation_check(const Server_Hello* server_hello)
698
27.8k
   {
699
27.8k
   const bool secure_renegotiation = server_hello->secure_renegotiation();
700
27.8k
701
27.8k
   if(auto active = active_state())
702
0
      {
703
0
      const bool active_sr = active->server_hello()->secure_renegotiation();
704
0
705
0
      if(active_sr != secure_renegotiation)
706
0
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
707
0
                             "Server changed its mind about secure renegotiation");
708
27.8k
      }
709
27.8k
710
27.8k
   if(secure_renegotiation)
711
7.18k
      {
712
7.18k
      const std::vector<uint8_t>& data = server_hello->renegotiation_info();
713
7.18k
714
7.18k
      if(data != secure_renegotiation_data_for_server_hello())
715
1
         throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
716
1
                             "Server sent bad values for secure renegotiation");
717
7.18k
      }
718
27.8k
   }
719
720
std::vector<uint8_t> Channel::secure_renegotiation_data_for_client_hello() const
721
15.7k
   {
722
15.7k
   if(auto active = active_state())
723
0
      return active->client_finished()->verify_data();
724
15.7k
   return std::vector<uint8_t>();
725
15.7k
   }
726
727
std::vector<uint8_t> Channel::secure_renegotiation_data_for_server_hello() const
728
30.5k
   {
729
30.5k
   if(auto active = active_state())
730
0
      {
731
0
      std::vector<uint8_t> buf = active->client_finished()->verify_data();
732
0
      buf += active->server_finished()->verify_data();
733
0
      return buf;
734
0
      }
735
30.5k
736
30.5k
   return std::vector<uint8_t>();
737
30.5k
   }
738
739
bool Channel::secure_renegotiation_supported() const
740
0
   {
741
0
   if(auto active = active_state())
742
0
      return active->server_hello()->secure_renegotiation();
743
0
744
0
   if(auto pending = pending_state())
745
0
      if(auto hello = pending->server_hello())
746
0
         return hello->secure_renegotiation();
747
0
748
0
   return false;
749
0
   }
750
751
SymmetricKey Channel::key_material_export(const std::string& label,
752
                                          const std::string& context,
753
                                          size_t length) const
754
0
   {
755
0
   if(auto active = active_state())
756
0
      {
757
0
      if(pending_state() != nullptr)
758
0
         throw Invalid_State("Channel::key_material_export cannot export during renegotiation");
759
0
760
0
      std::unique_ptr<KDF> prf(active->protocol_specific_prf());
761
0
762
0
      const secure_vector<uint8_t>& master_secret =
763
0
         active->session_keys().master_secret();
764
0
765
0
      std::vector<uint8_t> salt;
766
0
      salt += active->client_hello()->random();
767
0
      salt += active->server_hello()->random();
768
0
769
0
      if(context != "")
770
0
         {
771
0
         size_t context_size = context.length();
772
0
         if(context_size > 0xFFFF)
773
0
            throw Invalid_Argument("key_material_export context is too long");
774
0
         salt.push_back(get_byte(0, static_cast<uint16_t>(context_size)));
775
0
         salt.push_back(get_byte(1, static_cast<uint16_t>(context_size)));
776
0
         salt += to_byte_vector(context);
777
0
         }
778
0
779
0
      return prf->derive_key(length, master_secret, salt, to_byte_vector(label));
780
0
      }
781
0
   else
782
0
      {
783
0
      throw Invalid_State("Channel::key_material_export connection not active");
784
0
      }
785
0
   }
786
787
}
788
789
}