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:
Server_Handshake_State(Handshake_IO * io,Callbacks & cb)22 Server_Handshake_State(Handshake_IO* io, Callbacks& cb)
23 : Handshake_State(io, cb) {}
24
server_rsa_kex_key()25 Private_Key* server_rsa_kex_key() { return m_server_rsa_kex_key; }
set_server_rsa_kex_key(Private_Key * key)26 void set_server_rsa_kex_key(Private_Key* key)
27 { m_server_rsa_kex_key = key; }
28
allow_session_resumption() const29 bool allow_session_resumption() const
30 { return m_allow_session_resumption; }
set_allow_session_resumption(bool allow_session_resumption)31 void set_allow_session_resumption(bool allow_session_resumption)
32 { m_allow_session_resumption = allow_session_resumption; }
33
resume_peer_certs() const34 const std::vector<X509_Certificate>& resume_peer_certs() const
35 { return m_resume_peer_certs; }
36
set_resume_certs(const std::vector<X509_Certificate> & certs)37 void set_resume_certs(const std::vector<X509_Certificate>& certs)
38 { m_resume_peer_certs = certs; }
39
mark_as_resumption()40 void mark_as_resumption() { m_is_a_resumption = true; }
41
is_a_resumption() const42 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
check_for_resume(Session & session_info,Session_Manager & session_manager,Credentials_Manager & credentials,const Client_Hello * client_hello,std::chrono::seconds session_ticket_lifetime)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 */
choose_ciphersuite(const Policy & policy,Protocol_Version version,Credentials_Manager & creds,const std::map<std::string,std::vector<X509_Certificate>> & cert_chains,const Client_Hello & client_hello)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>>
get_server_certs(const std::string & hostname,Credentials_Manager & creds)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 */
Server(Callbacks & callbacks,Session_Manager & session_manager,Credentials_Manager & creds,const Policy & policy,RandomNumberGenerator & rng,bool is_datagram,size_t io_buf_sz)298 Server::Server(Callbacks& callbacks,
299 Session_Manager& session_manager,
300 Credentials_Manager& creds,
301 const Policy& policy,
302 RandomNumberGenerator& rng,
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
Server(output_fn output,data_cb got_data_cb,alert_cb recv_alert_cb,handshake_cb hs_cb,Session_Manager & session_manager,Credentials_Manager & creds,const Policy & policy,RandomNumberGenerator & rng,next_protocol_fn next_proto,bool is_datagram,size_t io_buf_sz)311 Server::Server(output_fn output,
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,
318 RandomNumberGenerator& rng,
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
Server(output_fn output,data_cb got_data_cb,alert_cb recv_alert_cb,handshake_cb hs_cb,handshake_msg_cb hs_msg_cb,Session_Manager & session_manager,Credentials_Manager & creds,const Policy & policy,RandomNumberGenerator & rng,next_protocol_fn next_proto,bool is_datagram)330 Server::Server(output_fn output,
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,
338 RandomNumberGenerator& rng,
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
new_handshake_state(Handshake_IO * io)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>
get_peer_cert_chain(const Handshake_State & state_base) const357 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 */
initiate_handshake(Handshake_State & state,bool force_full_renegotiation)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
select_version(const Botan::TLS::Policy & policy,Protocol_Version client_offer,Protocol_Version active_version,bool is_fallback,const std::vector<Protocol_Version> & supported_versions)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)))
405 return Protocol_Version::DTLS_V12;
406 #if defined(BOTAN_HAS_TLS_V10)
407 if(policy.allow_dtls10() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V10)))
408 return Protocol_Version::DTLS_V10;
409 #endif
410 throw TLS_Exception(Alert::PROTOCOL_VERSION, "No shared DTLS version");
411 }
412 else
413 {
414 if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V12)))
415 return Protocol_Version::TLS_V12;
416 #if defined(BOTAN_HAS_TLS_V10)
417 if(policy.allow_tls11() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V11)))
418 return Protocol_Version::TLS_V11;
419 if(policy.allow_tls10() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V10)))
420 return Protocol_Version::TLS_V10;
421 #endif
422 throw TLS_Exception(Alert::PROTOCOL_VERSION, "No shared TLS version");
423 }
424 }
425
426 const bool client_offer_acceptable =
427 client_offer.known_version() && policy.acceptable_protocol_version(client_offer);
428
429 if(!initial_handshake)
430 {
431 /*
432 * If this is a renegotiation, and the client has offered a
433 * later version than what it initially negotiated, negotiate
434 * the old version. This matches OpenSSL's behavior. If the
435 * client is offering a version earlier than what it initially
436 * negotiated, reject as a probable attack.
437 */
438 if(active_version > client_offer)
439 {
440 throw TLS_Exception(Alert::PROTOCOL_VERSION,
441 "Client negotiated " +
442 active_version.to_string() +
443 " then renegotiated with " +
444 client_offer.to_string());
445 }
446 else
447 {
448 return active_version;
449 }
450 }
451 else if(client_offer_acceptable)
452 {
453 return client_offer;
454 }
455 else if(!client_offer.known_version() || client_offer > latest_supported)
456 {
457 /*
458 The client offered some version newer than the latest we
459 support. Offer them the best we know.
460 */
461 return latest_supported;
462 }
463 else
464 {
465 throw TLS_Exception(Alert::PROTOCOL_VERSION,
466 "Client version " + client_offer.to_string() +
467 " is unacceptable by policy");
468 }
469 }
470
471 }
472
473 /*
474 * Process a CLIENT HELLO Message
475 */
process_client_hello_msg(const Handshake_State * active_state,Server_Handshake_State & pending_state,const std::vector<uint8_t> & contents,bool epoch0_restart)476 void Server::process_client_hello_msg(const Handshake_State* active_state,
477 Server_Handshake_State& pending_state,
478 const std::vector<uint8_t>& contents,
479 bool epoch0_restart)
480 {
481 BOTAN_ASSERT_IMPLICATION(epoch0_restart, active_state != nullptr, "Can't restart with a dead connection");
482
483 const bool initial_handshake = epoch0_restart || !active_state;
484
485 if(initial_handshake == false && policy().allow_client_initiated_renegotiation() == false)
486 {
487 if(policy().abort_connection_on_undesired_renegotiation())
488 throw TLS_Exception(Alert::NO_RENEGOTIATION, "Server policy prohibits renegotiation");
489 else
490 send_warning_alert(Alert::NO_RENEGOTIATION);
491 return;
492 }
493
494 if(!policy().allow_insecure_renegotiation() &&
495 !(initial_handshake || secure_renegotiation_supported()))
496 {
497 send_warning_alert(Alert::NO_RENEGOTIATION);
498 return;
499 }
500
501 pending_state.client_hello(new Client_Hello(contents));
502 const Protocol_Version client_offer = pending_state.client_hello()->version();
503 const bool datagram = client_offer.is_datagram_protocol();
504
505 if(datagram)
506 {
507 if(client_offer.major_version() == 0xFF)
508 throw TLS_Exception(Alert::PROTOCOL_VERSION, "Client offered DTLS version with major version 0xFF");
509 }
510 else
511 {
512 if(client_offer.major_version() < 3)
513 throw TLS_Exception(Alert::PROTOCOL_VERSION, "Client offered TLS version with major version under 3");
514 if(client_offer.major_version() == 3 && client_offer.minor_version() == 0)
515 throw TLS_Exception(Alert::PROTOCOL_VERSION, "SSLv3 is not supported");
516 }
517
518 /*
519 * BoGo test suite expects that we will send the hello verify with a record
520 * version matching the version that is eventually negotiated. This is wrong
521 * but harmless, so go with it. Also doing the version negotiation step first
522 * allows to immediately close the connection with an alert if the client has
523 * offered a version that we are not going to negotiate anyway, instead of
524 * making them first do the cookie exchange and then telling them no.
525 *
526 * There is no issue with amplification here, since the alert is just 2 bytes.
527 */
528 const Protocol_Version negotiated_version =
529 select_version(policy(), client_offer,
530 active_state ? active_state->version() : Protocol_Version(),
531 pending_state.client_hello()->sent_fallback_scsv(),
532 pending_state.client_hello()->supported_versions());
533
534 pending_state.set_version(negotiated_version);
535
536 const auto compression_methods = pending_state.client_hello()->compression_methods();
537 if(!value_exists(compression_methods, uint8_t(0)))
538 throw TLS_Exception(Alert::ILLEGAL_PARAMETER, "Client did not offer NULL compression");
539
540 if(initial_handshake && datagram)
541 {
542 SymmetricKey cookie_secret;
543
544 try
545 {
546 cookie_secret = m_creds.psk("tls-server", "dtls-cookie-secret", "");
547 }
548 catch(...) {}
549
550 if(cookie_secret.size() > 0)
551 {
552 const std::string client_identity = callbacks().tls_peer_network_identity();
553 Hello_Verify_Request verify(pending_state.client_hello()->cookie_input_data(), client_identity, cookie_secret);
554
555 if(pending_state.client_hello()->cookie() != verify.cookie())
556 {
557 if(epoch0_restart)
558 pending_state.handshake_io().send_under_epoch(verify, 0);
559 else
560 pending_state.handshake_io().send(verify);
561
562 pending_state.client_hello(nullptr);
563 pending_state.set_expected_next(CLIENT_HELLO);
564 return;
565 }
566 }
567 else if(epoch0_restart)
568 {
569 throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Reuse of DTLS association requires DTLS cookie secret be set");
570 }
571 }
572
573 if(epoch0_restart)
574 {
575 // If we reached here then we were able to verify the cookie
576 reset_active_association_state();
577 }
578
579 secure_renegotiation_check(pending_state.client_hello());
580
581 callbacks().tls_examine_extensions(pending_state.client_hello()->extensions(), CLIENT);
582
583 Session session_info;
584 const bool resuming =
585 pending_state.allow_session_resumption() &&
586 check_for_resume(session_info,
587 session_manager(),
588 m_creds,
589 pending_state.client_hello(),
590 std::chrono::seconds(policy().session_ticket_lifetime()));
591
592 bool have_session_ticket_key = false;
593
594 try
595 {
596 have_session_ticket_key =
597 m_creds.psk("tls-server", "session-ticket", "").length() > 0;
598 }
599 catch(...) {}
600
601 m_next_protocol = "";
602 if(pending_state.client_hello()->supports_alpn())
603 {
604 m_next_protocol = callbacks().tls_server_choose_app_protocol(pending_state.client_hello()->next_protocols());
605
606 // if the callback return was empty, fall back to the (deprecated) std::function
607 if(m_next_protocol.empty() && m_choose_next_protocol)
608 {
609 m_next_protocol = m_choose_next_protocol(pending_state.client_hello()->next_protocols());
610 }
611 }
612
613 if(resuming)
614 {
615 this->session_resume(pending_state, have_session_ticket_key, session_info);
616 }
617 else // new session
618 {
619 this->session_create(pending_state, have_session_ticket_key);
620 }
621 }
622
process_certificate_msg(Server_Handshake_State & pending_state,const std::vector<uint8_t> & contents)623 void Server::process_certificate_msg(Server_Handshake_State& pending_state,
624 const std::vector<uint8_t>& contents)
625 {
626 pending_state.client_certs(new Certificate(contents, policy()));
627
628 // CERTIFICATE_REQUIRED would make more sense but BoGo expects handshake failure alert
629 if(pending_state.client_certs()->empty() && policy().require_client_certificate_authentication())
630 throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Policy requires client send a certificate, but it did not");
631
632 pending_state.set_expected_next(CLIENT_KEX);
633 }
634
process_client_key_exchange_msg(Server_Handshake_State & pending_state,const std::vector<uint8_t> & contents)635 void Server::process_client_key_exchange_msg(Server_Handshake_State& pending_state,
636 const std::vector<uint8_t>& contents)
637 {
638 if(pending_state.received_handshake_msg(CERTIFICATE) && !pending_state.client_certs()->empty())
639 pending_state.set_expected_next(CERTIFICATE_VERIFY);
640 else
641 pending_state.set_expected_next(HANDSHAKE_CCS);
642
643 pending_state.client_kex(new Client_Key_Exchange(contents, pending_state,
644 pending_state.server_rsa_kex_key(),
645 m_creds, policy(), rng()));
646
647 pending_state.compute_session_keys();
648 }
649
process_change_cipher_spec_msg(Server_Handshake_State & pending_state)650 void Server::process_change_cipher_spec_msg(Server_Handshake_State& pending_state)
651 {
652 pending_state.set_expected_next(FINISHED);
653 change_cipher_spec_reader(SERVER);
654 }
655
process_certificate_verify_msg(Server_Handshake_State & pending_state,Handshake_Type type,const std::vector<uint8_t> & contents)656 void Server::process_certificate_verify_msg(Server_Handshake_State& pending_state,
657 Handshake_Type type,
658 const std::vector<uint8_t>& contents)
659 {
660 pending_state.client_verify(new Certificate_Verify(contents, pending_state.version()));
661
662 const std::vector<X509_Certificate>& client_certs =
663 pending_state.client_certs()->cert_chain();
664
665 const bool sig_valid =
666 pending_state.client_verify()->verify(client_certs[0], pending_state, policy());
667
668 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
669
670 /*
671 * Using DECRYPT_ERROR looks weird here, but per RFC 4346 is for
672 * "A handshake cryptographic operation failed, including being
673 * unable to correctly verify a signature, ..."
674 */
675 if(!sig_valid)
676 throw TLS_Exception(Alert::DECRYPT_ERROR, "Client cert verify failed");
677
678 try
679 {
680 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
681 auto trusted_CAs = m_creds.trusted_certificate_authorities("tls-server", sni_hostname);
682
683 callbacks().tls_verify_cert_chain(client_certs,
684 {}, // ocsp
685 trusted_CAs,
686 Usage_Type::TLS_CLIENT_AUTH,
687 sni_hostname,
688 policy());
689 }
690 catch(std::exception& e)
691 {
692 throw TLS_Exception(Alert::BAD_CERTIFICATE, e.what());
693 }
694
695 pending_state.set_expected_next(HANDSHAKE_CCS);
696 }
697
process_finished_msg(Server_Handshake_State & pending_state,Handshake_Type type,const std::vector<uint8_t> & contents)698 void Server::process_finished_msg(Server_Handshake_State& pending_state,
699 Handshake_Type type,
700 const std::vector<uint8_t>& contents)
701 {
702 pending_state.set_expected_next(HANDSHAKE_NONE);
703
704 pending_state.client_finished(new Finished(contents));
705
706 if(!pending_state.client_finished()->verify(pending_state, CLIENT))
707 throw TLS_Exception(Alert::DECRYPT_ERROR,
708 "Finished message didn't verify");
709
710 if(!pending_state.server_finished())
711 {
712 // already sent finished if resuming, so this is a new session
713
714 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
715
716 Session session_info(
717 pending_state.server_hello()->session_id(),
718 pending_state.session_keys().master_secret(),
719 pending_state.server_hello()->version(),
720 pending_state.server_hello()->ciphersuite(),
721 SERVER,
722 pending_state.server_hello()->supports_extended_master_secret(),
723 pending_state.server_hello()->supports_encrypt_then_mac(),
724 get_peer_cert_chain(pending_state),
725 std::vector<uint8_t>(),
726 Server_Information(pending_state.client_hello()->sni_hostname()),
727 pending_state.srp_identifier(),
728 pending_state.server_hello()->srtp_profile());
729
730 if(save_session(session_info))
731 {
732 if(pending_state.server_hello()->supports_session_ticket())
733 {
734 try
735 {
736 const SymmetricKey ticket_key = m_creds.psk("tls-server", "session-ticket", "");
737
738 pending_state.new_session_ticket(
739 new New_Session_Ticket(pending_state.handshake_io(),
740 pending_state.hash(),
741 session_info.encrypt(ticket_key, rng()),
742 policy().session_ticket_lifetime()));
743 }
744 catch(...) {}
745 }
746 else
747 session_manager().save(session_info);
748 }
749
750 if(!pending_state.new_session_ticket() &&
751 pending_state.server_hello()->supports_session_ticket())
752 {
753 pending_state.new_session_ticket(
754 new New_Session_Ticket(pending_state.handshake_io(), pending_state.hash()));
755 }
756
757 pending_state.handshake_io().send(Change_Cipher_Spec());
758
759 change_cipher_spec_writer(SERVER);
760
761 pending_state.server_finished(new Finished(pending_state.handshake_io(), pending_state, SERVER));
762 }
763
764 activate_session();
765 }
766
767 /*
768 * Process a handshake message
769 */
process_handshake_msg(const Handshake_State * active_state,Handshake_State & state_base,Handshake_Type type,const std::vector<uint8_t> & contents,bool epoch0_restart)770 void Server::process_handshake_msg(const Handshake_State* active_state,
771 Handshake_State& state_base,
772 Handshake_Type type,
773 const std::vector<uint8_t>& contents,
774 bool epoch0_restart)
775 {
776 Server_Handshake_State& state = dynamic_cast<Server_Handshake_State&>(state_base);
777 state.confirm_transition_to(type);
778
779 /*
780 * The change cipher spec message isn't technically a handshake
781 * message so it's not included in the hash. The finished and
782 * certificate verify messages are verified based on the current
783 * state of the hash *before* this message so we delay adding them
784 * to the hash computation until we've processed them below.
785 */
786 if(type != HANDSHAKE_CCS && type != FINISHED && type != CERTIFICATE_VERIFY)
787 {
788 state.hash().update(state.handshake_io().format(contents, type));
789 }
790
791 switch(type)
792 {
793 case CLIENT_HELLO:
794 return this->process_client_hello_msg(active_state, state, contents, epoch0_restart);
795
796 case CERTIFICATE:
797 return this->process_certificate_msg(state, contents);
798
799 case CLIENT_KEX:
800 return this->process_client_key_exchange_msg(state, contents);
801
802 case CERTIFICATE_VERIFY:
803 return this->process_certificate_verify_msg(state, type, contents);
804
805 case HANDSHAKE_CCS:
806 return this->process_change_cipher_spec_msg(state);
807
808 case FINISHED:
809 return this->process_finished_msg(state, type, contents);
810
811 default:
812 throw Unexpected_Message("Unknown handshake message received");
813 }
814 }
815
session_resume(Server_Handshake_State & pending_state,bool have_session_ticket_key,Session & session_info)816 void Server::session_resume(Server_Handshake_State& pending_state,
817 bool have_session_ticket_key,
818 Session& session_info)
819 {
820 // Only offer a resuming client a new ticket if they didn't send one this time,
821 // ie, resumed via server-side resumption. TODO: also send one if expiring soon?
822
823 const bool offer_new_session_ticket =
824 (pending_state.client_hello()->supports_session_ticket() &&
825 pending_state.client_hello()->session_ticket().empty() &&
826 have_session_ticket_key);
827
828 pending_state.server_hello(new Server_Hello(
829 pending_state.handshake_io(),
830 pending_state.hash(),
831 policy(),
832 callbacks(),
833 rng(),
834 secure_renegotiation_data_for_server_hello(),
835 *pending_state.client_hello(),
836 session_info,
837 offer_new_session_ticket,
838 m_next_protocol));
839
840 secure_renegotiation_check(pending_state.server_hello());
841
842 pending_state.mark_as_resumption();
843 pending_state.compute_session_keys(session_info.master_secret());
844 pending_state.set_resume_certs(session_info.peer_certs());
845
846 if(!save_session(session_info))
847 {
848 session_manager().remove_entry(session_info.session_id());
849
850 if(pending_state.server_hello()->supports_session_ticket()) // send an empty ticket
851 {
852 pending_state.new_session_ticket(
853 new New_Session_Ticket(pending_state.handshake_io(),
854 pending_state.hash()));
855 }
856 }
857
858 if(pending_state.server_hello()->supports_session_ticket() && !pending_state.new_session_ticket())
859 {
860 try
861 {
862 const SymmetricKey ticket_key = m_creds.psk("tls-server", "session-ticket", "");
863
864 pending_state.new_session_ticket(
865 new New_Session_Ticket(pending_state.handshake_io(),
866 pending_state.hash(),
867 session_info.encrypt(ticket_key, rng()),
868 policy().session_ticket_lifetime()));
869 }
870 catch(...) {}
871
872 if(!pending_state.new_session_ticket())
873 {
874 pending_state.new_session_ticket(
875 new New_Session_Ticket(pending_state.handshake_io(), pending_state.hash()));
876 }
877 }
878
879 pending_state.handshake_io().send(Change_Cipher_Spec());
880
881 change_cipher_spec_writer(SERVER);
882
883 pending_state.server_finished(new Finished(pending_state.handshake_io(), pending_state, SERVER));
884 pending_state.set_expected_next(HANDSHAKE_CCS);
885 }
886
session_create(Server_Handshake_State & pending_state,bool have_session_ticket_key)887 void Server::session_create(Server_Handshake_State& pending_state,
888 bool have_session_ticket_key)
889 {
890 std::map<std::string, std::vector<X509_Certificate>> cert_chains;
891
892 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
893
894 cert_chains = get_server_certs(sni_hostname, m_creds);
895
896 if(sni_hostname != "" && cert_chains.empty())
897 {
898 cert_chains = get_server_certs("", m_creds);
899
900 /*
901 * Only send the unrecognized_name alert if we couldn't
902 * find any certs for the requested name but did find at
903 * least one cert to use in general. That avoids sending an
904 * unrecognized_name when a server is configured for purely
905 * anonymous/PSK operation.
906 */
907 if(!cert_chains.empty())
908 send_warning_alert(Alert::UNRECOGNIZED_NAME);
909 }
910
911 const uint16_t ciphersuite = choose_ciphersuite(policy(), pending_state.version(),
912 m_creds, cert_chains,
913 *pending_state.client_hello());
914
915 Server_Hello::Settings srv_settings(
916 make_hello_random(rng(), policy()), // new session ID
917 pending_state.version(),
918 ciphersuite,
919 have_session_ticket_key);
920
921 pending_state.server_hello(new Server_Hello(
922 pending_state.handshake_io(),
923 pending_state.hash(),
924 policy(),
925 callbacks(),
926 rng(),
927 secure_renegotiation_data_for_server_hello(),
928 *pending_state.client_hello(),
929 srv_settings,
930 m_next_protocol));
931
932 secure_renegotiation_check(pending_state.server_hello());
933
934 const Ciphersuite& pending_suite = pending_state.ciphersuite();
935
936 Private_Key* private_key = nullptr;
937
938 if(pending_suite.signature_used() || pending_suite.kex_method() == Kex_Algo::STATIC_RSA)
939 {
940 const std::string algo_used =
941 pending_suite.signature_used() ? pending_suite.sig_algo() : "RSA";
942
943 BOTAN_ASSERT(!cert_chains[algo_used].empty(),
944 "Attempting to send empty certificate chain");
945
946 pending_state.server_certs(new Certificate(pending_state.handshake_io(),
947 pending_state.hash(),
948 cert_chains[algo_used]));
949
950 if(pending_state.client_hello()->supports_cert_status_message() && pending_state.is_a_resumption() == false)
951 {
952 auto csr = pending_state.client_hello()->extensions().get<Certificate_Status_Request>();
953 // csr is non-null if client_hello()->supports_cert_status_message()
954 BOTAN_ASSERT_NOMSG(csr != nullptr);
955 const auto resp_bytes = callbacks().tls_provide_cert_status(cert_chains[algo_used], *csr);
956 if(resp_bytes.size() > 0)
957 {
958 pending_state.server_cert_status(new Certificate_Status(
959 pending_state.handshake_io(),
960 pending_state.hash(),
961 resp_bytes
962 ));
963 }
964 }
965
966 private_key = m_creds.private_key_for(
967 pending_state.server_certs()->cert_chain()[0],
968 "tls-server",
969 sni_hostname);
970
971 if(!private_key)
972 throw Internal_Error("No private key located for associated server cert");
973 }
974
975 if(pending_suite.kex_method() == Kex_Algo::STATIC_RSA)
976 {
977 pending_state.set_server_rsa_kex_key(private_key);
978 }
979 else
980 {
981 pending_state.server_kex(new Server_Key_Exchange(pending_state.handshake_io(),
982 pending_state, policy(),
983 m_creds, rng(), private_key));
984 }
985
986 auto trusted_CAs = m_creds.trusted_certificate_authorities("tls-server", sni_hostname);
987
988 std::vector<X509_DN> client_auth_CAs;
989
990 for(auto store : trusted_CAs)
991 {
992 auto subjects = store->all_subjects();
993 client_auth_CAs.insert(client_auth_CAs.end(), subjects.begin(), subjects.end());
994 }
995
996 const bool request_cert =
997 (client_auth_CAs.empty() == false) ||
998 policy().request_client_certificate_authentication();
999
1000 if(request_cert && pending_state.ciphersuite().signature_used())
1001 {
1002 pending_state.cert_req(
1003 new Certificate_Req(pending_state.handshake_io(),
1004 pending_state.hash(),
1005 policy(),
1006 client_auth_CAs,
1007 pending_state.version()));
1008
1009 /*
1010 SSLv3 allowed clients to skip the Certificate message entirely
1011 if they wanted. In TLS v1.0 and later clients must send a
1012 (possibly empty) Certificate message
1013 */
1014 pending_state.set_expected_next(CERTIFICATE);
1015 }
1016 else
1017 {
1018 pending_state.set_expected_next(CLIENT_KEX);
1019 }
1020
1021 pending_state.server_hello_done(new Server_Hello_Done(pending_state.handshake_io(), pending_state.hash()));
1022 }
1023 }
1024
1025 }
1026