Botan  2.12.1
Crypto and TLS for C++11
tls_server.cpp
Go to the documentation of this file.
1 /*
2 * TLS Server
3 * (C) 2004-2011,2012,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_server.h>
10 #include <botan/tls_messages.h>
11 #include <botan/internal/tls_handshake_state.h>
12 #include <botan/internal/stl_util.h>
13 #include <botan/tls_magic.h>
14 
15 namespace Botan {
16 
17 namespace TLS {
18 
19 class Server_Handshake_State final : public Handshake_State
20  {
21  public:
22  Server_Handshake_State(Handshake_IO* io, Callbacks& cb)
23  : Handshake_State(io, cb) {}
24 
25  Private_Key* server_rsa_kex_key() { return m_server_rsa_kex_key; }
26  void set_server_rsa_kex_key(Private_Key* key)
27  { m_server_rsa_kex_key = key; }
28 
29  bool allow_session_resumption() const
30  { return m_allow_session_resumption; }
31  void set_allow_session_resumption(bool allow_session_resumption)
32  { m_allow_session_resumption = allow_session_resumption; }
33 
34  const std::vector<X509_Certificate>& resume_peer_certs() const
35  { return m_resume_peer_certs; }
36 
37  void set_resume_certs(const std::vector<X509_Certificate>& certs)
38  { m_resume_peer_certs = certs; }
39 
40  void mark_as_resumption() { m_is_a_resumption = true; }
41 
42  bool is_a_resumption() const { return m_is_a_resumption; }
43 
44  private:
45  // Used by the server only, in case of RSA key exchange. Not owned
46  Private_Key* m_server_rsa_kex_key = nullptr;
47 
48  /*
49  * Used by the server to know if resumption should be allowed on
50  * a server-initiated renegotiation
51  */
52  bool m_allow_session_resumption = true;
53 
54  bool m_is_a_resumption = false;
55 
56  std::vector<X509_Certificate> m_resume_peer_certs;
57  };
58 
59 namespace {
60 
61 bool check_for_resume(Session& session_info,
62  Session_Manager& session_manager,
63  Credentials_Manager& credentials,
64  const Client_Hello* client_hello,
65  std::chrono::seconds session_ticket_lifetime)
66  {
67  const std::vector<uint8_t>& client_session_id = client_hello->session_id();
68  const std::vector<uint8_t>& session_ticket = client_hello->session_ticket();
69 
70  if(session_ticket.empty())
71  {
72  if(client_session_id.empty()) // not resuming
73  return false;
74 
75  // not found
76  if(!session_manager.load_from_session_id(client_session_id, session_info))
77  return false;
78  }
79  else
80  {
81  // If a session ticket was sent, ignore client session ID
82  try
83  {
84  session_info = Session::decrypt(
85  session_ticket,
86  credentials.psk("tls-server", "session-ticket", ""));
87 
88  if(session_ticket_lifetime != std::chrono::seconds(0) &&
89  session_info.session_age() > session_ticket_lifetime)
90  return false; // ticket has expired
91  }
92  catch(...)
93  {
94  return false;
95  }
96  }
97 
98  // wrong version
99  if(client_hello->version() != session_info.version())
100  return false;
101 
102  // client didn't send original ciphersuite
103  if(!value_exists(client_hello->ciphersuites(),
104  session_info.ciphersuite_code()))
105  return false;
106 
107 #if defined(BOTAN_HAS_SRP6)
108  // client sent a different SRP identity
109  if(client_hello->srp_identifier() != "")
110  {
111  if(client_hello->srp_identifier() != session_info.srp_identifier())
112  return false;
113  }
114 #endif
115 
116  // client sent a different SNI hostname
117  if(client_hello->sni_hostname() != "")
118  {
119  if(client_hello->sni_hostname() != session_info.server_info().hostname())
120  return false;
121  }
122 
123  // Checking extended_master_secret on resume (RFC 7627 section 5.3)
124  if(client_hello->supports_extended_master_secret() != session_info.supports_extended_master_secret())
125  {
126  if(!session_info.supports_extended_master_secret())
127  {
128  return false; // force new handshake with extended master secret
129  }
130  else
131  {
132  /*
133  Client previously negotiated session with extended master secret,
134  but has now attempted to resume without the extension: abort
135  */
136  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
137  "Client resumed extended ms session without sending extension");
138  }
139  }
140 
141  // Checking encrypt_then_mac on resume (RFC 7366 section 3.1)
142  if(!client_hello->supports_encrypt_then_mac() && session_info.supports_encrypt_then_mac())
143  {
144  /*
145  Client previously negotiated session with Encrypt-then-MAC,
146  but has now attempted to resume without the extension: abort
147  */
148  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
149  "Client resumed Encrypt-then-MAC session without sending extension");
150  }
151 
152  return true;
153  }
154 
155 /*
156 * Choose which ciphersuite to use
157 */
158 uint16_t choose_ciphersuite(
159  const Policy& policy,
160  Protocol_Version version,
161  Credentials_Manager& creds,
162  const std::map<std::string, std::vector<X509_Certificate>>& cert_chains,
163  const Client_Hello& client_hello)
164  {
165  const bool our_choice = policy.server_uses_own_ciphersuite_preferences();
166  const bool have_srp = creds.attempt_srp("tls-server", client_hello.sni_hostname());
167  const std::vector<uint16_t> client_suites = client_hello.ciphersuites();
168  const std::vector<uint16_t> server_suites = policy.ciphersuite_list(version, have_srp);
169 
170  if(server_suites.empty())
171  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
172  "Policy forbids us from negotiating any ciphersuite");
173 
174  const bool have_shared_ecc_curve =
175  (policy.choose_key_exchange_group(client_hello.supported_ecc_curves()) != Group_Params::NONE);
176 
177  /*
178  Walk down one list in preference order
179  */
180  std::vector<uint16_t> pref_list = server_suites;
181  std::vector<uint16_t> other_list = client_suites;
182 
183  if(!our_choice)
184  std::swap(pref_list, other_list);
185 
186  for(auto suite_id : pref_list)
187  {
188  if(!value_exists(other_list, suite_id))
189  continue;
190 
191  const Ciphersuite suite = Ciphersuite::by_id(suite_id);
192 
193  if(suite.valid() == false)
194  {
195  continue;
196  }
197 
198  if(have_shared_ecc_curve == false && suite.ecc_ciphersuite())
199  {
200  continue;
201  }
202 
203  // For non-anon ciphersuites
204  if(suite.signature_used())
205  {
206  const std::string sig_algo = suite.sig_algo();
207 
208  // Do we have any certificates for this sig?
209  if(cert_chains.count(sig_algo) == 0)
210  {
211  continue;
212  }
213 
214  if(version.supports_negotiable_signature_algorithms())
215  {
216  const std::vector<Signature_Scheme> allowed =
217  policy.allowed_signature_schemes();
218 
219  std::vector<Signature_Scheme> client_sig_methods =
220  client_hello.signature_schemes();
221 
222  if(client_sig_methods.empty())
223  {
224  // If empty, then implicit SHA-1 (TLS v1.2 rules)
225  client_sig_methods.push_back(Signature_Scheme::RSA_PKCS1_SHA1);
226  client_sig_methods.push_back(Signature_Scheme::ECDSA_SHA1);
227  client_sig_methods.push_back(Signature_Scheme::DSA_SHA1);
228  }
229 
230  bool we_support_some_hash_by_client = false;
231 
232  for(Signature_Scheme scheme : client_sig_methods)
233  {
234  if(signature_scheme_is_known(scheme) == false)
235  continue;
236 
237  if(signature_algorithm_of_scheme(scheme) == suite.sig_algo() &&
238  policy.allowed_signature_hash(hash_function_of_scheme(scheme)))
239  {
240  we_support_some_hash_by_client = true;
241  }
242  }
243 
244  if(we_support_some_hash_by_client == false)
245  {
246  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
247  "Policy does not accept any hash function supported by client");
248  }
249  }
250  }
251 
252 #if defined(BOTAN_HAS_SRP6)
253  /*
254  The client may offer SRP cipher suites in the hello message but
255  omit the SRP extension. If the server would like to select an
256  SRP cipher suite in this case, the server SHOULD return a fatal
257  "unknown_psk_identity" alert immediately after processing the
258  client hello message.
259  - RFC 5054 section 2.5.1.2
260  */
261  if(suite.kex_method() == Kex_Algo::SRP_SHA && client_hello.srp_identifier() == "")
262  throw TLS_Exception(Alert::UNKNOWN_PSK_IDENTITY,
263  "Client wanted SRP but did not send username");
264 #endif
265 
266  return suite_id;
267  }
268 
269  throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
270  "Can't agree on a ciphersuite with client");
271  }
272 
273 std::map<std::string, std::vector<X509_Certificate>>
274 get_server_certs(const std::string& hostname,
275  Credentials_Manager& creds)
276  {
277  const char* cert_types[] = { "RSA", "ECDSA", "DSA", nullptr };
278 
279  std::map<std::string, std::vector<X509_Certificate>> cert_chains;
280 
281  for(size_t i = 0; cert_types[i]; ++i)
282  {
283  const std::vector<X509_Certificate> certs =
284  creds.cert_chain_single_type(cert_types[i], "tls-server", hostname);
285 
286  if(!certs.empty())
287  cert_chains[cert_types[i]] = certs;
288  }
289 
290  return cert_chains;
291  }
292 
293 }
294 
295 /*
296 * TLS Server Constructor
297 */
299  Session_Manager& session_manager,
300  Credentials_Manager& creds,
301  const Policy& policy,
303  bool is_datagram,
304  size_t io_buf_sz) :
305  Channel(callbacks, session_manager, rng, policy,
306  true, is_datagram, io_buf_sz),
307  m_creds(creds)
308  {
309  }
310 
312  data_cb got_data_cb,
313  alert_cb recv_alert_cb,
314  handshake_cb hs_cb,
315  Session_Manager& session_manager,
316  Credentials_Manager& creds,
317  const Policy& policy,
319  next_protocol_fn next_proto,
320  bool is_datagram,
321  size_t io_buf_sz) :
322  Channel(output, got_data_cb, recv_alert_cb, hs_cb,
323  Channel::handshake_msg_cb(), session_manager,
324  rng, policy, true, is_datagram, io_buf_sz),
325  m_creds(creds),
326  m_choose_next_protocol(next_proto)
327  {
328  }
329 
331  data_cb got_data_cb,
332  alert_cb recv_alert_cb,
333  handshake_cb hs_cb,
334  handshake_msg_cb hs_msg_cb,
335  Session_Manager& session_manager,
336  Credentials_Manager& creds,
337  const Policy& policy,
339  next_protocol_fn next_proto,
340  bool is_datagram) :
341  Channel(output, got_data_cb, recv_alert_cb, hs_cb, hs_msg_cb,
342  session_manager, rng, policy, true, is_datagram),
343  m_creds(creds),
344  m_choose_next_protocol(next_proto)
345  {
346  }
347 
348 Handshake_State* Server::new_handshake_state(Handshake_IO* io)
349  {
350  std::unique_ptr<Handshake_State> state(new Server_Handshake_State(io, callbacks()));
351 
352  state->set_expected_next(CLIENT_HELLO);
353  return state.release();
354  }
355 
356 std::vector<X509_Certificate>
357 Server::get_peer_cert_chain(const Handshake_State& state_base) const
358  {
359  const Server_Handshake_State& state = dynamic_cast<const Server_Handshake_State&>(state_base);
360  if(state.resume_peer_certs().size() > 0)
361  return state.resume_peer_certs();
362 
363  if(state.client_certs())
364  return state.client_certs()->cert_chain();
365  return std::vector<X509_Certificate>();
366  }
367 
368 /*
369 * Send a hello request to the client
370 */
371 void Server::initiate_handshake(Handshake_State& state,
372  bool force_full_renegotiation)
373  {
374  dynamic_cast<Server_Handshake_State&>(state).
375  set_allow_session_resumption(!force_full_renegotiation);
376 
377  Hello_Request hello_req(state.handshake_io());
378  }
379 
380 namespace {
381 
382 Protocol_Version select_version(const Botan::TLS::Policy& policy,
383  Protocol_Version client_offer,
384  Protocol_Version active_version,
385  bool is_fallback,
386  const std::vector<Protocol_Version>& supported_versions)
387  {
388  const bool is_datagram = client_offer.is_datagram_protocol();
389  const bool initial_handshake = (active_version.valid() == false);
390 
391  const Protocol_Version latest_supported = policy.latest_supported_version(is_datagram);
392 
393  if(is_fallback)
394  {
395  if(latest_supported > client_offer)
396  throw TLS_Exception(Alert::INAPPROPRIATE_FALLBACK,
397  "Client signalled fallback SCSV, possible attack");
398  }
399 
400  if(supported_versions.size() > 0)
401  {
402  if(is_datagram)
403  {
404  if(policy.allow_dtls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V12)))
406  if(policy.allow_dtls10() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V10)))
408  throw TLS_Exception(Alert::PROTOCOL_VERSION, "No shared DTLS version");
409  }
410  else
411  {
412  if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V12)))
414  if(policy.allow_tls11() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V11)))
416  if(policy.allow_tls10() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V10)))
418  throw TLS_Exception(Alert::PROTOCOL_VERSION, "No shared TLS version");
419  }
420  }
421 
422  const bool client_offer_acceptable =
423  client_offer.known_version() && policy.acceptable_protocol_version(client_offer);
424 
425  if(!initial_handshake)
426  {
427  /*
428  * If this is a renegotiation, and the client has offered a
429  * later version than what it initially negotiated, negotiate
430  * the old version. This matches OpenSSL's behavior. If the
431  * client is offering a version earlier than what it initially
432  * negotiated, reject as a probable attack.
433  */
434  if(active_version > client_offer)
435  {
436  throw TLS_Exception(Alert::PROTOCOL_VERSION,
437  "Client negotiated " +
438  active_version.to_string() +
439  " then renegotiated with " +
440  client_offer.to_string());
441  }
442  else
443  {
444  return active_version;
445  }
446  }
447  else if(client_offer_acceptable)
448  {
449  return client_offer;
450  }
451  else if(!client_offer.known_version() || client_offer > latest_supported)
452  {
453  /*
454  The client offered some version newer than the latest we
455  support. Offer them the best we know.
456  */
457  return latest_supported;
458  }
459  else
460  {
461  throw TLS_Exception(Alert::PROTOCOL_VERSION,
462  "Client version " + client_offer.to_string() +
463  " is unacceptable by policy");
464  }
465  }
466 
467 }
468 
469 /*
470 * Process a CLIENT HELLO Message
471 */
472 void Server::process_client_hello_msg(const Handshake_State* active_state,
473  Server_Handshake_State& pending_state,
474  const std::vector<uint8_t>& contents,
475  bool epoch0_restart)
476  {
477  BOTAN_ASSERT_IMPLICATION(epoch0_restart, active_state != nullptr, "Can't restart with a dead connection");
478 
479  const bool initial_handshake = epoch0_restart || !active_state;
480 
481  if(initial_handshake == false && policy().allow_client_initiated_renegotiation() == false)
482  {
483  if(policy().abort_connection_on_undesired_renegotiation())
484  throw TLS_Exception(Alert::NO_RENEGOTIATION, "Server policy prohibits renegotiation");
485  else
487  return;
488  }
489 
490  if(!policy().allow_insecure_renegotiation() &&
491  !(initial_handshake || secure_renegotiation_supported()))
492  {
494  return;
495  }
496 
497  pending_state.client_hello(new Client_Hello(contents));
498  const Protocol_Version client_offer = pending_state.client_hello()->version();
499  const bool datagram = client_offer.is_datagram_protocol();
500 
501  if(datagram)
502  {
503  if(client_offer.major_version() == 0xFF)
504  throw TLS_Exception(Alert::PROTOCOL_VERSION, "Client offered DTLS version with major version 0xFF");
505  }
506  else
507  {
508  if(client_offer.major_version() < 3)
509  throw TLS_Exception(Alert::PROTOCOL_VERSION, "Client offered TLS version with major version under 3");
510  if(client_offer.major_version() == 3 && client_offer.minor_version() == 0)
511  throw TLS_Exception(Alert::PROTOCOL_VERSION, "SSLv3 is not supported");
512  }
513 
514  /*
515  * BoGo test suite expects that we will send the hello verify with a record
516  * version matching the version that is eventually negotiated. This is wrong
517  * but harmless, so go with it. Also doing the version negotiation step first
518  * allows to immediately close the connection with an alert if the client has
519  * offered a version that we are not going to negotiate anyway, instead of
520  * making them first do the cookie exchange and then telling them no.
521  *
522  * There is no issue with amplification here, since the alert is just 2 bytes.
523  */
524  const Protocol_Version negotiated_version =
525  select_version(policy(), client_offer,
526  active_state ? active_state->version() : Protocol_Version(),
527  pending_state.client_hello()->sent_fallback_scsv(),
528  pending_state.client_hello()->supported_versions());
529 
530  pending_state.set_version(negotiated_version);
531 
532  const auto compression_methods = pending_state.client_hello()->compression_methods();
533  if(!value_exists(compression_methods, uint8_t(0)))
534  throw TLS_Exception(Alert::ILLEGAL_PARAMETER, "Client did not offer NULL compression");
535 
536  if(initial_handshake && datagram)
537  {
538  SymmetricKey cookie_secret;
539 
540  try
541  {
542  cookie_secret = m_creds.psk("tls-server", "dtls-cookie-secret", "");
543  }
544  catch(...) {}
545 
546  if(cookie_secret.size() > 0)
547  {
548  const std::string client_identity = callbacks().tls_peer_network_identity();
549  Hello_Verify_Request verify(pending_state.client_hello()->cookie_input_data(), client_identity, cookie_secret);
550 
551  if(pending_state.client_hello()->cookie() != verify.cookie())
552  {
553  if(epoch0_restart)
554  pending_state.handshake_io().send_under_epoch(verify, 0);
555  else
556  pending_state.handshake_io().send(verify);
557 
558  pending_state.client_hello(nullptr);
559  pending_state.set_expected_next(CLIENT_HELLO);
560  return;
561  }
562  }
563  else if(epoch0_restart)
564  {
565  throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Reuse of DTLS association requires DTLS cookie secret be set");
566  }
567  }
568 
569  if(epoch0_restart)
570  {
571  // If we reached here then we were able to verify the cookie
573  }
574 
575  secure_renegotiation_check(pending_state.client_hello());
576 
577  callbacks().tls_examine_extensions(pending_state.client_hello()->extensions(), CLIENT);
578 
579  Session session_info;
580  const bool resuming =
581  pending_state.allow_session_resumption() &&
582  check_for_resume(session_info,
583  session_manager(),
584  m_creds,
585  pending_state.client_hello(),
586  std::chrono::seconds(policy().session_ticket_lifetime()));
587 
588  bool have_session_ticket_key = false;
589 
590  try
591  {
592  have_session_ticket_key =
593  m_creds.psk("tls-server", "session-ticket", "").length() > 0;
594  }
595  catch(...) {}
596 
597  m_next_protocol = "";
598  if(pending_state.client_hello()->supports_alpn())
599  {
600  m_next_protocol = callbacks().tls_server_choose_app_protocol(pending_state.client_hello()->next_protocols());
601 
602  // if the callback return was empty, fall back to the (deprecated) std::function
603  if(m_next_protocol.empty() && m_choose_next_protocol)
604  {
605  m_next_protocol = m_choose_next_protocol(pending_state.client_hello()->next_protocols());
606  }
607  }
608 
609  if(resuming)
610  {
611  this->session_resume(pending_state, have_session_ticket_key, session_info);
612  }
613  else // new session
614  {
615  this->session_create(pending_state, have_session_ticket_key);
616  }
617  }
618 
619 void Server::process_certificate_msg(Server_Handshake_State& pending_state,
620  const std::vector<uint8_t>& contents)
621  {
622  pending_state.client_certs(new Certificate(contents, policy()));
623 
624  // CERTIFICATE_REQUIRED would make more sense but BoGo expects handshake failure alert
625  if(pending_state.client_certs()->empty() && policy().require_client_certificate_authentication())
626  throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Policy requires client send a certificate, but it did not");
627 
628  pending_state.set_expected_next(CLIENT_KEX);
629  }
630 
631 void Server::process_client_key_exchange_msg(Server_Handshake_State& pending_state,
632  const std::vector<uint8_t>& contents)
633  {
634  if(pending_state.received_handshake_msg(CERTIFICATE) && !pending_state.client_certs()->empty())
635  pending_state.set_expected_next(CERTIFICATE_VERIFY);
636  else
637  pending_state.set_expected_next(HANDSHAKE_CCS);
638 
639  pending_state.client_kex(new Client_Key_Exchange(contents, pending_state,
640  pending_state.server_rsa_kex_key(),
641  m_creds, policy(), rng()));
642 
643  pending_state.compute_session_keys();
644  }
645 
646 void Server::process_change_cipher_spec_msg(Server_Handshake_State& pending_state)
647  {
648  pending_state.set_expected_next(FINISHED);
650  }
651 
652 void Server::process_certificate_verify_msg(Server_Handshake_State& pending_state,
654  const std::vector<uint8_t>& contents)
655  {
656  pending_state.client_verify(new Certificate_Verify(contents, pending_state.version()));
657 
658  const std::vector<X509_Certificate>& client_certs =
659  pending_state.client_certs()->cert_chain();
660 
661  const bool sig_valid =
662  pending_state.client_verify()->verify(client_certs[0], pending_state, policy());
663 
664  pending_state.hash().update(pending_state.handshake_io().format(contents, type));
665 
666  /*
667  * Using DECRYPT_ERROR looks weird here, but per RFC 4346 is for
668  * "A handshake cryptographic operation failed, including being
669  * unable to correctly verify a signature, ..."
670  */
671  if(!sig_valid)
672  throw TLS_Exception(Alert::DECRYPT_ERROR, "Client cert verify failed");
673 
674  try
675  {
676  const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
677  auto trusted_CAs = m_creds.trusted_certificate_authorities("tls-server", sni_hostname);
678 
679  callbacks().tls_verify_cert_chain(client_certs,
680  {}, // ocsp
681  trusted_CAs,
683  sni_hostname,
684  policy());
685  }
686  catch(std::exception& e)
687  {
688  throw TLS_Exception(Alert::BAD_CERTIFICATE, e.what());
689  }
690 
691  pending_state.set_expected_next(HANDSHAKE_CCS);
692  }
693 
694 void Server::process_finished_msg(Server_Handshake_State& pending_state,
696  const std::vector<uint8_t>& contents)
697  {
698  pending_state.set_expected_next(HANDSHAKE_NONE);
699 
700  pending_state.client_finished(new Finished(contents));
701 
702  if(!pending_state.client_finished()->verify(pending_state, CLIENT))
703  throw TLS_Exception(Alert::DECRYPT_ERROR,
704  "Finished message didn't verify");
705 
706  if(!pending_state.server_finished())
707  {
708  // already sent finished if resuming, so this is a new session
709 
710  pending_state.hash().update(pending_state.handshake_io().format(contents, type));
711 
712  Session session_info(
713  pending_state.server_hello()->session_id(),
714  pending_state.session_keys().master_secret(),
715  pending_state.server_hello()->version(),
716  pending_state.server_hello()->ciphersuite(),
717  SERVER,
718  pending_state.server_hello()->supports_extended_master_secret(),
719  pending_state.server_hello()->supports_encrypt_then_mac(),
720  get_peer_cert_chain(pending_state),
721  std::vector<uint8_t>(),
722  Server_Information(pending_state.client_hello()->sni_hostname()),
723  pending_state.srp_identifier(),
724  pending_state.server_hello()->srtp_profile());
725 
726  if(save_session(session_info))
727  {
728  if(pending_state.server_hello()->supports_session_ticket())
729  {
730  try
731  {
732  const SymmetricKey ticket_key = m_creds.psk("tls-server", "session-ticket", "");
733 
734  pending_state.new_session_ticket(
735  new New_Session_Ticket(pending_state.handshake_io(),
736  pending_state.hash(),
737  session_info.encrypt(ticket_key, rng()),
739  }
740  catch(...) {}
741  }
742  else
743  session_manager().save(session_info);
744  }
745 
746  if(!pending_state.new_session_ticket() &&
747  pending_state.server_hello()->supports_session_ticket())
748  {
749  pending_state.new_session_ticket(
750  new New_Session_Ticket(pending_state.handshake_io(), pending_state.hash()));
751  }
752 
753  pending_state.handshake_io().send(Change_Cipher_Spec());
754 
756 
757  pending_state.server_finished(new Finished(pending_state.handshake_io(), pending_state, SERVER));
758  }
759 
761  }
762 
763 /*
764 * Process a handshake message
765 */
766 void Server::process_handshake_msg(const Handshake_State* active_state,
767  Handshake_State& state_base,
769  const std::vector<uint8_t>& contents,
770  bool epoch0_restart)
771  {
772  Server_Handshake_State& state = dynamic_cast<Server_Handshake_State&>(state_base);
773  state.confirm_transition_to(type);
774 
775  /*
776  * The change cipher spec message isn't technically a handshake
777  * message so it's not included in the hash. The finished and
778  * certificate verify messages are verified based on the current
779  * state of the hash *before* this message so we delay adding them
780  * to the hash computation until we've processed them below.
781  */
783  {
784  state.hash().update(state.handshake_io().format(contents, type));
785  }
786 
787  switch(type)
788  {
789  case CLIENT_HELLO:
790  return this->process_client_hello_msg(active_state, state, contents, epoch0_restart);
791 
792  case CERTIFICATE:
793  return this->process_certificate_msg(state, contents);
794 
795  case CLIENT_KEX:
796  return this->process_client_key_exchange_msg(state, contents);
797 
798  case CERTIFICATE_VERIFY:
799  return this->process_certificate_verify_msg(state, type, contents);
800 
801  case HANDSHAKE_CCS:
802  return this->process_change_cipher_spec_msg(state);
803 
804  case FINISHED:
805  return this->process_finished_msg(state, type, contents);
806 
807  default:
808  throw Unexpected_Message("Unknown handshake message received");
809  }
810  }
811 
812 void Server::session_resume(Server_Handshake_State& pending_state,
813  bool have_session_ticket_key,
814  Session& session_info)
815  {
816  // Only offer a resuming client a new ticket if they didn't send one this time,
817  // ie, resumed via server-side resumption. TODO: also send one if expiring soon?
818 
819  const bool offer_new_session_ticket =
820  (pending_state.client_hello()->supports_session_ticket() &&
821  pending_state.client_hello()->session_ticket().empty() &&
822  have_session_ticket_key);
823 
824  pending_state.server_hello(new Server_Hello(
825  pending_state.handshake_io(),
826  pending_state.hash(),
827  policy(),
828  callbacks(),
829  rng(),
831  *pending_state.client_hello(),
832  session_info,
833  offer_new_session_ticket,
834  m_next_protocol));
835 
836  secure_renegotiation_check(pending_state.server_hello());
837 
838  pending_state.mark_as_resumption();
839  pending_state.compute_session_keys(session_info.master_secret());
840  pending_state.set_resume_certs(session_info.peer_certs());
841 
842  if(!save_session(session_info))
843  {
844  session_manager().remove_entry(session_info.session_id());
845 
846  if(pending_state.server_hello()->supports_session_ticket()) // send an empty ticket
847  {
848  pending_state.new_session_ticket(
849  new New_Session_Ticket(pending_state.handshake_io(),
850  pending_state.hash()));
851  }
852  }
853 
854  if(pending_state.server_hello()->supports_session_ticket() && !pending_state.new_session_ticket())
855  {
856  try
857  {
858  const SymmetricKey ticket_key = m_creds.psk("tls-server", "session-ticket", "");
859 
860  pending_state.new_session_ticket(
861  new New_Session_Ticket(pending_state.handshake_io(),
862  pending_state.hash(),
863  session_info.encrypt(ticket_key, rng()),
865  }
866  catch(...) {}
867 
868  if(!pending_state.new_session_ticket())
869  {
870  pending_state.new_session_ticket(
871  new New_Session_Ticket(pending_state.handshake_io(), pending_state.hash()));
872  }
873  }
874 
875  pending_state.handshake_io().send(Change_Cipher_Spec());
876 
878 
879  pending_state.server_finished(new Finished(pending_state.handshake_io(), pending_state, SERVER));
880  pending_state.set_expected_next(HANDSHAKE_CCS);
881  }
882 
883 void Server::session_create(Server_Handshake_State& pending_state,
884  bool have_session_ticket_key)
885  {
886  std::map<std::string, std::vector<X509_Certificate>> cert_chains;
887 
888  const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
889 
890  cert_chains = get_server_certs(sni_hostname, m_creds);
891 
892  if(sni_hostname != "" && cert_chains.empty())
893  {
894  cert_chains = get_server_certs("", m_creds);
895 
896  /*
897  * Only send the unrecognized_name alert if we couldn't
898  * find any certs for the requested name but did find at
899  * least one cert to use in general. That avoids sending an
900  * unrecognized_name when a server is configured for purely
901  * anonymous/PSK operation.
902  */
903  if(!cert_chains.empty())
905  }
906 
907  const uint16_t ciphersuite = choose_ciphersuite(policy(), pending_state.version(),
908  m_creds, cert_chains,
909  *pending_state.client_hello());
910 
911  Server_Hello::Settings srv_settings(
912  make_hello_random(rng(), policy()), // new session ID
913  pending_state.version(),
914  ciphersuite,
915  have_session_ticket_key);
916 
917  pending_state.server_hello(new Server_Hello(
918  pending_state.handshake_io(),
919  pending_state.hash(),
920  policy(),
921  callbacks(),
922  rng(),
924  *pending_state.client_hello(),
925  srv_settings,
926  m_next_protocol));
927 
928  secure_renegotiation_check(pending_state.server_hello());
929 
930  const Ciphersuite& pending_suite = pending_state.ciphersuite();
931 
932  Private_Key* private_key = nullptr;
933 
934  if(pending_suite.signature_used() || pending_suite.kex_method() == Kex_Algo::STATIC_RSA)
935  {
936  const std::string algo_used =
937  pending_suite.signature_used() ? pending_suite.sig_algo() : "RSA";
938 
939  BOTAN_ASSERT(!cert_chains[algo_used].empty(),
940  "Attempting to send empty certificate chain");
941 
942  pending_state.server_certs(new Certificate(pending_state.handshake_io(),
943  pending_state.hash(),
944  cert_chains[algo_used]));
945 
946  if(pending_state.client_hello()->supports_cert_status_message() && pending_state.is_a_resumption() == false)
947  {
948  auto csr = pending_state.client_hello()->extensions().get<Certificate_Status_Request>();
949  // csr is non-null if client_hello()->supports_cert_status_message()
950  BOTAN_ASSERT_NOMSG(csr != nullptr);
951  const auto resp_bytes = callbacks().tls_provide_cert_status(cert_chains[algo_used], *csr);
952  if(resp_bytes.size() > 0)
953  {
954  pending_state.server_cert_status(new Certificate_Status(
955  pending_state.handshake_io(),
956  pending_state.hash(),
957  resp_bytes
958  ));
959  }
960  }
961 
962  private_key = m_creds.private_key_for(
963  pending_state.server_certs()->cert_chain()[0],
964  "tls-server",
965  sni_hostname);
966 
967  if(!private_key)
968  throw Internal_Error("No private key located for associated server cert");
969  }
970 
971  if(pending_suite.kex_method() == Kex_Algo::STATIC_RSA)
972  {
973  pending_state.set_server_rsa_kex_key(private_key);
974  }
975  else
976  {
977  pending_state.server_kex(new Server_Key_Exchange(pending_state.handshake_io(),
978  pending_state, policy(),
979  m_creds, rng(), private_key));
980  }
981 
982  auto trusted_CAs = m_creds.trusted_certificate_authorities("tls-server", sni_hostname);
983 
984  std::vector<X509_DN> client_auth_CAs;
985 
986  for(auto store : trusted_CAs)
987  {
988  auto subjects = store->all_subjects();
989  client_auth_CAs.insert(client_auth_CAs.end(), subjects.begin(), subjects.end());
990  }
991 
992  const bool request_cert =
993  (client_auth_CAs.empty() == false) ||
995 
996  if(request_cert && pending_state.ciphersuite().signature_used())
997  {
998  pending_state.cert_req(
999  new Certificate_Req(pending_state.handshake_io(),
1000  pending_state.hash(),
1001  policy(),
1002  client_auth_CAs,
1003  pending_state.version()));
1004 
1005  /*
1006  SSLv3 allowed clients to skip the Certificate message entirely
1007  if they wanted. In TLS v1.0 and later clients must send a
1008  (possibly empty) Certificate message
1009  */
1010  pending_state.set_expected_next(CERTIFICATE);
1011  }
1012  else
1013  {
1014  pending_state.set_expected_next(CLIENT_KEX);
1015  }
1016 
1017  pending_state.server_hello_done(new Server_Hello_Done(pending_state.handshake_io(), pending_state.hash()));
1018  }
1019 }
1020 
1021 }
virtual bool allow_tls11() const
Definition: tls_policy.cpp:325
static Session decrypt(const uint8_t ctext[], size_t ctext_size, const SymmetricKey &key)
virtual void remove_entry(const std::vector< uint8_t > &session_id)=0
virtual std::string tls_server_choose_app_protocol(const std::vector< std::string > &client_protos)
std::function< void(Alert, const uint8_t[], size_t)> alert_cb
Definition: tls_channel.h:42
std::string hash_function_of_scheme(Signature_Scheme scheme)
Definition: tls_algos.cpp:191
void change_cipher_spec_reader(Connection_Side side)
int(* final)(unsigned char *, CTX *)
Signature_Scheme
Definition: tls_algos.h:86
virtual bool require_client_certificate_authentication() const
Definition: tls_policy.cpp:336
void change_cipher_spec_writer(Connection_Side side)
void send_warning_alert(Alert::Type type)
Definition: tls_channel.h:143
std::function< void(const uint8_t[], size_t)> output_fn
Definition: tls_channel.h:40
bool secure_renegotiation_supported() const
#define BOTAN_ASSERT_NOMSG(expr)
Definition: assert.h:68
RandomNumberGenerator & rng()
Definition: tls_channel.h:238
Handshake_State(Handshake_IO *io, Callbacks &callbacks)
MechanismType type
#define BOTAN_ASSERT(expr, assertion_made)
Definition: assert.h:55
bool signature_scheme_is_known(Signature_Scheme scheme)
Definition: tls_algos.cpp:262
void reset_active_association_state()
Definition: tls_channel.cpp:92
std::function< bool(const Session &)> handshake_cb
Definition: tls_channel.h:43
bool save_session(const Session &session)
std::vector< uint8_t > secure_renegotiation_data_for_server_hello() const
std::function< std::string(std::vector< std::string >)> next_protocol_fn
Definition: tls_server.h:29
virtual std::string tls_peer_network_identity()
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)
virtual bool allow_dtls10() const
Definition: tls_policy.cpp:327
Definition: alg_id.cpp:13
OctetString SymmetricKey
Definition: symkey.h:141
virtual bool request_client_certificate_authentication() const
Definition: tls_policy.cpp:337
virtual void tls_examine_extensions(const Extensions &extn, Connection_Side which_side)
void secure_renegotiation_check(const Client_Hello *client_hello)
size_t length() const
Definition: symkey.h:25
std::vector< uint8_t > make_hello_random(RandomNumberGenerator &rng, const Policy &policy)
virtual SymmetricKey psk(const std::string &type, const std::string &context, const std::string &identity)
std::function< void(const uint8_t[], size_t)> data_cb
Definition: tls_channel.h:41
virtual bool allow_tls12() const
Definition: tls_policy.cpp:326
std::string signature_algorithm_of_scheme(Signature_Scheme scheme)
Definition: tls_algos.cpp:291
bool value_exists(const std::vector< T > &vec, const T &val)
Definition: stl_util.h:86
virtual bool allow_dtls12() const
Definition: tls_policy.cpp:328
static Ciphersuite by_id(uint16_t suite)
virtual std::vector< Certificate_Store * > trusted_certificate_authorities(const std::string &type, const std::string &context)
Callbacks & callbacks() const
Definition: tls_channel.h:246
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition: assert.h:94
const Policy & policy() const
Definition: tls_channel.h:242
virtual bool acceptable_protocol_version(Protocol_Version version) const
Definition: tls_policy.cpp:278
Server(Callbacks &callbacks, Session_Manager &session_manager, Credentials_Manager &creds, const Policy &policy, RandomNumberGenerator &rng, bool is_datagram=false, size_t reserved_io_buffer_size=TLS::Server::IO_BUF_DEFAULT_SIZE)
Definition: tls_server.cpp:298
virtual void save(const Session &session)=0
virtual uint32_t session_ticket_lifetime() const
Definition: tls_policy.cpp:268
virtual Protocol_Version latest_supported_version(bool datagram) const
Definition: tls_policy.cpp:293
virtual bool allow_tls10() const
Definition: tls_policy.cpp:324
Session_Manager & session_manager()
Definition: tls_channel.h:240
std::function< void(const Handshake_Message &)> handshake_msg_cb
Definition: tls_channel.h:44
virtual std::vector< uint8_t > tls_provide_cert_status(const std::vector< X509_Certificate > &chain, const Certificate_Status_Request &csr)
virtual Private_Key * private_key_for(const X509_Certificate &cert, const std::string &type, const std::string &context)