Botan  1.11.15
src/lib/tls/tls_channel.cpp
Go to the documentation of this file.
00001 /*
00002 * TLS Channels
00003 * (C) 2011,2012,2014,2015 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/tls_channel.h>
00009 #include <botan/internal/tls_handshake_state.h>
00010 #include <botan/internal/tls_messages.h>
00011 #include <botan/internal/tls_heartbeats.h>
00012 #include <botan/internal/tls_record.h>
00013 #include <botan/internal/tls_seq_numbers.h>
00014 #include <botan/internal/rounding.h>
00015 #include <botan/internal/stl_util.h>
00016 #include <botan/loadstor.h>
00017 
00018 namespace Botan {
00019 
00020 namespace TLS {
00021 
00022 Channel::Channel(output_fn output_fn,
00023                  data_cb data_cb,
00024                  alert_cb alert_cb,
00025                  handshake_cb handshake_cb,
00026                  Session_Manager& session_manager,
00027                  RandomNumberGenerator& rng,
00028                  bool is_datagram,
00029                  size_t reserved_io_buffer_size) :
00030    m_is_datagram(is_datagram),
00031    m_handshake_cb(handshake_cb),
00032    m_data_cb(data_cb),
00033    m_alert_cb(alert_cb),
00034    m_output_fn(output_fn),
00035    m_rng(rng),
00036    m_session_manager(session_manager)
00037    {
00038    /* epoch 0 is plaintext, thus null cipher state */
00039    m_write_cipher_states[0] = nullptr;
00040    m_read_cipher_states[0] = nullptr;
00041 
00042    m_writebuf.reserve(reserved_io_buffer_size);
00043    m_readbuf.reserve(reserved_io_buffer_size);
00044    }
00045 
00046 void Channel::reset_state()
00047    {
00048    m_active_state.reset();
00049    m_pending_state.reset();
00050    m_readbuf.clear();
00051    m_write_cipher_states.clear();
00052    m_read_cipher_states.clear();
00053    }
00054 
00055 Channel::~Channel()
00056    {
00057    // So unique_ptr destructors run correctly
00058    }
00059 
00060 Connection_Sequence_Numbers& Channel::sequence_numbers() const
00061    {
00062    BOTAN_ASSERT(m_sequence_numbers, "Have a sequence numbers object");
00063    return *m_sequence_numbers;
00064    }
00065 
00066 std::shared_ptr<Connection_Cipher_State> Channel::read_cipher_state_epoch(u16bit epoch) const
00067    {
00068    auto i = m_read_cipher_states.find(epoch);
00069 
00070    BOTAN_ASSERT(i != m_read_cipher_states.end(),
00071                 "Have a cipher state for the specified epoch");
00072 
00073    return i->second;
00074    }
00075 
00076 std::shared_ptr<Connection_Cipher_State> Channel::write_cipher_state_epoch(u16bit epoch) const
00077    {
00078    auto i = m_write_cipher_states.find(epoch);
00079 
00080    BOTAN_ASSERT(i != m_write_cipher_states.end(),
00081                 "Have a cipher state for the specified epoch");
00082 
00083    return i->second;
00084    }
00085 
00086 std::vector<X509_Certificate> Channel::peer_cert_chain() const
00087    {
00088    if(auto active = active_state())
00089       return get_peer_cert_chain(*active);
00090    return std::vector<X509_Certificate>();
00091    }
00092 
00093 Handshake_State& Channel::create_handshake_state(Protocol_Version version)
00094    {
00095    if(pending_state())
00096       throw Internal_Error("create_handshake_state called during handshake");
00097 
00098    if(auto active = active_state())
00099       {
00100       Protocol_Version active_version = active->version();
00101 
00102       if(active_version.is_datagram_protocol() != version.is_datagram_protocol())
00103          throw std::runtime_error("Active state using version " +
00104                                   active_version.to_string() +
00105                                   " cannot change to " +
00106                                   version.to_string() +
00107                                   " in pending");
00108       }
00109 
00110    if(!m_sequence_numbers)
00111       {
00112       if(version.is_datagram_protocol())
00113          m_sequence_numbers.reset(new Datagram_Sequence_Numbers);
00114       else
00115          m_sequence_numbers.reset(new Stream_Sequence_Numbers);
00116       }
00117 
00118    using namespace std::placeholders;
00119 
00120    std::unique_ptr<Handshake_IO> io;
00121    if(version.is_datagram_protocol())
00122       {
00123       // default MTU is IPv6 min MTU minus UDP/IP headers (TODO: make configurable)
00124       const u16bit mtu = 1280 - 40 - 8;
00125 
00126       io.reset(new Datagram_Handshake_IO(
00127                   std::bind(&Channel::send_record_under_epoch, this, _1, _2, _3),
00128                   sequence_numbers(),
00129                   mtu));
00130       }
00131    else
00132       io.reset(new Stream_Handshake_IO(
00133                   std::bind(&Channel::send_record, this, _1, _2)));
00134 
00135    m_pending_state.reset(new_handshake_state(io.release()));
00136 
00137    if(auto active = active_state())
00138       m_pending_state->set_version(active->version());
00139 
00140    return *m_pending_state.get();
00141    }
00142 
00143 bool Channel::timeout_check()
00144    {
00145    if(m_pending_state)
00146       return m_pending_state->handshake_io().timeout_check();
00147 
00148    //FIXME: scan cipher suites and remove epochs older than 2*MSL
00149    return false;
00150    }
00151 
00152 void Channel::renegotiate(bool force_full_renegotiation)
00153    {
00154    if(pending_state()) // currently in handshake?
00155       return;
00156 
00157    if(auto active = active_state())
00158       initiate_handshake(create_handshake_state(active->version()),
00159                          force_full_renegotiation);
00160    else
00161       throw std::runtime_error("Cannot renegotiate on inactive connection");
00162    }
00163 
00164 size_t Channel::maximum_fragment_size() const
00165    {
00166    // should we be caching this value?
00167 
00168    if(auto pending = pending_state())
00169       if(auto server_hello = pending->server_hello())
00170          if(size_t frag = server_hello->fragment_size())
00171             return frag;
00172 
00173    if(auto active = active_state())
00174       if(size_t frag = active->server_hello()->fragment_size())
00175          return frag;
00176 
00177    return MAX_PLAINTEXT_SIZE;
00178    }
00179 
00180 void Channel::change_cipher_spec_reader(Connection_Side side)
00181    {
00182    auto pending = pending_state();
00183 
00184    BOTAN_ASSERT(pending && pending->server_hello(),
00185                 "Have received server hello");
00186 
00187    if(pending->server_hello()->compression_method() != NO_COMPRESSION)
00188       throw Internal_Error("Negotiated unknown compression algorithm");
00189 
00190    sequence_numbers().new_read_cipher_state();
00191 
00192    const u16bit epoch = sequence_numbers().current_read_epoch();
00193 
00194    BOTAN_ASSERT(m_read_cipher_states.count(epoch) == 0,
00195                 "No read cipher state currently set for next epoch");
00196 
00197    // flip side as we are reading
00198    std::shared_ptr<Connection_Cipher_State> read_state(
00199       new Connection_Cipher_State(pending->version(),
00200                                   (side == CLIENT) ? SERVER : CLIENT,
00201                                   false,
00202                                   pending->ciphersuite(),
00203                                   pending->session_keys()));
00204 
00205    m_read_cipher_states[epoch] = read_state;
00206    }
00207 
00208 void Channel::change_cipher_spec_writer(Connection_Side side)
00209    {
00210    auto pending = pending_state();
00211 
00212    BOTAN_ASSERT(pending && pending->server_hello(),
00213                 "Have received server hello");
00214 
00215    if(pending->server_hello()->compression_method() != NO_COMPRESSION)
00216       throw Internal_Error("Negotiated unknown compression algorithm");
00217 
00218    sequence_numbers().new_write_cipher_state();
00219 
00220    const u16bit epoch = sequence_numbers().current_write_epoch();
00221 
00222    BOTAN_ASSERT(m_write_cipher_states.count(epoch) == 0,
00223                 "No write cipher state currently set for next epoch");
00224 
00225    std::shared_ptr<Connection_Cipher_State> write_state(
00226       new Connection_Cipher_State(pending->version(),
00227                                   side,
00228                                   true,
00229                                   pending->ciphersuite(),
00230                                   pending->session_keys()));
00231 
00232    m_write_cipher_states[epoch] = write_state;
00233    }
00234 
00235 bool Channel::is_active() const
00236    {
00237    return (active_state() != nullptr);
00238    }
00239 
00240 bool Channel::is_closed() const
00241    {
00242    if(active_state() || pending_state())
00243       return false;
00244 
00245    /*
00246    * If no active or pending state, then either we had a connection
00247    * and it has been closed, or we are a server which has never
00248    * received a connection. This case is detectable by also lacking
00249    * m_sequence_numbers
00250    */
00251    return (m_sequence_numbers != nullptr);
00252    }
00253 
00254 void Channel::activate_session()
00255    {
00256    std::swap(m_active_state, m_pending_state);
00257    m_pending_state.reset();
00258 
00259    if(!m_active_state->version().is_datagram_protocol())
00260       {
00261       // TLS is easy just remove all but the current state
00262       auto current_epoch = sequence_numbers().current_write_epoch();
00263 
00264       const auto not_current_epoch =
00265          [current_epoch](u16bit epoch) { return (epoch != current_epoch); };
00266 
00267       map_remove_if(not_current_epoch, m_write_cipher_states);
00268       map_remove_if(not_current_epoch, m_read_cipher_states);
00269       }
00270    }
00271 
00272 bool Channel::peer_supports_heartbeats() const
00273    {
00274    if(auto active = active_state())
00275       return active->server_hello()->supports_heartbeats();
00276    return false;
00277    }
00278 
00279 bool Channel::heartbeat_sending_allowed() const
00280    {
00281    if(auto active = active_state())
00282       return active->server_hello()->peer_can_send_heartbeats();
00283    return false;
00284    }
00285 
00286 size_t Channel::received_data(const std::vector<byte>& buf)
00287    {
00288    return this->received_data(&buf[0], buf.size());
00289    }
00290 
00291 size_t Channel::received_data(const byte input[], size_t input_size)
00292    {
00293    const size_t max_fragment_size = maximum_fragment_size();
00294 
00295    try
00296       {
00297       while(!is_closed() && input_size)
00298          {
00299          secure_vector<byte> record;
00300          u64bit record_sequence = 0;
00301          Record_Type record_type = NO_RECORD;
00302          Protocol_Version record_version;
00303 
00304          size_t consumed = 0;
00305 
00306          const size_t needed =
00307             read_record(m_readbuf,
00308                         input,
00309                         input_size,
00310                         m_is_datagram,
00311                         consumed,
00312                         record,
00313                         &record_sequence,
00314                         &record_version,
00315                         &record_type,
00316                         m_sequence_numbers.get(),
00317                         std::bind(&TLS::Channel::read_cipher_state_epoch, this,
00318                                   std::placeholders::_1));
00319 
00320          BOTAN_ASSERT(consumed > 0, "Got to eat something");
00321 
00322          BOTAN_ASSERT(consumed <= input_size,
00323                       "Record reader consumed sane amount");
00324 
00325          input += consumed;
00326          input_size -= consumed;
00327 
00328          BOTAN_ASSERT(input_size == 0 || needed == 0,
00329                       "Got a full record or consumed all input");
00330 
00331          if(input_size == 0 && needed != 0)
00332             return needed; // need more data to complete record
00333 
00334          if(record.size() > max_fragment_size)
00335             throw TLS_Exception(Alert::RECORD_OVERFLOW,
00336                                 "Plaintext record is too large");
00337 
00338          if(record_type == HANDSHAKE || record_type == CHANGE_CIPHER_SPEC)
00339             {
00340             if(!m_pending_state)
00341                {
00342                if(record_version.is_datagram_protocol())
00343                   {
00344                   if(m_sequence_numbers)
00345                      {
00346                      /*
00347                      * Might be a peer retransmit under epoch - 1 in which
00348                      * case we must retransmit last flight
00349                      */
00350                      sequence_numbers().read_accept(record_sequence);
00351 
00352                      const u16bit epoch = record_sequence >> 48;
00353 
00354                      if(epoch == sequence_numbers().current_read_epoch())
00355                         {
00356                         create_handshake_state(record_version);
00357                         }
00358                      else if(epoch == sequence_numbers().current_read_epoch() - 1)
00359                         {
00360                         BOTAN_ASSERT(m_active_state, "Have active state here");
00361                         m_active_state->handshake_io().add_record(unlock(record),
00362                                                                   record_type,
00363                                                                   record_sequence);
00364                         }
00365                      }
00366                   else if(record_sequence == 0)
00367                      {
00368                      create_handshake_state(record_version);
00369                      }
00370                   }
00371                else
00372                   {
00373                   create_handshake_state(record_version);
00374                   }
00375                }
00376 
00377             if(m_pending_state)
00378                {
00379                m_pending_state->handshake_io().add_record(unlock(record),
00380                                                           record_type,
00381                                                           record_sequence);
00382 
00383                while(auto pending = m_pending_state.get())
00384                   {
00385                   auto msg = pending->get_next_handshake_msg();
00386 
00387                   if(msg.first == HANDSHAKE_NONE) // no full handshake yet
00388                      break;
00389 
00390                   process_handshake_msg(active_state(), *pending,
00391                                         msg.first, msg.second);
00392                   }
00393                }
00394             }
00395          else if(record_type == HEARTBEAT && peer_supports_heartbeats())
00396             {
00397             if(!active_state())
00398                throw Unexpected_Message("Heartbeat sent before handshake done");
00399 
00400             Heartbeat_Message heartbeat(unlock(record));
00401 
00402             const std::vector<byte>& payload = heartbeat.payload();
00403 
00404             if(heartbeat.is_request())
00405                {
00406                if(!pending_state())
00407                   {
00408                   const std::vector<byte> padding = unlock(rng().random_vec(16));
00409                   Heartbeat_Message response(Heartbeat_Message::RESPONSE,
00410                                              &payload[0], payload.size(), padding);
00411 
00412                   send_record(HEARTBEAT, response.contents());
00413                   }
00414                }
00415             else
00416                {
00417                m_alert_cb(Alert(Alert::HEARTBEAT_PAYLOAD), &payload[0], payload.size());
00418                }
00419             }
00420          else if(record_type == APPLICATION_DATA)
00421             {
00422             if(!active_state())
00423                throw Unexpected_Message("Application data before handshake done");
00424 
00425             /*
00426             * OpenSSL among others sends empty records in versions
00427             * before TLS v1.1 in order to randomize the IV of the
00428             * following record. Avoid spurious callbacks.
00429             */
00430             if(record.size() > 0)
00431                m_data_cb(&record[0], record.size());
00432             }
00433          else if(record_type == ALERT)
00434             {
00435             Alert alert_msg(record);
00436 
00437             if(alert_msg.type() == Alert::NO_RENEGOTIATION)
00438                m_pending_state.reset();
00439 
00440             m_alert_cb(alert_msg, nullptr, 0);
00441 
00442             if(alert_msg.is_fatal())
00443                {
00444                if(auto active = active_state())
00445                   m_session_manager.remove_entry(active->server_hello()->session_id());
00446                }
00447 
00448             if(alert_msg.type() == Alert::CLOSE_NOTIFY)
00449                send_warning_alert(Alert::CLOSE_NOTIFY); // reply in kind
00450 
00451             if(alert_msg.type() == Alert::CLOSE_NOTIFY || alert_msg.is_fatal())
00452                {
00453                reset_state();
00454                return 0;
00455                }
00456             }
00457          else if(record_type != NO_RECORD)
00458             throw Unexpected_Message("Unexpected record type " +
00459                                      std::to_string(record_type) +
00460                                      " from counterparty");
00461          }
00462 
00463       return 0; // on a record boundary
00464       }
00465    catch(TLS_Exception& e)
00466       {
00467       send_fatal_alert(e.type());
00468       throw;
00469       }
00470    catch(Integrity_Failure&)
00471       {
00472       send_fatal_alert(Alert::BAD_RECORD_MAC);
00473       throw;
00474       }
00475    catch(Decoding_Error&)
00476       {
00477       send_fatal_alert(Alert::DECODE_ERROR);
00478       throw;
00479       }
00480    catch(...)
00481       {
00482       send_fatal_alert(Alert::INTERNAL_ERROR);
00483       throw;
00484       }
00485    }
00486 
00487 void Channel::heartbeat(const byte payload[], size_t payload_size, size_t pad_size)
00488    {
00489    if(heartbeat_sending_allowed())
00490       {
00491       const std::vector<byte> padding = unlock(rng().random_vec(pad_size + 16));
00492       Heartbeat_Message heartbeat(Heartbeat_Message::REQUEST,
00493                                   payload, payload_size, padding);
00494 
00495       send_record(HEARTBEAT, heartbeat.contents());
00496       }
00497    }
00498 
00499 void Channel::write_record(Connection_Cipher_State* cipher_state, u16bit epoch,
00500                            byte record_type, const byte input[], size_t length)
00501    {
00502    BOTAN_ASSERT(m_pending_state || m_active_state, "Some connection state exists");
00503 
00504    Protocol_Version record_version =
00505       (m_pending_state) ? (m_pending_state->version()) : (m_active_state->version());
00506 
00507    TLS::write_record(m_writebuf,
00508                      record_type,
00509                      input,
00510                      length,
00511                      record_version,
00512                      sequence_numbers().next_write_sequence(epoch),
00513                      cipher_state,
00514                      m_rng);
00515 
00516    m_output_fn(&m_writebuf[0], m_writebuf.size());
00517    }
00518 
00519 void Channel::send_record_array(u16bit epoch, byte type, const byte input[], size_t length)
00520    {
00521    if(length == 0)
00522       return;
00523 
00524    /*
00525    * If using CBC mode without an explicit IV (SSL v3 or TLS v1.0),
00526    * send a single byte of plaintext to randomize the (implicit) IV of
00527    * the following main block. If using a stream cipher, or TLS v1.1
00528    * or higher, this isn't necessary.
00529    *
00530    * An empty record also works but apparently some implementations do
00531    * not like this (https://bugzilla.mozilla.org/show_bug.cgi?id=665814)
00532    *
00533    * See http://www.openssl.org/~bodo/tls-cbc.txt for background.
00534    */
00535 
00536    auto cipher_state = write_cipher_state_epoch(epoch);
00537 
00538    if(type == APPLICATION_DATA && cipher_state->cbc_without_explicit_iv())
00539       {
00540       write_record(cipher_state.get(), epoch, type, &input[0], 1);
00541       input += 1;
00542       length -= 1;
00543       }
00544 
00545    const size_t max_fragment_size = maximum_fragment_size();
00546 
00547    while(length)
00548       {
00549       const size_t sending = std::min(length, max_fragment_size);
00550       write_record(cipher_state.get(), epoch, type, &input[0], sending);
00551 
00552       input += sending;
00553       length -= sending;
00554       }
00555    }
00556 
00557 void Channel::send_record(byte record_type, const std::vector<byte>& record)
00558    {
00559    send_record_array(sequence_numbers().current_write_epoch(),
00560                      record_type, &record[0], record.size());
00561    }
00562 
00563 void Channel::send_record_under_epoch(u16bit epoch, byte record_type,
00564                                       const std::vector<byte>& record)
00565    {
00566    send_record_array(epoch, record_type, &record[0], record.size());
00567    }
00568 
00569 void Channel::send(const byte buf[], size_t buf_size)
00570    {
00571    if(!is_active())
00572       throw std::runtime_error("Data cannot be sent on inactive TLS connection");
00573 
00574    send_record_array(sequence_numbers().current_write_epoch(),
00575                      APPLICATION_DATA, buf, buf_size);
00576    }
00577 
00578 void Channel::send(const std::string& string)
00579    {
00580    this->send(reinterpret_cast<const byte*>(string.c_str()), string.size());
00581    }
00582 
00583 void Channel::send_alert(const Alert& alert)
00584    {
00585    if(alert.is_valid() && !is_closed())
00586       {
00587       try
00588          {
00589          send_record(ALERT, alert.serialize());
00590          }
00591       catch(...) { /* swallow it */ }
00592       }
00593 
00594    if(alert.type() == Alert::NO_RENEGOTIATION)
00595       m_pending_state.reset();
00596 
00597    if(alert.is_fatal())
00598       if(auto active = active_state())
00599          m_session_manager.remove_entry(active->server_hello()->session_id());
00600 
00601    if(alert.type() == Alert::CLOSE_NOTIFY || alert.is_fatal())
00602       reset_state();
00603    }
00604 
00605 void Channel::secure_renegotiation_check(const Client_Hello* client_hello)
00606    {
00607    const bool secure_renegotiation = client_hello->secure_renegotiation();
00608 
00609    if(auto active = active_state())
00610       {
00611       const bool active_sr = active->client_hello()->secure_renegotiation();
00612 
00613       if(active_sr != secure_renegotiation)
00614          throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
00615                              "Client changed its mind about secure renegotiation");
00616       }
00617 
00618    if(secure_renegotiation)
00619       {
00620       const std::vector<byte>& data = client_hello->renegotiation_info();
00621 
00622       if(data != secure_renegotiation_data_for_client_hello())
00623          throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
00624                              "Client sent bad values for secure renegotiation");
00625       }
00626    }
00627 
00628 void Channel::secure_renegotiation_check(const Server_Hello* server_hello)
00629    {
00630    const bool secure_renegotiation = server_hello->secure_renegotiation();
00631 
00632    if(auto active = active_state())
00633       {
00634       const bool active_sr = active->client_hello()->secure_renegotiation();
00635 
00636       if(active_sr != secure_renegotiation)
00637          throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
00638                              "Server changed its mind about secure renegotiation");
00639       }
00640 
00641    if(secure_renegotiation)
00642       {
00643       const std::vector<byte>& data = server_hello->renegotiation_info();
00644 
00645       if(data != secure_renegotiation_data_for_server_hello())
00646          throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
00647                              "Server sent bad values for secure renegotiation");
00648       }
00649    }
00650 
00651 std::vector<byte> Channel::secure_renegotiation_data_for_client_hello() const
00652    {
00653    if(auto active = active_state())
00654       return active->client_finished()->verify_data();
00655    return std::vector<byte>();
00656    }
00657 
00658 std::vector<byte> Channel::secure_renegotiation_data_for_server_hello() const
00659    {
00660    if(auto active = active_state())
00661       {
00662       std::vector<byte> buf = active->client_finished()->verify_data();
00663       buf += active->server_finished()->verify_data();
00664       return buf;
00665       }
00666 
00667    return std::vector<byte>();
00668    }
00669 
00670 bool Channel::secure_renegotiation_supported() const
00671    {
00672    if(auto active = active_state())
00673       return active->server_hello()->secure_renegotiation();
00674 
00675    if(auto pending = pending_state())
00676       if(auto hello = pending->server_hello())
00677          return hello->secure_renegotiation();
00678 
00679    return false;
00680    }
00681 
00682 SymmetricKey Channel::key_material_export(const std::string& label,
00683                                           const std::string& context,
00684                                           size_t length) const
00685    {
00686    if(auto active = active_state())
00687       {
00688       std::unique_ptr<KDF> prf(active->protocol_specific_prf());
00689 
00690       const secure_vector<byte>& master_secret =
00691          active->session_keys().master_secret();
00692 
00693       std::vector<byte> salt;
00694       salt += to_byte_vector(label);
00695       salt += active->client_hello()->random();
00696       salt += active->server_hello()->random();
00697 
00698       if(context != "")
00699          {
00700          size_t context_size = context.length();
00701          if(context_size > 0xFFFF)
00702             throw std::runtime_error("key_material_export context is too long");
00703          salt.push_back(get_byte<u16bit>(0, context_size));
00704          salt.push_back(get_byte<u16bit>(1, context_size));
00705          salt += to_byte_vector(context);
00706          }
00707 
00708       return prf->derive_key(length, master_secret, salt);
00709       }
00710    else
00711       throw std::runtime_error("Channel::key_material_export connection not active");
00712    }
00713 
00714 }
00715 
00716 }
00717