Botan 3.12.0
Crypto and TLS for C&
tls_server_impl_12.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/internal/tls_server_impl_12.h>
10
11#include <botan/certstor.h>
12#include <botan/ocsp.h>
13#include <botan/tls_callbacks.h>
14#include <botan/tls_magic.h>
15#include <botan/tls_messages_12.h>
16#include <botan/tls_policy.h>
17#include <botan/tls_version.h>
18#include <botan/internal/ct_utils.h>
19#include <botan/internal/stl_util.h>
20#include <botan/internal/tls_handshake_state.h>
21#include <botan/internal/tls_messages_internal.h>
22#include <unordered_set>
23
24namespace Botan::TLS {
25
26class Server_Handshake_State final : public Handshake_State {
27 public:
28 Server_Handshake_State(std::unique_ptr<Handshake_IO> io, Callbacks& cb) : Handshake_State(std::move(io), cb) {}
29
30 Private_Key* server_rsa_kex_key() { return m_server_rsa_kex_key.get(); }
31
32 void set_server_rsa_kex_key(std::shared_ptr<Private_Key> key) { m_server_rsa_kex_key = std::move(key); }
33
34 bool allow_session_resumption() const { return m_allow_session_resumption; }
35
36 void set_allow_session_resumption(bool allow_session_resumption) {
37 m_allow_session_resumption = allow_session_resumption;
38 }
39
40 const std::vector<X509_Certificate>& resume_peer_certs() const { return m_resume_peer_certs; }
41
42 void set_resume_certs(const std::vector<X509_Certificate>& certs) { m_resume_peer_certs = certs; }
43
44 void mark_as_resumption() { m_is_a_resumption = true; }
45
46 bool is_a_resumption() const { return m_is_a_resumption; }
47
48 std::vector<X509_Certificate> peer_cert_chain() const override {
49 if(!m_resume_peer_certs.empty()) {
50 return m_resume_peer_certs;
51 }
52 if(client_certs() != nullptr) {
53 return client_certs()->cert_chain();
54 }
55 return {};
56 }
57
58 private:
59 // Used by the server only, in case of RSA key exchange.
60 std::shared_ptr<Private_Key> m_server_rsa_kex_key;
61
62 /*
63 * Used by the server to know if resumption should be allowed on
64 * a server-initiated renegotiation
65 */
66 bool m_allow_session_resumption = true;
67
68 bool m_is_a_resumption = false;
69
70 std::vector<X509_Certificate> m_resume_peer_certs;
71};
72
73namespace {
74
75std::optional<Session> check_for_resume(const Session_Handle& handle_to_resume,
76 Session_Manager& session_manager,
77 Callbacks& cb,
78 const Policy& policy,
79 const Client_Hello_12* client_hello) {
80 auto session = session_manager.retrieve(handle_to_resume, cb, policy);
81 if(!session.has_value()) {
82 return std::nullopt;
83 }
84
85 // wrong version
86 if(client_hello->legacy_version() != session->version()) {
87 return std::nullopt;
88 }
89
90 // client didn't send original ciphersuite
91 if(!value_exists(client_hello->ciphersuites(), session->ciphersuite_code())) {
92 return std::nullopt;
93 }
94
95 // client sent a different SNI hostname
96 if(!client_hello->sni_hostname().empty() && client_hello->sni_hostname() != session->server_info().hostname()) {
97 return std::nullopt;
98 }
99
100 // Checking extended_master_secret on resume (RFC 7627 section 5.3)
101 if(client_hello->supports_extended_master_secret() != session->supports_extended_master_secret()) {
102 if(!session->supports_extended_master_secret()) {
103 return std::nullopt; // force new handshake with extended master secret
104 } else {
105 /*
106 Client previously negotiated session with extended master secret,
107 but has now attempted to resume without the extension: abort
108 */
109 throw TLS_Exception(Alert::HandshakeFailure, "Client resumed extended ms session without sending extension");
110 }
111 }
112
113 // Checking encrypt_then_mac on resume (RFC 7366 section 3.1)
114 if(!client_hello->supports_encrypt_then_mac() && session->supports_encrypt_then_mac()) {
115 /*
116 Client previously negotiated session with Encrypt-then-MAC,
117 but has now attempted to resume without the extension: abort
118 */
119 throw TLS_Exception(Alert::HandshakeFailure, "Client resumed Encrypt-then-MAC session without sending extension");
120 }
121
122 return session;
123}
124
125/*
126* Choose which ciphersuite to use
127*/
128uint16_t choose_ciphersuite(const Policy& policy,
129 Protocol_Version version,
130 const std::map<std::string, std::vector<X509_Certificate>>& cert_chains,
131 const Client_Hello_12& client_hello) {
132 const bool our_choice = policy.server_uses_own_ciphersuite_preferences();
133 const std::vector<uint16_t>& client_suites = client_hello.ciphersuites();
134 const std::vector<uint16_t> server_suites = policy.ciphersuite_list(version);
135
136 if(server_suites.empty()) {
137 throw TLS_Exception(Alert::HandshakeFailure, "Policy forbids us from negotiating any ciphersuite");
138 }
139
140 const bool have_shared_ecc_curve =
141 (policy.choose_key_exchange_group(client_hello.supported_ecc_curves(), {}) != Group_Params::NONE);
142
143 const bool client_supports_ffdhe_groups = !client_hello.supported_dh_groups().empty();
144
145 const bool have_shared_dh_group =
146 (policy.choose_key_exchange_group(client_hello.supported_dh_groups(), {}) != Group_Params::NONE);
147
148 const std::unordered_set<uint16_t> client_suite_set(client_suites.begin(), client_suites.end());
149
150 const std::vector<Signature_Scheme> allowed_sig_schemes = policy.allowed_signature_schemes();
151 const std::vector<Signature_Scheme> client_sig_methods = client_hello.signature_schemes();
152
153 // Algorithm names (eg "RSA", "ECDSA") for which the client offered at least
154 // one signature_scheme that is available, is in our policy, and uses a hash we accept.
155 const std::unordered_set<std::string> client_sig_algs = [&] {
156 std::unordered_set<uint16_t> allowed_codes;
157 allowed_codes.reserve(allowed_sig_schemes.size());
158 for(auto s : allowed_sig_schemes) {
159 allowed_codes.insert(static_cast<uint16_t>(s.wire_code()));
160 }
161 std::unordered_set<std::string> result;
162 for(const Signature_Scheme scheme : client_sig_methods) {
163 if(!scheme.is_available()) {
164 continue;
165 }
166 if(!allowed_codes.contains(static_cast<uint16_t>(scheme.wire_code()))) {
167 continue;
168 }
169 if(!policy.allowed_signature_hash(scheme.hash_function_name())) {
170 continue;
171 }
172 result.insert(scheme.algorithm_name());
173 }
174 return result;
175 }();
176
177 /*
178 Walk down one list in preference order
179 */
180 const std::vector<uint16_t>& pref_list = our_choice ? server_suites : client_suites;
181
182 auto in_other_list = [&](uint16_t suite_id) {
183 // server_suites is small and policy-controlled
184 return our_choice ? client_suite_set.contains(suite_id) : value_exists(server_suites, suite_id);
185 };
186
187 for(auto suite_id : pref_list) {
188 if(!in_other_list(suite_id)) {
189 continue;
190 }
191
192 const auto suite = Ciphersuite::by_id(suite_id);
193
194 if(!suite.has_value() || !suite->valid()) {
195 continue;
196 }
197
198 if(have_shared_ecc_curve == false && suite->ecc_ciphersuite()) {
199 continue;
200 }
201
202 if(suite->kex_method() == Kex_Algo::DH && client_supports_ffdhe_groups && !have_shared_dh_group) {
203 continue;
204 }
205
206 // For non-anon ciphersuites
207 if(suite->is_certificate_required()) {
208 const std::string cert_algo = suite->signature_used() ? suite->sig_algo() : "RSA";
209
210 // Do we have any certificates for this sig?
211 if(!cert_chains.contains(cert_algo)) {
212 continue;
213 }
214 }
215
216 if(suite->signature_used()) {
217 // The client's signature_algorithms list might not include a scheme
218 // matching this suite's sig_algo (e.g. the client offered ECDSA
219 // schemes but we're considering an RSA suite). That's just a
220 // mismatch on this candidate, not a handshake-fatal condition - try
221 // the next suite. The final "Can't agree on a ciphersuite" throw
222 // below fires only if no candidate works.
223 if(!client_sig_algs.contains(suite->sig_algo())) {
224 continue;
225 }
226 }
227
228 return suite_id;
229 }
230
231 // RFC 7919 Section 4.
232 // If the [Supported Groups] extension is present
233 // with FFDHE groups, none of the client’s offered groups are acceptable
234 // by the server, and none of the client’s proposed non-FFDHE cipher
235 // suites are acceptable to the server, the server MUST end the
236 // connection with a fatal TLS alert of type insufficient_security(71).
237 if(client_supports_ffdhe_groups && !have_shared_dh_group) {
238 throw TLS_Exception(Alert::InsufficientSecurity, "Can't agree on a sufficiently strong ciphersuite with client");
239 }
240
241 throw TLS_Exception(Alert::HandshakeFailure, "Can't agree on a ciphersuite with client");
242}
243
244std::map<std::string, std::vector<X509_Certificate>> get_server_certs(
245 std::string_view hostname, const std::vector<Signature_Scheme>& cert_sig_schemes, Credentials_Manager& creds) {
246 const std::vector<std::string> cert_types = {"RSA", "ECDSA"};
247
248 std::map<std::string, std::vector<X509_Certificate>> cert_chains;
249
250 for(const auto& cert_type : cert_types) {
251 const std::vector<X509_Certificate> certs = creds.cert_chain_single_type(
252 cert_type, to_algorithm_identifiers(cert_sig_schemes), "tls-server", std::string(hostname));
253
254 if(!certs.empty()) {
255 cert_chains[cert_type] = certs;
256 }
257 }
258
259 return cert_chains;
260}
261
262} // namespace
263
264Server_Impl_12::Server_Impl_12(const std::shared_ptr<Callbacks>& callbacks,
265 const std::shared_ptr<Session_Manager>& session_manager,
266 const std::shared_ptr<Credentials_Manager>& creds,
267 const std::shared_ptr<const Policy>& policy,
268 const std::shared_ptr<RandomNumberGenerator>& rng,
269 bool is_datagram,
270 size_t io_buf_sz) :
271 Channel_Impl_12(callbacks, session_manager, rng, policy, true, is_datagram, io_buf_sz), m_creds(creds) {
272 BOTAN_ASSERT_NONNULL(m_creds);
273}
274
276 Channel_Impl_12(downgrade_info.callbacks,
277 downgrade_info.session_manager,
278 downgrade_info.rng,
279 downgrade_info.policy,
280 true /* is_server*/,
281 false /* TLS 1.3 does not support DTLS yet */,
282 downgrade_info.io_buffer_size),
283 m_creds(downgrade_info.creds) {}
284
285std::unique_ptr<Handshake_State> Server_Impl_12::new_handshake_state(std::unique_ptr<Handshake_IO> io) {
286 auto state = std::make_unique<Server_Handshake_State>(std::move(io), callbacks());
287 state->set_expected_next(Handshake_Type::ClientHello);
288 return state;
289}
290
291/*
292* Send a hello request to the client
293*/
294void Server_Impl_12::initiate_handshake(Handshake_State& state, bool force_full_renegotiation) {
295 dynamic_cast<Server_Handshake_State&>(state).set_allow_session_resumption(!force_full_renegotiation);
296
297 const Hello_Request hello_req(state.handshake_io());
298}
299
300namespace {
301
302Protocol_Version select_version(const TLS::Policy& policy,
303 Protocol_Version client_offer,
304 Protocol_Version active_version,
305 const std::vector<Protocol_Version>& supported_versions) {
306 const bool is_datagram = client_offer.is_datagram_protocol();
307 const bool initial_handshake = (active_version.valid() == false);
308
309 if(!supported_versions.empty()) {
310 if(is_datagram) {
311 if(policy.allow_dtls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V12))) {
312 return Protocol_Version::DTLS_V12;
313 }
314 throw TLS_Exception(Alert::ProtocolVersion, "No shared DTLS version");
315 } else {
316 if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V12))) {
317 return Protocol_Version::TLS_V12;
318 }
319 throw TLS_Exception(Alert::ProtocolVersion, "No shared TLS version");
320 }
321 }
322
323 if(!initial_handshake) {
324 /*
325 * If this is a renegotiation, and the client has offered a
326 * later version than what it initially negotiated, negotiate
327 * the old version. This matches OpenSSL's behavior. If the
328 * client is offering a version earlier than what it initially
329 * negotiated, reject as a probable attack.
330 */
331 if(active_version > client_offer) {
332 throw TLS_Exception(
333 Alert::ProtocolVersion,
334 "Client negotiated " + active_version.to_string() + " then renegotiated with " + client_offer.to_string());
335 } else {
336 return active_version;
337 }
338 }
339
340 if(is_datagram) {
341 if(policy.allow_dtls12() && client_offer >= Protocol_Version::DTLS_V12) {
342 return Protocol_Version::DTLS_V12;
343 }
344 } else {
345 if(policy.allow_tls12() && client_offer >= Protocol_Version::TLS_V12) {
346 return Protocol_Version::TLS_V12;
347 }
348 }
349
350 throw TLS_Exception(Alert::ProtocolVersion,
351 "Client version " + client_offer.to_string() + " is unacceptable by policy");
352}
353} // namespace
354
355/*
356* Process a Client Hello Message
357*/
358void Server_Impl_12::process_client_hello_msg(Server_Handshake_State& pending_state,
359 const std::vector<uint8_t>& contents,
360 bool epoch0_restart) {
361 BOTAN_ASSERT_IMPLICATION(epoch0_restart, active_state().has_value(), "Can't restart with a dead connection");
362
363 const bool initial_handshake = epoch0_restart || !active_state().has_value();
364
365 if(initial_handshake == false && policy().allow_client_initiated_renegotiation() == false) {
366 if(policy().abort_connection_on_undesired_renegotiation()) {
367 throw TLS_Exception(Alert::NoRenegotiation, "Server policy prohibits renegotiation");
368 } else {
369 send_warning_alert(Alert::NoRenegotiation);
370 }
371 return;
372 }
373
374 if(!policy().allow_insecure_renegotiation() && !(initial_handshake || secure_renegotiation_supported())) {
375 send_warning_alert(Alert::NoRenegotiation);
376 return;
377 }
378
379 if(pending_state.handshake_io().have_more_data()) {
380 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after ClientHello");
381 }
382
383 pending_state.client_hello(std::make_unique<Client_Hello_12>(contents));
384 const Protocol_Version client_offer = pending_state.client_hello()->legacy_version();
385 const bool datagram = client_offer.is_datagram_protocol();
386
387 if(datagram) {
388 if(client_offer.major_version() == 0xFF) {
389 throw TLS_Exception(Alert::ProtocolVersion, "Client offered DTLS version with major version 0xFF");
390 }
391 } else {
392 if(client_offer.major_version() < 3) {
393 throw TLS_Exception(Alert::ProtocolVersion, "Client offered TLS version with major version under 3");
394 }
395 if(client_offer.major_version() == 3 && client_offer.minor_version() == 0) {
396 throw TLS_Exception(Alert::ProtocolVersion, "Client offered SSLv3 which is not supported");
397 }
398 }
399
400 /*
401 * BoGo test suite expects that we will send the hello verify with a record
402 * version matching the version that is eventually negotiated. This is wrong
403 * but harmless, so go with it. Also doing the version negotiation step first
404 * allows to immediately close the connection with an alert if the client has
405 * offered a version that we are not going to negotiate anyway, instead of
406 * making them first do the cookie exchange and then telling them no.
407 *
408 * There is no issue with amplification here, since the alert is just 2 bytes.
409 */
410 const Protocol_Version negotiated_version =
411 select_version(policy(),
412 client_offer,
413 active_state().has_value() ? active_state()->version() : Protocol_Version(),
414 pending_state.client_hello()->supported_versions());
415
416 pending_state.set_version(negotiated_version);
417
418 const auto compression_methods = pending_state.client_hello()->compression_methods();
419 if(!value_exists(compression_methods, uint8_t(0))) {
420 throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
421 }
422
423 if(initial_handshake && datagram) {
424 SymmetricKey cookie_secret;
425
426 try {
427 cookie_secret = m_creds->psk("tls-server", "dtls-cookie-secret", "");
428 } catch(...) {}
429
430 if(!cookie_secret.empty()) {
431 const std::string client_identity = callbacks().tls_peer_network_identity();
432 const Hello_Verify_Request verify(
433 pending_state.client_hello()->cookie_input_data(), client_identity, cookie_secret);
434
435 if(!CT::is_equal<uint8_t>(pending_state.client_hello()->cookie(), verify.cookie()).as_bool()) {
436 if(epoch0_restart) {
437 pending_state.handshake_io().send_under_epoch(verify, 0);
438 } else {
439 pending_state.handshake_io().send(verify);
440 }
441
442 pending_state.client_hello(nullptr);
443 pending_state.set_expected_next(Handshake_Type::ClientHello);
444 return;
445 }
446 } else if(epoch0_restart) {
447 throw TLS_Exception(Alert::HandshakeFailure, "Reuse of DTLS association requires DTLS cookie secret be set");
448 }
449 }
450
451 if(epoch0_restart) {
452 // If we reached here then we were able to verify the cookie
454 }
455
456 secure_renegotiation_check(pending_state.client_hello());
457
458 // RFC 7627 / RFC 9325 4.4: optionally require Extended Master Secret
459 if(policy().require_extended_master_secret() && !pending_state.client_hello()->supports_extended_master_secret()) {
460 throw TLS_Exception(Alert::HandshakeFailure,
461 "Policy requires the Extended Master Secret extension but the client did not send it");
462 }
463
464 // RFC 7627 5.3 has an explicit MUST regarding EMS mismatch on resumption
465 //
466 // "If the original session used the 'extended_master_secret'
467 // extension but the new ClientHello does not contain it, the
468 // server MUST abort the abbreviated handshake."
469 //
470 // There is apparently no RFC requirement that a client must not drop EMS between the
471 // initial negotiation and a renegotiation... but there is also no RFC requirement
472 // that we must accept it. So we don't.
473 if(const auto& active = active_state()) {
474 const bool ems_pending = pending_state.client_hello()->supports_extended_master_secret();
475 if(active->supports_extended_master_secret() == true && ems_pending == false) {
476 throw TLS_Exception(Alert::HandshakeFailure,
477 "Renegotiation ClientHello dropped the Extended Master Secret extension");
478 }
479 }
480
482 pending_state.client_hello()->extensions(), Connection_Side::Client, Handshake_Type::ClientHello);
483
484 const auto session_handle = pending_state.client_hello()->session_handle();
485
486 std::optional<Session> session_info;
487 if(pending_state.allow_session_resumption() && session_handle.has_value()) {
488 session_info = check_for_resume(
489 session_handle.value(), session_manager(), callbacks(), policy(), pending_state.client_hello());
490 }
491
492 m_next_protocol = "";
493 if(pending_state.client_hello()->supports_alpn()) {
494 const auto offered = pending_state.client_hello()->next_protocols();
495 m_next_protocol = callbacks().tls_server_choose_app_protocol(offered);
496 // RFC 7301 3.2: if a protocol is selected, the server MUST select one
497 // of the protocols advertised by the client. An empty return signals
498 // "no ALPN" and is allowed.
499 if(!m_next_protocol.empty() && !value_exists(offered, m_next_protocol)) {
500 throw TLS_Exception(Alert::InternalError, "Application chose an ALPN protocol that the client did not offer");
501 }
502 }
503
504 if(session_info.has_value()) {
505 this->session_resume(pending_state, {session_info.value(), session_handle.value()});
506 } else {
507 // new session
508 this->session_create(pending_state);
509 }
510}
511
512void Server_Impl_12::process_certificate_msg(Server_Handshake_State& pending_state,
513 const std::vector<uint8_t>& contents) {
514 pending_state.client_certs(std::make_unique<Certificate_12>(contents, policy()));
515
516 // CERTIFICATE_REQUIRED would make more sense but BoGo expects handshake failure alert
517 if(pending_state.client_certs()->empty() && policy().require_client_certificate_authentication()) {
518 throw TLS_Exception(Alert::HandshakeFailure, "Policy requires client send a certificate, but it did not");
519 }
520
521 pending_state.set_expected_next(Handshake_Type::ClientKeyExchange);
522}
523
524void Server_Impl_12::process_client_key_exchange_msg(Server_Handshake_State& pending_state,
525 const std::vector<uint8_t>& contents) {
526 if(pending_state.received_handshake_msg(Handshake_Type::Certificate) && !pending_state.client_certs()->empty()) {
527 pending_state.set_expected_next(Handshake_Type::CertificateVerify);
528 } else {
529 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
530 }
531
532 pending_state.client_kex(std::make_unique<Client_Key_Exchange>(
533 contents, pending_state, pending_state.server_rsa_kex_key(), *m_creds, policy(), rng()));
534
535 pending_state.compute_session_keys();
536 if(policy().allow_ssl_key_log_file()) {
537 // draft-thomson-tls-keylogfile-00 Section 3.2
538 // An implementation of TLS 1.2 (and also earlier versions) use
539 // the label "CLIENT_RANDOM" to identify the "master" secret for
540 // the connection.
542 "CLIENT_RANDOM", pending_state.client_hello()->random(), pending_state.session_keys().master_secret());
543 }
544}
545
546void Server_Impl_12::process_change_cipher_spec_msg(Server_Handshake_State& pending_state) {
547 pending_state.set_expected_next(Handshake_Type::Finished);
549}
550
551void Server_Impl_12::process_certificate_verify_msg(Server_Handshake_State& pending_state,
552 Handshake_Type type,
553 const std::vector<uint8_t>& contents) {
554 pending_state.client_verify(std::make_unique<Certificate_Verify_12>(contents));
555
556 const std::vector<X509_Certificate>& client_certs = pending_state.client_certs()->cert_chain();
557
558 if(client_certs.empty()) {
559 throw TLS_Exception(Alert::DecodeError, "No client certificate sent");
560 }
561
562 const auto cert_constraints = client_certs[0].constraints();
563 if(!cert_constraints.empty()) {
564 if(!cert_constraints.includes_any(Key_Constraints::DigitalSignature, Key_Constraints::NonRepudiation)) {
565 throw TLS_Exception(Alert::BadCertificate, "Client certificate does not support signing");
566 }
567 }
568
569 const bool sig_valid = pending_state.client_verify()->verify(client_certs[0], pending_state, policy());
570
571 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
572
573 /*
574 * Using DECRYPT_ERROR looks weird here, but per RFC 4346 is for
575 * "A handshake cryptographic operation failed, including being
576 * unable to correctly verify a signature, ..."
577 */
578 if(!sig_valid) {
579 throw TLS_Exception(Alert::DecryptError, "Client cert verify failed");
580 }
581
582 try {
583 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
584 auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-server", sni_hostname);
585
586 callbacks().tls_verify_cert_chain(client_certs,
587 {}, // ocsp
588 trusted_CAs,
590 sni_hostname,
591 policy());
592 } catch(std::exception& e) {
593 throw TLS_Exception(Alert::BadCertificate, e.what());
594 }
595
596 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
597}
598
599void Server_Impl_12::process_finished_msg(Server_Handshake_State& pending_state,
600 Handshake_Type type,
601 const std::vector<uint8_t>& contents) {
602 pending_state.set_expected_next(Handshake_Type::None);
603
604 if(pending_state.handshake_io().have_more_data()) {
605 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after Finished");
606 }
607
608 pending_state.client_finished(std::make_unique<Finished_12>(contents));
609
610 if(!pending_state.client_finished()->verify(pending_state, Connection_Side::Client)) {
611 throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify");
612 }
613
614 if(pending_state.server_finished() == nullptr) {
615 // already sent finished if resuming, so this is a new session
616
617 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
618
619 Session session_info(pending_state.session_keys().master_secret(),
620 pending_state.server_hello()->legacy_version(),
621 pending_state.server_hello()->ciphersuite(),
623 pending_state.server_hello()->supports_extended_master_secret(),
624 pending_state.server_hello()->supports_encrypt_then_mac(),
625 pending_state.peer_cert_chain(),
626 Server_Information(pending_state.client_hello()->sni_hostname()),
627 pending_state.server_hello()->srtp_profile(),
628 callbacks().tls_current_timestamp());
629
630 // Give the application a chance for a final veto before fully
631 // establishing the connection.
633 Session_Summary summary(session_info, pending_state.is_a_resumption(), external_psk_identity());
634 summary.set_session_id(pending_state.server_hello()->session_id());
635 return summary;
636 }());
637
638 if(callbacks().tls_should_persist_resumption_information(session_info)) {
639 auto handle = session_manager().establish(session_info,
640 pending_state.server_hello()->session_id(),
641 !pending_state.server_hello()->supports_session_ticket());
642
643 if(pending_state.server_hello()->supports_session_ticket() && handle.has_value() && handle->is_ticket()) {
644 pending_state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(
645 pending_state.handshake_io(),
646 pending_state.hash(),
647 handle->ticket().value(),
648 static_cast<uint32_t>(policy().session_ticket_lifetime().count())));
649 }
650 }
651
652 if(pending_state.new_session_ticket() == nullptr && pending_state.server_hello()->supports_session_ticket()) {
653 pending_state.new_session_ticket(
654 std::make_unique<New_Session_Ticket_12>(pending_state.handshake_io(), pending_state.hash()));
655 }
656
657 pending_state.handshake_io().send(Change_Cipher_Spec());
658
660
661 pending_state.server_finished(
662 std::make_unique<Finished_12>(pending_state.handshake_io(), pending_state, Connection_Side::Server));
663 }
664
666}
667
668/*
669* Process a handshake message
670*/
671void Server_Impl_12::process_handshake_msg(Handshake_State& state_base,
672 Handshake_Type type,
673 const std::vector<uint8_t>& contents,
674 bool epoch0_restart) {
675 Server_Handshake_State& state = dynamic_cast<Server_Handshake_State&>(state_base);
676 state.confirm_transition_to(type);
677
678 /*
679 * The change cipher spec message isn't technically a handshake
680 * message so it's not included in the hash. The finished and
681 * certificate verify messages are verified based on the current
682 * state of the hash *before* this message so we delay adding them
683 * to the hash computation until we've processed them below.
684 */
687 state.hash().update(state.handshake_io().format(contents, type));
688 }
689
690 switch(type) {
692 return this->process_client_hello_msg(state, contents, epoch0_restart);
693
695 return this->process_certificate_msg(state, contents);
696
698 return this->process_client_key_exchange_msg(state, contents);
699
701 return this->process_certificate_verify_msg(state, type, contents);
702
704 return this->process_change_cipher_spec_msg(state);
705
707 return this->process_finished_msg(state, type, contents);
708
709 default:
710 throw Unexpected_Message("Unknown handshake message received");
711 }
712}
713
714void Server_Impl_12::session_resume(Server_Handshake_State& pending_state, const Session_with_Handle& session) {
715 // Only offer a resuming client a new ticket if they didn't send one this time,
716 // ie, resumed via server-side resumption. TODO: also send one if expiring soon?
717
718 const bool offer_new_session_ticket = pending_state.client_hello()->supports_session_ticket() &&
719 pending_state.client_hello()->session_ticket().empty() &&
721
722 pending_state.server_hello(std::make_unique<Server_Hello_12>(pending_state.handshake_io(),
723 pending_state.hash(),
724 policy(),
725 callbacks(),
726 rng(),
728 *pending_state.client_hello(),
729 session.session,
730 offer_new_session_ticket,
731 m_next_protocol));
732
733 secure_renegotiation_check(pending_state.server_hello());
734
735 pending_state.mark_as_resumption();
736 pending_state.compute_session_keys(session.session.master_secret());
737 if(policy().allow_ssl_key_log_file()) {
738 // draft-thomson-tls-keylogfile-00 Section 3.2
739 // An implementation of TLS 1.2 (and also earlier versions) use
740 // the label "CLIENT_RANDOM" to identify the "master" secret for
741 // the connection.
743 "CLIENT_RANDOM", pending_state.client_hello()->random(), pending_state.session_keys().master_secret());
744 }
745 pending_state.set_resume_certs(session.session.peer_certs());
746
747 // Give the application a chance for a final veto before fully
748 // establishing the connection.
750 Session_Summary summary(session.session, pending_state.is_a_resumption(), external_psk_identity());
751 summary.set_session_id(pending_state.server_hello()->session_id());
752 if(auto ticket = session.handle.ticket()) {
753 summary.set_session_ticket(std::move(ticket.value()));
754 }
755 return summary;
756 }());
757
758 auto new_handle = [&, this]() -> std::optional<Session_Handle> {
759 if(!callbacks().tls_should_persist_resumption_information(session.session)) {
760 session_manager().remove(session.handle);
761 return std::nullopt;
762 } else {
763 return session_manager().establish(session.session, session.handle.id());
764 }
765 }();
766
767 if(pending_state.server_hello()->supports_session_ticket()) {
768 if(new_handle.has_value() && new_handle->is_ticket()) {
769 const uint32_t lifetime = static_cast<uint32_t>(policy().session_ticket_lifetime().count());
770 pending_state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(
771 pending_state.handshake_io(), pending_state.hash(), new_handle->ticket().value(), lifetime));
772 } else {
773 pending_state.new_session_ticket(
774 std::make_unique<New_Session_Ticket_12>(pending_state.handshake_io(), pending_state.hash()));
775 }
776 }
777
778 pending_state.handshake_io().send(Change_Cipher_Spec());
779
781
782 pending_state.server_finished(
783 std::make_unique<Finished_12>(pending_state.handshake_io(), pending_state, Connection_Side::Server));
784 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
785}
786
787void Server_Impl_12::session_create(Server_Handshake_State& pending_state) {
788 std::map<std::string, std::vector<X509_Certificate>> cert_chains;
789
790 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
791
792 // RFC 8446 1.3
793 // The "signature_algorithms_cert" extension allows a client to indicate
794 // which signature algorithms it can validate in X.509 certificates.
795 //
796 // RFC 8446 4.2.3
797 // TLS 1.2 implementations SHOULD also process this extension.
798 const auto cert_signature_schemes = pending_state.client_hello()->certificate_signature_schemes();
799 cert_chains = get_server_certs(sni_hostname, cert_signature_schemes, *m_creds);
800
801 if(!sni_hostname.empty() && cert_chains.empty()) {
802 cert_chains = get_server_certs("", cert_signature_schemes, *m_creds);
803
804 /*
805 * Only send the unrecognized_name alert if we couldn't
806 * find any certs for the requested name but did find at
807 * least one cert to use in general. That avoids sending an
808 * unrecognized_name when a server is configured for purely
809 * anonymous/PSK operation.
810 */
811 if(!cert_chains.empty()) {
812 send_warning_alert(Alert::UnrecognizedName);
813 }
814 }
815
816 const uint16_t ciphersuite =
817 choose_ciphersuite(policy(), pending_state.version(), cert_chains, *pending_state.client_hello());
818
819 const Server_Hello_12::Settings srv_settings(Session_ID(make_hello_random(rng(), callbacks(), policy())),
820 pending_state.version(),
821 ciphersuite,
822 session_manager().emits_session_tickets());
823
824 pending_state.server_hello(std::make_unique<Server_Hello_12>(pending_state.handshake_io(),
825 pending_state.hash(),
826 policy(),
827 callbacks(),
828 rng(),
830 *pending_state.client_hello(),
831 srv_settings,
832 m_next_protocol));
833
834 secure_renegotiation_check(pending_state.server_hello());
835
836 const Ciphersuite& pending_suite = pending_state.ciphersuite();
837
838 std::shared_ptr<Private_Key> private_key;
839
840 if(pending_suite.is_certificate_required()) {
841 const std::string algo_used = pending_suite.signature_used() ? pending_suite.sig_algo() : "RSA";
842
843 BOTAN_ASSERT(!cert_chains[algo_used].empty(), "Attempting to send empty certificate chain");
844
845 pending_state.server_certs(
846 std::make_unique<Certificate_12>(pending_state.handshake_io(), pending_state.hash(), cert_chains[algo_used]));
847
848 if(pending_state.client_hello()->supports_cert_status_message() && pending_state.is_a_resumption() == false) {
849 auto* csr = pending_state.client_hello()->extensions().get<Certificate_Status_Request>();
850 // csr is non-null if client_hello()->supports_cert_status_message()
851 BOTAN_ASSERT_NOMSG(csr != nullptr);
852 const auto resp_bytes = callbacks().tls_provide_cert_status(cert_chains[algo_used], *csr);
853 if(!resp_bytes.empty()) {
854 pending_state.server_cert_status(
855 std::make_unique<Certificate_Status_12>(pending_state.handshake_io(), pending_state.hash(), resp_bytes));
856 }
857 }
858
859 private_key = m_creds->private_key_for(pending_state.server_certs()->cert_chain()[0], "tls-server", sni_hostname);
860
861 if(!private_key) {
862 throw Internal_Error("No private key located for associated server cert");
863 }
864 }
865
866 if(pending_suite.kex_method() == Kex_Algo::STATIC_RSA) {
867 pending_state.set_server_rsa_kex_key(private_key);
868 } else {
869 pending_state.server_kex(std::make_unique<Server_Key_Exchange>(
870 pending_state.handshake_io(), pending_state, policy(), *m_creds, rng(), private_key.get()));
871 }
872
873 auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-server", sni_hostname);
874
875 std::vector<X509_DN> client_auth_CAs;
876
877 for(auto* store : trusted_CAs) {
878 auto subjects = store->all_subjects();
879 client_auth_CAs.insert(client_auth_CAs.end(), subjects.begin(), subjects.end());
880 }
881
882 const bool request_cert = (client_auth_CAs.empty() == false) || policy().request_client_certificate_authentication();
883
884 // RFC 5246 7.4.4: supported_signature_algorithms<2..2^16-2>
885 // Without at least one acceptable scheme we cannot construct a valid
886 // CertificateRequest, so client cert auth is unreachable regardless.
887 const bool can_request_cert = !policy().acceptable_signature_schemes().empty();
888
889 if(request_cert && can_request_cert && pending_state.ciphersuite().is_certificate_required()) {
890 pending_state.cert_req(std::make_unique<Certificate_Request_12>(
891 pending_state.handshake_io(), pending_state.hash(), policy(), client_auth_CAs));
892
893 /*
894 SSLv3 allowed clients to skip the Certificate message entirely
895 if they wanted. In TLS v1.0 and later clients must send a
896 (possibly empty) Certificate message
897 */
898 pending_state.set_expected_next(Handshake_Type::Certificate);
899 } else {
900 pending_state.set_expected_next(Handshake_Type::ClientKeyExchange);
901 }
902
903 pending_state.server_hello_done(
904 std::make_unique<Server_Hello_Done>(pending_state.handshake_io(), pending_state.hash()));
905}
906} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:114
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:101
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
virtual std::vector< uint8_t > tls_provide_cert_status(const std::vector< X509_Certificate > &chain, const Certificate_Status_Request &csr)
virtual std::string tls_peer_network_identity()
virtual std::string tls_server_choose_app_protocol(const std::vector< std::string > &client_protos)
virtual void tls_examine_extensions(const Extensions &extn, Connection_Side which_side, Handshake_Type which_message)
virtual void tls_session_established(const Session_Summary &session)
virtual void tls_verify_cert_chain(const std::vector< X509_Certificate > &cert_chain, const std::vector< std::optional< OCSP::Response > > &ocsp_responses, const std::vector< Certificate_Store * > &trusted_roots, Usage_Type usage, std::string_view hostname, const TLS::Policy &policy)
virtual void tls_ssl_key_log_data(std::string_view label, std::span< const uint8_t > client_random, std::span< const uint8_t > secret) const
const std::vector< X509_Certificate > & cert_chain() const
RandomNumberGenerator & rng()
void change_cipher_spec_reader(Connection_Side side)
std::vector< uint8_t > secure_renegotiation_data_for_server_hello() const
void secure_renegotiation_check(const Client_Hello_12 *client_hello)
Session_Manager & session_manager()
const Policy & policy() const
void change_cipher_spec_writer(Connection_Side side)
Channel_Impl_12(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< RandomNumberGenerator > &rng, const std::shared_ptr< const Policy > &policy, bool is_server, bool is_datagram, size_t io_buf_sz=TLS::Channel::IO_BUF_DEFAULT_SIZE)
const std::optional< Active_Connection_State_12 > & active_state() const
std::optional< std::string > external_psk_identity() const override
bool secure_renegotiation_supported() const override
void send_warning_alert(Alert::Type type)
static std::optional< Ciphersuite > by_id(uint16_t suite)
Handshake_State(std::unique_ptr< Handshake_IO > io, Callbacks &callbacks)
const Certificate_12 * client_certs() const
virtual std::vector< X509_Certificate > peer_cert_chain() const =0
virtual bool request_client_certificate_authentication() const
virtual std::vector< Signature_Scheme > acceptable_signature_schemes() const
virtual std::chrono::seconds session_ticket_lifetime() const
Server_Impl_12(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< Credentials_Manager > &creds, const std::shared_ptr< const Policy > &policy, const std::shared_ptr< RandomNumberGenerator > &rng, bool is_datagram=false, size_t reserved_io_buffer_size=TLS::Channel::IO_BUF_DEFAULT_SIZE)
Helper class to embody a session handle in all protocol versions.
virtual size_t remove(const Session_Handle &handle)=0
virtual std::optional< Session_Handle > establish(const Session &session, const std::optional< Session_ID > &id=std::nullopt, bool tls12_no_ticket=false)
Save a new Session and assign a Session_Handle (TLS Server).
constexpr CT::Mask< T > is_equal(const T x[], const T y[], size_t len)
Definition ct_utils.h:798
std::vector< AlgorithmIdentifier > to_algorithm_identifiers(const std::vector< Signature_Scheme > &schemes)
std::vector< uint8_t > make_hello_random(RandomNumberGenerator &rng, Callbacks &cb, const Policy &policy)
Strong< std::vector< uint8_t >, struct Session_ID_ > Session_ID
holds a TLS 1.2 session ID for stateful resumption
OctetString SymmetricKey
Definition symkey.h:140
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44