Botan 3.13.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
262secure_vector<uint8_t> load_dtls_cookie_secret(Credentials_Manager& creds) {
263 auto cookie_secret = [&]() -> secure_vector<uint8_t> {
264 try {
265 return creds.psk("tls-server", "dtls-cookie-secret", "").bits_of();
266 } catch(...) {
267 return {};
268 }
269 }();
270
271 if(cookie_secret.empty()) {
272 // TODO(Botan4): Simplify this error message that was meant to ease the
273 // burden on users running into a deliberate semver violation.
274 throw Invalid_State(
275 "Since Botan 3.13 DTLS server requires setting a non-empty cookie secret. "
276 "Either override Credentials_Manager::dtls_cookie_secret() or disable the "
277 "cookie exchange using TLS::Policy::dtls_server_require_cookie_exchange(), "
278 "if you understand the security implications of doing so.");
279 }
280
281 return cookie_secret;
282}
283
284} // namespace
285
286Server_Impl_12::Server_Impl_12(const std::shared_ptr<Callbacks>& callbacks,
287 const std::shared_ptr<Session_Manager>& session_manager,
288 const std::shared_ptr<Credentials_Manager>& creds,
289 const std::shared_ptr<const Policy>& policy,
290 const std::shared_ptr<RandomNumberGenerator>& rng,
291 bool is_datagram,
292 size_t io_buf_sz) :
293 Channel_Impl_12(callbacks, session_manager, rng, policy, true, is_datagram, io_buf_sz), m_creds(creds) {
294 BOTAN_ASSERT_NONNULL(m_creds);
295
296 // Try to load the cookie secret on initialization, rather than waiting to fail
297 // until the first client connects.
298 if(is_datagram && policy->dtls_server_require_cookie_exchange()) {
299 load_dtls_cookie_secret(*m_creds);
300 }
301}
302
303#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
304
305Server_Impl_12::Server_Impl_12(const Channel_Impl::Downgrade_Information& downgrade_info) :
306 Channel_Impl_12(downgrade_info.callbacks,
307 downgrade_info.session_manager,
308 downgrade_info.rng,
309 downgrade_info.policy,
310 true /* is_server*/,
311 false /* TLS 1.3 does not support DTLS yet */,
312 downgrade_info.io_buffer_size),
313 m_creds(downgrade_info.creds) {}
314
315#endif
316
317std::unique_ptr<Handshake_State> Server_Impl_12::new_handshake_state(std::unique_ptr<Handshake_IO> io) {
318 auto state = std::make_unique<Server_Handshake_State>(std::move(io), callbacks());
319 state->set_expected_next(Handshake_Type::ClientHello);
320 return state;
321}
322
323/*
324* Send a hello request to the client
325*/
326void Server_Impl_12::initiate_handshake(Handshake_State& state, bool force_full_renegotiation) {
327 dynamic_cast<Server_Handshake_State&>(state).set_allow_session_resumption(!force_full_renegotiation);
328
329 const Hello_Request hello_req(state.handshake_io());
330}
331
332namespace {
333
334Protocol_Version select_version(const TLS::Policy& policy,
335 Protocol_Version client_offer,
336 Protocol_Version active_version,
337 const std::vector<Protocol_Version>& supported_versions) {
338 const bool is_datagram = client_offer.is_datagram_protocol();
339 const bool initial_handshake = (active_version.valid() == false);
340
341 if(!supported_versions.empty()) {
342 if(is_datagram) {
343 if(policy.allow_dtls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V12))) {
344 return Protocol_Version::DTLS_V12;
345 }
346 throw TLS_Exception(Alert::ProtocolVersion, "No shared DTLS version");
347 } else {
348 if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V12))) {
349 return Protocol_Version::TLS_V12;
350 }
351 throw TLS_Exception(Alert::ProtocolVersion, "No shared TLS version");
352 }
353 }
354
355 if(!initial_handshake) {
356 /*
357 * If this is a renegotiation, and the client has offered a
358 * later version than what it initially negotiated, negotiate
359 * the old version. This matches OpenSSL's behavior. If the
360 * client is offering a version earlier than what it initially
361 * negotiated, reject as a probable attack.
362 */
363 if(active_version > client_offer) {
364 throw TLS_Exception(
365 Alert::ProtocolVersion,
366 "Client negotiated " + active_version.to_string() + " then renegotiated with " + client_offer.to_string());
367 } else {
368 return active_version;
369 }
370 }
371
372 if(is_datagram) {
373 if(policy.allow_dtls12() && client_offer >= Protocol_Version::DTLS_V12) {
374 return Protocol_Version::DTLS_V12;
375 }
376 } else {
377 if(policy.allow_tls12() && client_offer >= Protocol_Version::TLS_V12) {
378 return Protocol_Version::TLS_V12;
379 }
380 }
381
382 throw TLS_Exception(Alert::ProtocolVersion,
383 "Client version " + client_offer.to_string() + " is unacceptable by policy");
384}
385} // namespace
386
387/*
388* Process a Client Hello Message
389*/
390void Server_Impl_12::process_client_hello_msg(Server_Handshake_State& pending_state,
391 const std::vector<uint8_t>& contents,
392 bool epoch0_restart) {
393 BOTAN_ASSERT_IMPLICATION(epoch0_restart, active_state().has_value(), "Can't restart with a dead connection");
394
395 const bool initial_handshake = epoch0_restart || !active_state().has_value();
396
397 if(initial_handshake == false && policy().allow_client_initiated_renegotiation() == false) {
398 if(policy().abort_connection_on_undesired_renegotiation()) {
399 throw TLS_Exception(Alert::NoRenegotiation, "Server policy prohibits renegotiation");
400 } else {
401 send_warning_alert(Alert::NoRenegotiation);
402 }
403 return;
404 }
405
406 if(!policy().allow_insecure_renegotiation() && !(initial_handshake || secure_renegotiation_supported())) {
407 send_warning_alert(Alert::NoRenegotiation);
408 return;
409 }
410
411 if(pending_state.handshake_io().have_more_data()) {
412 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after ClientHello");
413 }
414
415 pending_state.client_hello(std::make_unique<Client_Hello_12>(contents));
416 const Protocol_Version client_offer = pending_state.client_hello()->legacy_version();
417 const bool datagram = client_offer.is_datagram_protocol();
418
419 if(datagram) {
420 if(client_offer.major_version() == 0xFF) {
421 throw TLS_Exception(Alert::ProtocolVersion, "Client offered DTLS version with major version 0xFF");
422 }
423 } else {
424 if(client_offer.major_version() < 3) {
425 throw TLS_Exception(Alert::ProtocolVersion, "Client offered TLS version with major version under 3");
426 }
427 if(client_offer.major_version() == 3 && client_offer.minor_version() == 0) {
428 throw TLS_Exception(Alert::ProtocolVersion, "Client offered SSLv3 which is not supported");
429 }
430 }
431
432 /*
433 * BoGo test suite expects that we will send the hello verify with a record
434 * version matching the version that is eventually negotiated. This is wrong
435 * but harmless, so go with it. Also doing the version negotiation step first
436 * allows to immediately close the connection with an alert if the client has
437 * offered a version that we are not going to negotiate anyway, instead of
438 * making them first do the cookie exchange and then telling them no.
439 *
440 * There is no issue with amplification here, since the alert is just 2 bytes.
441 */
442 const Protocol_Version negotiated_version =
443 select_version(policy(),
444 client_offer,
445 active_state().has_value() ? active_state()->version() : Protocol_Version(),
446 pending_state.client_hello()->supported_versions());
447
448 pending_state.set_version(negotiated_version);
449
450 const auto compression_methods = pending_state.client_hello()->compression_methods();
451 if(!value_exists(compression_methods, uint8_t(0))) {
452 throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
453 }
454
455 if(initial_handshake && datagram && policy().dtls_server_require_cookie_exchange()) {
456 // The cookie secret is read each time to allow for refreshing the key
457 const auto cookie_secret = load_dtls_cookie_secret(*m_creds);
458
459 const std::string client_identity = callbacks().tls_peer_network_identity();
460 if(client_identity.empty()) {
461 // RFC 9147 Section 11: the cookie MUST depend on the client's address
462 //
463 // Without an application-supplied identity the cookie is reusable from
464 // any source address, defeating the whole point of the cookie exchange.
465 //
466 // TODO(Botan4): Remove the version hint about the breaking change.
467 throw Invalid_State(
468 "Since Botan 3.13 DTLS server requires tls_peer_network_identity() return a non-empty value");
469 }
470 const Hello_Verify_Request verify(
471 pending_state.client_hello()->cookie_input_data(), client_identity, cookie_secret);
472
473 if(!CT::is_equal<uint8_t>(pending_state.client_hello()->cookie(), verify.cookie()).as_bool()) {
474 if(epoch0_restart) {
475 pending_state.handshake_io().send_under_epoch(verify, 0);
476 } else {
477 pending_state.handshake_io().send(verify);
478 }
479
480 pending_state.client_hello(nullptr);
481 pending_state.set_expected_next(Handshake_Type::ClientHello);
482 return;
483 }
484 }
485
486 if(epoch0_restart) {
487 // If we reached here then we were able to verify the cookie
489 }
490
491 secure_renegotiation_check(pending_state.client_hello());
492
493 // RFC 7627 / RFC 9325 4.4: optionally require Extended Master Secret
494 if(policy().require_extended_master_secret() && !pending_state.client_hello()->supports_extended_master_secret()) {
495 throw TLS_Exception(Alert::HandshakeFailure,
496 "Policy requires the Extended Master Secret extension but the client did not send it");
497 }
498
499 // RFC 7627 5.3 has an explicit MUST regarding EMS mismatch on resumption
500 //
501 // "If the original session used the 'extended_master_secret'
502 // extension but the new ClientHello does not contain it, the
503 // server MUST abort the abbreviated handshake."
504 //
505 // There is apparently no RFC requirement that a client must not drop EMS between the
506 // initial negotiation and a renegotiation... but there is also no RFC requirement
507 // that we must accept it. So we don't.
508 if(const auto& active = active_state()) {
509 const bool ems_pending = pending_state.client_hello()->supports_extended_master_secret();
510 if(active->supports_extended_master_secret() == true && ems_pending == false) {
511 throw TLS_Exception(Alert::HandshakeFailure,
512 "Renegotiation ClientHello dropped the Extended Master Secret extension");
513 }
514 }
515
517 pending_state.client_hello()->extensions(), Connection_Side::Client, Handshake_Type::ClientHello);
518
519 const auto session_handle = pending_state.client_hello()->session_handle();
520
521 std::optional<Session> session_info;
522 if(pending_state.allow_session_resumption() && session_handle.has_value()) {
523 session_info = check_for_resume(
524 session_handle.value(), session_manager(), callbacks(), policy(), pending_state.client_hello());
525 }
526
527 m_next_protocol = "";
528 if(pending_state.client_hello()->supports_alpn()) {
529 const auto offered = pending_state.client_hello()->next_protocols();
530 m_next_protocol = callbacks().tls_server_choose_app_protocol(offered);
531 // RFC 7301 3.2: if a protocol is selected, the server MUST select one
532 // of the protocols advertised by the client. An empty return signals
533 // "no ALPN" and is allowed.
534 if(!m_next_protocol.empty() && !value_exists(offered, m_next_protocol)) {
535 throw TLS_Exception(Alert::InternalError, "Application chose an ALPN protocol that the client did not offer");
536 }
537 }
538
539 if(session_info.has_value()) {
540 this->session_resume(pending_state, {session_info.value(), session_handle.value()});
541 } else {
542 // new session
543 this->session_create(pending_state);
544 }
545}
546
547void Server_Impl_12::process_certificate_msg(Server_Handshake_State& pending_state,
548 const std::vector<uint8_t>& contents) {
549 pending_state.client_certs(std::make_unique<Certificate_12>(contents, policy()));
550
551 // CERTIFICATE_REQUIRED would make more sense but BoGo expects handshake failure alert
552 if(pending_state.client_certs()->empty() && policy().require_client_certificate_authentication()) {
553 throw TLS_Exception(Alert::HandshakeFailure, "Policy requires client send a certificate, but it did not");
554 }
555
556 pending_state.set_expected_next(Handshake_Type::ClientKeyExchange);
557}
558
559void Server_Impl_12::process_client_key_exchange_msg(Server_Handshake_State& pending_state,
560 const std::vector<uint8_t>& contents) {
561 if(pending_state.received_handshake_msg(Handshake_Type::Certificate) && !pending_state.client_certs()->empty()) {
562 pending_state.set_expected_next(Handshake_Type::CertificateVerify);
563 } else {
564 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
565 }
566
567 pending_state.client_kex(std::make_unique<Client_Key_Exchange>(
568 contents, pending_state, pending_state.server_rsa_kex_key(), *m_creds, policy(), rng()));
569
570 pending_state.compute_session_keys();
571 if(policy().allow_ssl_key_log_file()) {
572 // draft-thomson-tls-keylogfile-00 Section 3.2
573 // An implementation of TLS 1.2 (and also earlier versions) use
574 // the label "CLIENT_RANDOM" to identify the "master" secret for
575 // the connection.
577 "CLIENT_RANDOM", pending_state.client_hello()->random(), pending_state.session_keys().master_secret());
578 }
579}
580
581void Server_Impl_12::process_change_cipher_spec_msg(Server_Handshake_State& pending_state) {
582 pending_state.set_expected_next(Handshake_Type::Finished);
584}
585
586void Server_Impl_12::process_certificate_verify_msg(Server_Handshake_State& pending_state,
587 Handshake_Type type,
588 const std::vector<uint8_t>& contents) {
589 pending_state.client_verify(std::make_unique<Certificate_Verify_12>(contents));
590
591 const std::vector<X509_Certificate>& client_certs = pending_state.client_certs()->cert_chain();
592
593 if(client_certs.empty()) {
594 throw TLS_Exception(Alert::DecodeError, "No client certificate sent");
595 }
596
597 const auto cert_constraints = client_certs[0].constraints();
598 if(!cert_constraints.empty()) {
599 if(!cert_constraints.includes_any(Key_Constraints::DigitalSignature, Key_Constraints::NonRepudiation)) {
600 throw TLS_Exception(Alert::BadCertificate, "Client certificate does not support signing");
601 }
602 }
603
604 const bool sig_valid = pending_state.client_verify()->verify(client_certs[0], pending_state, policy());
605
606 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
607
608 /*
609 * Using DECRYPT_ERROR looks weird here, but per RFC 4346 is for
610 * "A handshake cryptographic operation failed, including being
611 * unable to correctly verify a signature, ..."
612 */
613 if(!sig_valid) {
614 throw TLS_Exception(Alert::DecryptError, "Client cert verify failed");
615 }
616
617 try {
618 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
619 auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-server", sni_hostname);
620
621 callbacks().tls_verify_cert_chain(client_certs,
622 {}, // ocsp
623 trusted_CAs,
625 sni_hostname,
626 policy());
627 } catch(std::exception& e) {
628 throw TLS_Exception(Alert::BadCertificate, e.what());
629 }
630
631 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
632}
633
634void Server_Impl_12::process_finished_msg(Server_Handshake_State& pending_state,
635 Handshake_Type type,
636 const std::vector<uint8_t>& contents) {
637 pending_state.set_expected_next(Handshake_Type::None);
638
639 if(pending_state.handshake_io().have_more_data()) {
640 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after Finished");
641 }
642
643 pending_state.client_finished(std::make_unique<Finished_12>(contents));
644
645 if(!pending_state.client_finished()->verify(pending_state, Connection_Side::Client)) {
646 throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify");
647 }
648
649 if(pending_state.server_finished() == nullptr) {
650 // already sent finished if resuming, so this is a new session
651
652 pending_state.hash().update(pending_state.handshake_io().format(contents, type));
653
654 Session session_info(pending_state.session_keys().master_secret(),
655 pending_state.server_hello()->legacy_version(),
656 pending_state.server_hello()->ciphersuite(),
658 pending_state.server_hello()->supports_extended_master_secret(),
659 pending_state.server_hello()->supports_encrypt_then_mac(),
660 pending_state.peer_cert_chain(),
661 Server_Information(pending_state.client_hello()->sni_hostname()),
662 pending_state.server_hello()->srtp_profile(),
663 callbacks().tls_current_timestamp());
664
665 // Give the application a chance for a final veto before fully
666 // establishing the connection.
668 Session_Summary summary(session_info, pending_state.is_a_resumption(), pending_state.psk_identity());
669 summary.set_session_id(pending_state.server_hello()->session_id());
670 return summary;
671 }());
672
673 if(callbacks().tls_should_persist_resumption_information(session_info)) {
674 auto handle = session_manager().establish(session_info,
675 pending_state.server_hello()->session_id(),
676 !pending_state.server_hello()->supports_session_ticket());
677
678 if(pending_state.server_hello()->supports_session_ticket() && handle.has_value() && handle->is_ticket()) {
679 pending_state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(
680 pending_state.handshake_io(),
681 pending_state.hash(),
682 handle->ticket().value(),
683 static_cast<uint32_t>(policy().session_ticket_lifetime().count())));
684 }
685
687 }
688
689 if(pending_state.new_session_ticket() == nullptr && pending_state.server_hello()->supports_session_ticket()) {
690 pending_state.new_session_ticket(
691 std::make_unique<New_Session_Ticket_12>(pending_state.handshake_io(), pending_state.hash()));
692 }
693
694 pending_state.handshake_io().send(Change_Cipher_Spec());
695
697
698 pending_state.server_finished(
699 std::make_unique<Finished_12>(pending_state.handshake_io(), pending_state, Connection_Side::Server));
700 }
701
703}
704
705/*
706* Process a handshake message
707*/
708void Server_Impl_12::process_handshake_msg(Handshake_State& state_base,
709 Handshake_Type type,
710 const std::vector<uint8_t>& contents,
711 bool epoch0_restart) {
712 Server_Handshake_State& state = dynamic_cast<Server_Handshake_State&>(state_base);
713 state.confirm_transition_to(type);
714
715 /*
716 * The change cipher spec message isn't technically a handshake
717 * message so it's not included in the hash. The finished and
718 * certificate verify messages are verified based on the current
719 * state of the hash *before* this message so we delay adding them
720 * to the hash computation until we've processed them below.
721 */
724 state.hash().update(state.handshake_io().format(contents, type));
725 }
726
727 switch(type) {
729 return this->process_client_hello_msg(state, contents, epoch0_restart);
730
732 return this->process_certificate_msg(state, contents);
733
735 return this->process_client_key_exchange_msg(state, contents);
736
738 return this->process_certificate_verify_msg(state, type, contents);
739
741 return this->process_change_cipher_spec_msg(state);
742
744 return this->process_finished_msg(state, type, contents);
745
746 default:
747 throw Unexpected_Message("Unknown handshake message received");
748 }
749}
750
751void Server_Impl_12::session_resume(Server_Handshake_State& pending_state, const Session_with_Handle& session) {
752 // Only offer a resuming client a new ticket if they didn't send one this time,
753 // ie, resumed via server-side resumption. TODO: also send one if expiring soon?
754
755 const bool offer_new_session_ticket = pending_state.client_hello()->supports_session_ticket() &&
756 pending_state.client_hello()->session_ticket().empty() &&
758
759 pending_state.server_hello(std::make_unique<Server_Hello_12>(pending_state.handshake_io(),
760 pending_state.hash(),
761 policy(),
762 callbacks(),
763 rng(),
765 *pending_state.client_hello(),
766 session.session,
767 offer_new_session_ticket,
768 m_next_protocol));
769
770 secure_renegotiation_check(pending_state.server_hello());
771
772 pending_state.mark_as_resumption();
773 pending_state.compute_session_keys(session.session.master_secret());
774 if(policy().allow_ssl_key_log_file()) {
775 // draft-thomson-tls-keylogfile-00 Section 3.2
776 // An implementation of TLS 1.2 (and also earlier versions) use
777 // the label "CLIENT_RANDOM" to identify the "master" secret for
778 // the connection.
780 "CLIENT_RANDOM", pending_state.client_hello()->random(), pending_state.session_keys().master_secret());
781 }
782 pending_state.set_resume_certs(session.session.peer_certs());
783
784 // Give the application a chance for a final veto before fully
785 // establishing the connection.
787 Session_Summary summary(session.session, pending_state.is_a_resumption(), external_psk_identity());
788 summary.set_session_id(pending_state.server_hello()->session_id());
789 if(auto ticket = session.handle.ticket()) {
790 summary.set_session_ticket(std::move(ticket.value()));
791 }
792 return summary;
793 }());
794
795 auto new_handle = [&, this]() -> std::optional<Session_Handle> {
796 if(!callbacks().tls_should_persist_resumption_information(session.session)) {
797 session_manager().remove(session.handle);
798 return std::nullopt;
799 } else {
800 return session_manager().establish(session.session, session.handle.id());
801 }
802 }();
803
804 note_resumption_handle(new_handle);
805
806 if(pending_state.server_hello()->supports_session_ticket()) {
807 if(new_handle.has_value() && new_handle->is_ticket()) {
808 const uint32_t lifetime = static_cast<uint32_t>(policy().session_ticket_lifetime().count());
809 pending_state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(
810 pending_state.handshake_io(), pending_state.hash(), new_handle->ticket().value(), lifetime));
811 } else {
812 pending_state.new_session_ticket(
813 std::make_unique<New_Session_Ticket_12>(pending_state.handshake_io(), pending_state.hash()));
814 }
815 }
816
817 pending_state.handshake_io().send(Change_Cipher_Spec());
818
820
821 pending_state.server_finished(
822 std::make_unique<Finished_12>(pending_state.handshake_io(), pending_state, Connection_Side::Server));
823 pending_state.set_expected_next(Handshake_Type::HandshakeCCS);
824}
825
826void Server_Impl_12::session_create(Server_Handshake_State& pending_state) {
827 std::map<std::string, std::vector<X509_Certificate>> cert_chains;
828
829 const std::string sni_hostname = pending_state.client_hello()->sni_hostname();
830
831 // RFC 8446 1.3
832 // The "signature_algorithms_cert" extension allows a client to indicate
833 // which signature algorithms it can validate in X.509 certificates.
834 //
835 // RFC 8446 4.2.3
836 // TLS 1.2 implementations SHOULD also process this extension.
837 const auto cert_signature_schemes = pending_state.client_hello()->certificate_signature_schemes();
838 cert_chains = get_server_certs(sni_hostname, cert_signature_schemes, *m_creds);
839
840 if(!sni_hostname.empty() && cert_chains.empty()) {
841 cert_chains = get_server_certs("", cert_signature_schemes, *m_creds);
842
843 /*
844 * Only send the unrecognized_name alert if we couldn't
845 * find any certs for the requested name but did find at
846 * least one cert to use in general. That avoids sending an
847 * unrecognized_name when a server is configured for purely
848 * anonymous/PSK operation.
849 */
850 if(!cert_chains.empty()) {
851 send_warning_alert(Alert::UnrecognizedName);
852 }
853 }
854
855 const uint16_t ciphersuite =
856 choose_ciphersuite(policy(), pending_state.version(), cert_chains, *pending_state.client_hello());
857
858 const Server_Hello_12::Settings srv_settings(Session_ID(make_hello_random(rng(), callbacks(), policy())),
859 pending_state.version(),
860 ciphersuite,
861 session_manager().emits_session_tickets());
862
863 pending_state.server_hello(std::make_unique<Server_Hello_12>(pending_state.handshake_io(),
864 pending_state.hash(),
865 policy(),
866 callbacks(),
867 rng(),
869 *pending_state.client_hello(),
870 srv_settings,
871 m_next_protocol));
872
873 secure_renegotiation_check(pending_state.server_hello());
874
875 const Ciphersuite& pending_suite = pending_state.ciphersuite();
876
877 std::shared_ptr<Private_Key> private_key;
878
879 if(pending_suite.is_certificate_required()) {
880 const std::string algo_used = pending_suite.signature_used() ? pending_suite.sig_algo() : "RSA";
881
882 BOTAN_ASSERT(!cert_chains[algo_used].empty(), "Attempting to send empty certificate chain");
883
884 pending_state.server_certs(
885 std::make_unique<Certificate_12>(pending_state.handshake_io(), pending_state.hash(), cert_chains[algo_used]));
886
887 if(pending_state.client_hello()->supports_cert_status_message() && pending_state.is_a_resumption() == false) {
888 auto* csr = pending_state.client_hello()->extensions().get<Certificate_Status_Request>();
889 // csr is non-null if client_hello()->supports_cert_status_message()
890 BOTAN_ASSERT_NOMSG(csr != nullptr);
891 const auto resp_bytes = callbacks().tls_provide_cert_status(cert_chains[algo_used], *csr);
892 if(!resp_bytes.empty()) {
893 pending_state.server_cert_status(
894 std::make_unique<Certificate_Status_12>(pending_state.handshake_io(), pending_state.hash(), resp_bytes));
895 }
896 }
897
898 private_key = m_creds->private_key_for(pending_state.server_certs()->cert_chain()[0], "tls-server", sni_hostname);
899
900 if(!private_key) {
901 throw Internal_Error("No private key located for associated server cert");
902 }
903 }
904
905 if(pending_suite.kex_method() == Kex_Algo::STATIC_RSA) {
906 pending_state.set_server_rsa_kex_key(private_key);
907 } else {
908 pending_state.server_kex(std::make_unique<Server_Key_Exchange>(
909 pending_state.handshake_io(), pending_state, policy(), *m_creds, rng(), private_key.get()));
910 }
911
912 auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-server", sni_hostname);
913
914 std::vector<X509_DN> client_auth_CAs;
915
916 for(auto* store : trusted_CAs) {
917 auto subjects = store->all_subjects();
918 client_auth_CAs.insert(client_auth_CAs.end(), subjects.begin(), subjects.end());
919 }
920
921 const bool request_cert = (client_auth_CAs.empty() == false) || policy().request_client_certificate_authentication();
922
923 // RFC 5246 7.4.4: supported_signature_algorithms<2..2^16-2>
924 // Without at least one acceptable scheme we cannot construct a valid
925 // CertificateRequest, so client cert auth is unreachable regardless.
926 const bool can_request_cert = !policy().acceptable_signature_schemes().empty();
927
928 if(request_cert && can_request_cert && pending_state.ciphersuite().is_certificate_required()) {
929 pending_state.cert_req(std::make_unique<Certificate_Request_12>(
930 pending_state.handshake_io(), pending_state.hash(), policy(), client_auth_CAs));
931
932 /*
933 SSLv3 allowed clients to skip the Certificate message entirely
934 if they wanted. In TLS v1.0 and later clients must send a
935 (possibly empty) Certificate message
936 */
937 pending_state.set_expected_next(Handshake_Type::Certificate);
938 } else {
939 pending_state.set_expected_next(Handshake_Type::ClientKeyExchange);
940 }
941
942 pending_state.server_hello_done(
943 std::make_unique<Server_Hello_Done>(pending_state.handshake_io(), pending_state.hash()));
944}
945} // 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 note_resumption_handle(std::optional< Session_Handle > handle)
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
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128