Botan  2.1.0
Crypto and TLS for C++11
tls_client.cpp
Go to the documentation of this file.
1 /*
2 * TLS Client
3 * (C) 2004-2011,2012,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_client.h>
10 #include <botan/tls_messages.h>
11 #include <botan/internal/tls_handshake_state.h>
12 #include <botan/internal/stl_util.h>
13 #include <iterator>
14 #include <sstream>
15 
16 #include <botan/hex.h>
17 
18 namespace Botan {
19 
20 namespace TLS {
21 
22 namespace {
23 
24 class Client_Handshake_State : public Handshake_State
25  {
26  public:
27  // using Handshake_State::Handshake_State;
28 
29  Client_Handshake_State(Handshake_IO* io, Callbacks& cb) : Handshake_State(io, cb) {}
30 
31  const Public_Key& get_server_public_key() const
32  {
33  BOTAN_ASSERT(server_public_key, "Server sent us a certificate");
34  return *server_public_key.get();
35  }
36 
37  // Used during session resumption
38  secure_vector<uint8_t> resume_master_secret;
39 
40  std::unique_ptr<Public_Key> server_public_key;
41  };
42 
43 }
44 
45 /*
46 * TLS Client Constructor
47 */
49  Session_Manager& session_manager,
50  Credentials_Manager& creds,
51  const Policy& policy,
53  const Server_Information& info,
54  const Protocol_Version& offer_version,
55  const std::vector<std::string>& next_protos,
56  size_t io_buf_sz) :
57  Channel(callbacks, session_manager, rng, policy, offer_version.is_datagram_protocol(),
58  io_buf_sz),
59  m_creds(creds),
60  m_info(info)
61  {
62  init(offer_version, next_protos);
63  }
64 
66  data_cb proc_cb,
69  Session_Manager& session_manager,
70  Credentials_Manager& creds,
71  const Policy& policy,
73  const Server_Information& info,
74  const Protocol_Version& offer_version,
75  const std::vector<std::string>& next_protos,
76  size_t io_buf_sz) :
77  Channel(output_fn, proc_cb, alert_cb, handshake_cb, Channel::handshake_msg_cb(),
78  session_manager, rng, policy, offer_version.is_datagram_protocol(), io_buf_sz),
79  m_creds(creds),
80  m_info(info)
81  {
82  init(offer_version, next_protos);
83  }
84 
86  data_cb proc_cb,
89  handshake_msg_cb hs_msg_cb,
90  Session_Manager& session_manager,
91  Credentials_Manager& creds,
92  const Policy& policy,
94  const Server_Information& info,
95  const Protocol_Version& offer_version,
96  const std::vector<std::string>& next_protos) :
97  Channel(output_fn, proc_cb, alert_cb, handshake_cb, hs_msg_cb,
98  session_manager, rng, policy, offer_version.is_datagram_protocol()),
99  m_creds(creds),
100  m_info(info)
101  {
102  init(offer_version, next_protos);
103  }
104 
105 void Client::init(const Protocol_Version& protocol_version,
106  const std::vector<std::string>& next_protocols)
107  {
108  const std::string srp_identifier = m_creds.srp_identifier("tls-client", m_info.hostname());
109 
110  Handshake_State& state = create_handshake_state(protocol_version);
111  send_client_hello(state, false, protocol_version,
112  srp_identifier, next_protocols);
113  }
114 
115 Handshake_State* Client::new_handshake_state(Handshake_IO* io)
116  {
117  return new Client_Handshake_State(io, callbacks());
118  }
119 
120 std::vector<X509_Certificate>
121 Client::get_peer_cert_chain(const Handshake_State& state) const
122  {
123  if(state.server_certs())
124  return state.server_certs()->cert_chain();
125  return std::vector<X509_Certificate>();
126  }
127 
128 /*
129 * Send a new client hello to renegotiate
130 */
131 void Client::initiate_handshake(Handshake_State& state,
132  bool force_full_renegotiation)
133  {
134  send_client_hello(state, force_full_renegotiation, state.version());
135  }
136 
137 void Client::send_client_hello(Handshake_State& state_base,
138  bool force_full_renegotiation,
139  Protocol_Version version,
140  const std::string& srp_identifier,
141  const std::vector<std::string>& next_protocols)
142  {
143  Client_Handshake_State& state = dynamic_cast<Client_Handshake_State&>(state_base);
144 
145  if(state.version().is_datagram_protocol())
146  state.set_expected_next(HELLO_VERIFY_REQUEST); // optional
147  state.set_expected_next(SERVER_HELLO);
148 
149  if(!force_full_renegotiation && !m_info.empty())
150  {
151  Session session_info;
152  if(session_manager().load_from_server_info(m_info, session_info))
153  {
154  /*
155  Ensure that the session protocol type matches what we want to use
156  If not skip the resume and establish a new session
157  */
158  if(version == session_info.version())
159  {
160  if(srp_identifier == "" || session_info.srp_identifier() == srp_identifier)
161  {
162  state.client_hello(
163  new Client_Hello(state.handshake_io(),
164  state.hash(),
165  policy(),
166  rng(),
168  session_info,
169  next_protocols));
170 
171  state.resume_master_secret = session_info.master_secret();
172  }
173  }
174  }
175  }
176 
177  if(!state.client_hello()) // not resuming
178  {
179  Client_Hello::Settings client_settings(version, m_info.hostname(), srp_identifier);
180  state.client_hello(new Client_Hello(
181  state.handshake_io(),
182  state.hash(),
183  policy(),
184  rng(),
186  client_settings,
187  next_protocols));
188  }
189 
190  secure_renegotiation_check(state.client_hello());
191  }
192 
193 /*
194 * Process a handshake message
195 */
196 void Client::process_handshake_msg(const Handshake_State* active_state,
197  Handshake_State& state_base,
199  const std::vector<uint8_t>& contents)
200  {
201  Client_Handshake_State& state = dynamic_cast<Client_Handshake_State&>(state_base);
202 
203  if(type == HELLO_REQUEST && active_state)
204  {
205  Hello_Request hello_request(contents);
206 
207  // Ignore request entirely if we are currently negotiating a handshake
208  if(state.client_hello())
209  return;
210 
212  {
215  else
216  this->initiate_handshake(state, false);
217  }
218  else
219  {
220  // RFC 5746 section 4.2
222  }
223 
224  return;
225  }
226 
227  state.confirm_transition_to(type);
228 
229  if(type != HANDSHAKE_CCS && type != FINISHED && type != HELLO_VERIFY_REQUEST)
230  state.hash().update(state.handshake_io().format(contents, type));
231 
232  if(type == HELLO_VERIFY_REQUEST)
233  {
234  state.set_expected_next(SERVER_HELLO);
235  state.set_expected_next(HELLO_VERIFY_REQUEST); // might get it again
236 
237  Hello_Verify_Request hello_verify_request(contents);
238 
239  state.hello_verify_request(hello_verify_request);
240  }
241  else if(type == SERVER_HELLO)
242  {
243  state.server_hello(new Server_Hello(contents));
244 
245  if(!state.client_hello()->offered_suite(state.server_hello()->ciphersuite()))
246  {
247  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
248  "Server replied with ciphersuite we didn't send");
249  }
250 
251  if(Ciphersuite::is_scsv(state.server_hello()->ciphersuite()))
252  {
253  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
254  "Server replied with a signaling ciphersuite");
255  }
256 
257  if(!value_exists(state.client_hello()->compression_methods(),
258  state.server_hello()->compression_method()))
259  {
260  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
261  "Server replied with compression method we didn't send");
262  }
263 
264  auto client_extn = state.client_hello()->extension_types();
265  auto server_extn = state.server_hello()->extension_types();
266 
267  std::vector<Handshake_Extension_Type> diff;
268 
269  std::set_difference(server_extn.begin(), server_extn.end(),
270  client_extn.begin(), client_extn.end(),
271  std::back_inserter(diff));
272 
273  if(!diff.empty())
274  {
275  // Server sent us back an extension we did not send!
276 
277  std::ostringstream msg;
278  msg << "Server replied with " << diff.size() << " unsupported extensions:";
279  for(auto&& d : diff)
280  msg << " " << static_cast<int>(d);
281  throw TLS_Exception(Alert::HANDSHAKE_FAILURE, msg.str());
282  }
283 
284  if(uint16_t srtp = state.server_hello()->srtp_profile())
285  {
286  if(!value_exists(state.client_hello()->srtp_profiles(), srtp))
287  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
288  "Server replied with DTLS-SRTP alg we did not send");
289  }
290 
291  state.set_version(state.server_hello()->version());
292  m_application_protocol = state.server_hello()->next_protocol();
293 
294  secure_renegotiation_check(state.server_hello());
295 
296  const bool server_returned_same_session_id =
297  !state.server_hello()->session_id().empty() &&
298  (state.server_hello()->session_id() == state.client_hello()->session_id());
299 
300  if(server_returned_same_session_id)
301  {
302  // successful resumption
303 
304  /*
305  * In this case, we offered the version used in the original
306  * session, and the server must resume with the same version.
307  */
308  if(state.server_hello()->version() != state.client_hello()->version())
309  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
310  "Server resumed session but with wrong version");
311 
312  state.compute_session_keys(state.resume_master_secret);
313 
314  if(state.server_hello()->supports_session_ticket())
315  state.set_expected_next(NEW_SESSION_TICKET);
316  else
317  {
318  state.set_expected_next(HANDSHAKE_CCS);
319  }
320  }
321  else
322  {
323  // new session
324 
325  if(state.client_hello()->version().is_datagram_protocol() !=
326  state.server_hello()->version().is_datagram_protocol())
327  {
328  throw TLS_Exception(Alert::PROTOCOL_VERSION,
329  "Server replied with different protocol type than we offered");
330  }
331 
332  if(state.version() > state.client_hello()->version())
333  {
334  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
335  "Server replied with later version than in hello");
336  }
337 
338  if(!policy().acceptable_protocol_version(state.version()))
339  {
340  throw TLS_Exception(Alert::PROTOCOL_VERSION,
341  "Server version " + state.version().to_string() +
342  " is unacceptable by policy");
343  }
344 
345  if(state.ciphersuite().sig_algo() != "")
346  {
347  state.set_expected_next(CERTIFICATE);
348  }
349  else if(state.ciphersuite().kex_algo() == "PSK")
350  {
351  /* PSK is anonymous so no certificate/cert req message is
352  ever sent. The server may or may not send a server kex,
353  depending on if it has an identity hint for us.
354 
355  (EC)DHE_PSK always sends a server key exchange for the
356  DH exchange portion.
357  */
358 
359  state.set_expected_next(SERVER_KEX);
360  state.set_expected_next(SERVER_HELLO_DONE);
361  }
362  else if(state.ciphersuite().kex_algo() != "RSA")
363  {
364  state.set_expected_next(SERVER_KEX);
365  }
366  else
367  {
368  state.set_expected_next(CERTIFICATE_REQUEST); // optional
369  state.set_expected_next(SERVER_HELLO_DONE);
370  }
371  }
372  }
373  else if(type == CERTIFICATE)
374  {
375  state.server_certs(new Certificate(contents, policy()));
376 
377  const std::vector<X509_Certificate>& server_certs =
378  state.server_certs()->cert_chain();
379 
380  if(server_certs.empty())
381  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
382  "Client: No certificates sent by server");
383 
384  /*
385  Certificate verification happens after we receive the server hello done,
386  in case an OCSP response was also available
387  */
388 
389  std::unique_ptr<Public_Key> peer_key(server_certs[0].subject_public_key());
390 
391  if(peer_key->algo_name() != state.ciphersuite().sig_algo())
392  throw TLS_Exception(Alert::ILLEGAL_PARAMETER,
393  "Certificate key type did not match ciphersuite");
394 
395  state.server_public_key.reset(peer_key.release());
396 
397  if(state.ciphersuite().kex_algo() != "RSA")
398  {
399  state.set_expected_next(SERVER_KEX);
400  }
401  else
402  {
403  state.set_expected_next(CERTIFICATE_REQUEST); // optional
404  state.set_expected_next(SERVER_HELLO_DONE);
405  }
406 
407  if(state.server_hello()->supports_certificate_status_message())
408  {
409  state.set_expected_next(CERTIFICATE_STATUS); // optional
410  }
411  }
412  else if(type == CERTIFICATE_STATUS)
413  {
414  state.server_cert_status(new Certificate_Status(contents));
415 
416  if(state.ciphersuite().kex_algo() != "RSA")
417  {
418  state.set_expected_next(SERVER_KEX);
419  }
420  else
421  {
422  state.set_expected_next(CERTIFICATE_REQUEST); // optional
423  state.set_expected_next(SERVER_HELLO_DONE);
424  }
425  }
426  else if(type == SERVER_KEX)
427  {
428  state.set_expected_next(CERTIFICATE_REQUEST); // optional
429  state.set_expected_next(SERVER_HELLO_DONE);
430 
431  state.server_kex(
432  new Server_Key_Exchange(contents,
433  state.ciphersuite().kex_algo(),
434  state.ciphersuite().sig_algo(),
435  state.version())
436  );
437 
438  if(state.ciphersuite().sig_algo() != "")
439  {
440  const Public_Key& server_key = state.get_server_public_key();
441 
442  if(!state.server_kex()->verify(server_key, state, policy()))
443  {
444  throw TLS_Exception(Alert::DECRYPT_ERROR,
445  "Bad signature on server key exchange");
446  }
447  }
448  }
449  else if(type == CERTIFICATE_REQUEST)
450  {
451  state.set_expected_next(SERVER_HELLO_DONE);
452  state.cert_req(new Certificate_Req(contents, state.version()));
453  }
454  else if(type == SERVER_HELLO_DONE)
455  {
456  state.server_hello_done(new Server_Hello_Done(contents));
457 
458  if(state.server_certs() != nullptr)
459  {
460  try
461  {
462  auto trusted_CAs = m_creds.trusted_certificate_authorities("tls-client", m_info.hostname());
463 
464  std::vector<std::shared_ptr<const OCSP::Response>> ocsp;
465  if(state.server_cert_status() != nullptr)
466  ocsp.push_back(state.server_cert_status()->response());
467 
468  callbacks().tls_verify_cert_chain(state.server_certs()->cert_chain(),
469  ocsp,
470  trusted_CAs,
472  m_info.hostname(),
473  policy());
474  }
475  catch(std::exception& e)
476  {
477  throw TLS_Exception(Alert::BAD_CERTIFICATE, e.what());
478  }
479  }
480 
481  if(state.received_handshake_msg(CERTIFICATE_REQUEST))
482  {
483  const auto& types = state.cert_req()->acceptable_cert_types();
484 
485  std::vector<X509_Certificate> client_certs =
486  m_creds.cert_chain(types,
487  "tls-client",
488  m_info.hostname());
489 
490  state.client_certs(new Certificate(state.handshake_io(),
491  state.hash(),
492  client_certs));
493  }
494 
495  state.client_kex(
496  new Client_Key_Exchange(state.handshake_io(),
497  state,
498  policy(),
499  m_creds,
500  state.server_public_key.get(),
501  m_info.hostname(),
502  rng())
503  );
504 
505  state.compute_session_keys();
506 
507  if(state.received_handshake_msg(CERTIFICATE_REQUEST) &&
508  !state.client_certs()->empty())
509  {
510  Private_Key* private_key =
511  m_creds.private_key_for(state.client_certs()->cert_chain()[0],
512  "tls-client",
513  m_info.hostname());
514 
515  state.client_verify(
516  new Certificate_Verify(state.handshake_io(),
517  state,
518  policy(),
519  rng(),
520  private_key)
521  );
522  }
523 
524  state.handshake_io().send(Change_Cipher_Spec());
525 
527 
528  state.client_finished(new Finished(state.handshake_io(), state, CLIENT));
529 
530  if(state.server_hello()->supports_session_ticket())
531  state.set_expected_next(NEW_SESSION_TICKET);
532  else
533  state.set_expected_next(HANDSHAKE_CCS);
534  }
535  else if(type == NEW_SESSION_TICKET)
536  {
537  state.new_session_ticket(new New_Session_Ticket(contents));
538 
539  state.set_expected_next(HANDSHAKE_CCS);
540  }
541  else if(type == HANDSHAKE_CCS)
542  {
543  state.set_expected_next(FINISHED);
544 
546  }
547  else if(type == FINISHED)
548  {
549  state.server_finished(new Finished(contents));
550 
551  if(!state.server_finished()->verify(state, SERVER))
552  throw TLS_Exception(Alert::DECRYPT_ERROR,
553  "Finished message didn't verify");
554 
555  state.hash().update(state.handshake_io().format(contents, type));
556 
557  if(!state.client_finished()) // session resume case
558  {
559  state.handshake_io().send(Change_Cipher_Spec());
561  state.client_finished(new Finished(state.handshake_io(), state, CLIENT));
562  }
563 
564  std::vector<uint8_t> session_id = state.server_hello()->session_id();
565 
566  const std::vector<uint8_t>& session_ticket = state.session_ticket();
567 
568  if(session_id.empty() && !session_ticket.empty())
569  session_id = make_hello_random(rng(), policy());
570 
571  Session session_info(
572  session_id,
573  state.session_keys().master_secret(),
574  state.server_hello()->version(),
575  state.server_hello()->ciphersuite(),
576  state.server_hello()->compression_method(),
577  CLIENT,
578  state.server_hello()->supports_extended_master_secret(),
579  state.server_hello()->supports_encrypt_then_mac(),
580  get_peer_cert_chain(state),
581  session_ticket,
582  m_info,
583  "",
584  state.server_hello()->srtp_profile()
585  );
586 
587  const bool should_save = save_session(session_info);
588 
589  if(!session_id.empty())
590  {
591  if(should_save)
592  session_manager().save(session_info);
593  else
594  session_manager().remove_entry(session_info.session_id());
595  }
596 
598  }
599  else
600  throw Unexpected_Message("Unknown handshake message received");
601  }
602 
603 }
604 
605 }
Callbacks & callbacks() const
Definition: tls_channel.h:241
virtual void remove_entry(const std::vector< uint8_t > &session_id)=0
virtual bool allow_insecure_renegotiation() const
Definition: tls_policy.cpp:270
std::vector< uint8_t > secure_renegotiation_data_for_client_hello() const
virtual std::string srp_identifier(const std::string &type, const std::string &context)
std::function< void(Alert, const uint8_t[], size_t)> alert_cb
Definition: tls_channel.h:41
void change_cipher_spec_reader(Connection_Side side)
bool save_session(const Session &session) const
Definition: tls_channel.h:239
static bool is_scsv(uint16_t suite)
void change_cipher_spec_writer(Connection_Side side)
Client(Callbacks &callbacks, Session_Manager &session_manager, Credentials_Manager &creds, const Policy &policy, RandomNumberGenerator &rng, const Server_Information &server_info=Server_Information(), const Protocol_Version &offer_version=Protocol_Version::latest_tls_version(), const std::vector< std::string > &next_protocols={}, size_t reserved_io_buffer_size=TLS::Client::IO_BUF_DEFAULT_SIZE)
Definition: tls_client.cpp:48
void send_warning_alert(Alert::Type type)
Definition: tls_channel.h:140
std::function< void(const uint8_t[], size_t)> output_fn
Definition: tls_channel.h:39
Handshake_State & create_handshake_state(Protocol_Version version)
RandomNumberGenerator & rng()
Definition: tls_channel.h:233
MechanismType type
virtual void tls_verify_cert_chain(const std::vector< X509_Certificate > &cert_chain, const std::vector< std::shared_ptr< const OCSP::Response >> &ocsp_responses, const std::vector< Certificate_Store * > &trusted_roots, Usage_Type usage, const std::string &hostname, const TLS::Policy &policy)
std::string hostname() const
#define BOTAN_ASSERT(expr, assertion_made)
Definition: assert.h:27
virtual std::vector< X509_Certificate > cert_chain(const std::vector< std::string > &cert_key_types, const std::string &type, const std::string &context)
std::function< bool(const Session &)> handshake_cb
Definition: tls_channel.h:42
virtual bool allow_server_initiated_renegotiation() const
Definition: tls_policy.cpp:269
bool secure_renegotiation_supported() const
Definition: alg_id.cpp:13
void secure_renegotiation_check(const Client_Hello *client_hello)
secure_vector< uint8_t > resume_master_secret
Definition: tls_client.cpp:38
std::vector< uint8_t > make_hello_random(RandomNumberGenerator &rng, const Policy &policy)
std::function< void(const uint8_t[], size_t)> data_cb
Definition: tls_channel.h:40
std::unique_ptr< Public_Key > server_public_key
Definition: tls_client.cpp:40
bool value_exists(const std::vector< T > &vec, const T &val)
Definition: stl_util.h:86
virtual std::vector< Certificate_Store * > trusted_certificate_authorities(const std::string &type, const std::string &context)
virtual void save(const Session &session)=0
const Policy & policy() const
Definition: tls_channel.h:237
Session_Manager & session_manager()
Definition: tls_channel.h:235
std::function< void(const Handshake_Message &)> handshake_msg_cb
Definition: tls_channel.h:43
virtual bool load_from_server_info(const Server_Information &info, Session &session)=0