Botan 3.14.1
Crypto and TLS for C&
tls_server_impl_13.cpp
Go to the documentation of this file.
1/*
2* TLS Server - implementation for TLS 1.3
3* (C) 2022 Jack Lloyd
4* 2022 René Meusel - Rohde & Schwarz Cybersecurity
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/tls_server_impl_13.h>
10
11#include <botan/credentials_manager.h>
12#include <botan/rng.h>
13#include <botan/tls_callbacks.h>
14#include <botan/tls_extensions_13.h>
15#include <botan/tls_policy.h>
16#include <botan/x509cert.h>
17#include <botan/internal/loadstor.h>
18#include <botan/internal/stl_util.h>
19#include <botan/internal/tls_cipher_state.h>
20
21namespace Botan::TLS {
22
23std::shared_ptr<Server_Impl_13> Server_Impl_13::create(const std::shared_ptr<Callbacks>& callbacks,
24 const std::shared_ptr<Session_Manager>& session_manager,
25 const std::shared_ptr<Credentials_Manager>& credentials_manager,
26 const std::shared_ptr<const Policy>& policy,
27 const std::shared_ptr<RandomNumberGenerator>& rng) {
28 auto self =
29 std::make_shared<Server_Impl_13>(Private{}, callbacks, session_manager, credentials_manager, policy, rng);
30
31#if defined(BOTAN_HAS_TLS_12)
32 if(policy->allow_tls12()) {
33 self->expect_downgrade({}, {});
34 }
35#endif
36
37 self->m_handshake->transitions.set_expected_next(Handshake_Type::ClientHello);
38
39 return self;
40}
41
43 if(m_active_state.has_value()) {
44 return m_active_state->application_protocol();
45 }
46
47 return "";
48}
49
50std::vector<X509_Certificate> Server_Impl_13::peer_cert_chain() const {
51 if(m_active_state.has_value()) {
52 return m_active_state->peer_certs();
53 }
54
55 if(m_handshake) {
56 if(m_handshake->state.has_client_certificate_msg() &&
57 m_handshake->state.client_certificate().has_certificate_chain()) {
58 return m_handshake->state.client_certificate().cert_chain();
59 }
60
61 if(m_handshake->resumed_session.has_value()) {
62 return m_handshake->resumed_session->peer_certs();
63 }
64 }
65
66 return {};
67}
68
69std::shared_ptr<const Public_Key> Server_Impl_13::peer_raw_public_key() const {
70 if(m_active_state.has_value()) {
71 return m_active_state->peer_raw_public_key();
72 }
73
74 if(m_handshake) {
75 if(m_handshake->state.has_client_certificate_msg() &&
76 m_handshake->state.client_certificate().is_raw_public_key()) {
77 return m_handshake->state.client_certificate().public_key();
78 }
79
80 if(m_handshake->resumed_session.has_value()) {
81 return m_handshake->resumed_session->peer_raw_public_key();
82 }
83 }
84
85 return nullptr;
86}
87
88std::optional<std::string> Server_Impl_13::external_psk_identity() const {
89 if(m_active_state.has_value()) {
90 return m_active_state->psk_identity();
91 } else if(m_handshake) {
92 return m_handshake->psk_identity;
93 } else {
94 return std::nullopt;
95 }
96}
97
99 // RFC 8446 4.2.9
100 // This extension also restricts the modes for use with PSK resumption.
101 // Servers SHOULD NOT send NewSessionTicket with tickets that are not
102 // compatible with the advertised modes; however, if a server does so,
103 // the impact will just be that the client's attempts at resumption fail.
104 //
105 // Note: Applications can overrule this by calling send_new_session_tickets()
106 // regardless of this method indicating no support for tickets.
107 //
108 // TODO: Implement other PSK KE modes than PSK_DHE_KE
109 return is_handshake_complete() && m_active_state.has_value() && m_active_state->peer_supports_psk_dhe_ke();
110}
111
112size_t Server_Impl_13::send_new_session_tickets(const size_t tickets) {
115
116 if(tickets == 0) {
117 return 0;
118 }
119
120 auto flight = PostHandshakeFlight(callbacks());
121 size_t tickets_created = 0;
122
124
125 // RFC 8446 4.6.1
126 // Servers MUST NOT use any value greater than 604800 seconds (7 days).
127 //
128 // A policy lifetime of 0 (no expiry) is capped the same way.
129 const std::chrono::seconds max_ticket_lifetime(604800);
130 const auto policy_lifetime = policy().session_ticket_lifetime();
131 const auto ticket_lifetime =
132 (policy_lifetime.count() <= 0 || policy_lifetime > max_ticket_lifetime) ? max_ticket_lifetime : policy_lifetime;
133
134 for(size_t i = 0; i < tickets; ++i) {
135 auto nonce = m_cipher_state->next_ticket_nonce();
136 const uint32_t ticket_age_add = load_be(rng().random_array<4>());
137 const Session session(m_cipher_state->psk(nonce),
138 std::nullopt, // early data not yet implemented
139 ticket_age_add,
140 ticket_lifetime,
141 m_active_state->version(),
142 m_active_state->ciphersuite_code(),
146 Server_Information(m_active_state->sni_hostname()),
147 callbacks().tls_current_timestamp());
148
149 if(callbacks().tls_should_persist_resumption_information(session)) {
150 if(auto handle = session_manager().establish(session)) {
151 flight.add(New_Session_Ticket_13(std::move(nonce), session, handle.value(), callbacks()));
152 ++tickets_created;
153 }
154 }
155 }
156
157 if(tickets_created > 0) {
158 send_flight(flight.commit());
159 }
160
161 return tickets_created;
162}
163
164void Server_Impl_13::process_handshake_msg(Handshake_Message_13 message) {
165 BOTAN_STATE_CHECK(m_handshake != nullptr);
166
167 // first verify that the message was expected by the state machine
168 // (and only then store it in the handshake state)
169 m_handshake->transitions.confirm_transition_to(std::visit([](const auto& msg) { return msg.type(); }, message));
170
171 std::visit(
172 [&](auto msg) {
173 // ... then allow the library user to abort on their discretion
175
176 // ... finally handle the message
177 handle(msg.get());
178 },
179 m_handshake->state.received(std::move(message)));
180}
181
182void Server_Impl_13::process_post_handshake_msg(Post_Handshake_Message_13 message) {
184
185 const auto msg = specialize_to<Client_Post_Handshake_13_Message>(std::move(message));
186 if(!msg) {
187 throw TLS_Exception(Alert::UnexpectedMessage, "Received an unexpected post-handshake message");
188 }
189
190 std::visit(
191 [&](auto&& m) {
193 handle(m);
194 },
195 *msg);
196}
197
199 // RFC 8446 5.
200 // If an implementation detects a change_cipher_spec record received before
201 // the first ClientHello message or after the peer's Finished message, it MUST be
202 // treated as an unexpected record type [("unexpected_message" alert)].
203 if(!m_handshake || !m_handshake->state.has_client_hello() || m_handshake->state.has_client_finished()) {
204 throw TLS_Exception(Alert::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec");
205 }
206
207 // RFC 8446 5.
208 // An implementation may receive an unencrypted record of type change_cipher_spec [...]
209 // at any time after the first ClientHello message has been sent or received
210 // and before the peer's Finished message has been received [...]
211 // and MUST simply drop it without further processing.
212 //
213 // ... no further processing.
214}
215
217 // A handshake that was aborted after the client's Finished is not complete
218 return m_active_state.has_value() ||
219 (m_handshake != nullptr && m_handshake->state.handshake_finished() && !is_closed());
220}
221
222void Server_Impl_13::maybe_log_secret(std::string_view label, std::span<const uint8_t> secret) const {
223 if(policy().allow_ssl_key_log_file()) {
224 if(m_active_state.has_value()) {
225 callbacks().tls_ssl_key_log_data(label, m_active_state->client_random(), secret);
226 } else {
227 callbacks().tls_ssl_key_log_data(label, m_handshake->state.client_hello().random(), secret);
228 }
229 }
230}
231
232#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
233
234void Server_Impl_13::downgrade() {
236
237 request_downgrade();
238
239 // After this, no further messages are expected here because this instance
240 // will be replaced by a Server_Impl_12.
241 m_handshake->transitions.set_expected_next({});
242}
243
244#endif
245
247 // RFC 9846 E.4
248 // This "compatibility mode" is partially negotiated: the client can opt
249 // to provide a session ID or not, [...].
250 //
251 // I.e., before we received a ClientHello, we cannot know whether the client
252 // requested middlebox compatibility mode or not.
253 if(m_handshake == nullptr || !m_handshake->state.has_client_hello()) {
254 return false;
255 }
256
257 // RFC 9846 E.4
258 // This "compatibility mode" is partially negotiated: the client can opt
259 // to provide a session ID or not, and the server has to echo it. Either
260 // side can send change_cipher_spec at any time during the handshake, as
261 // they must be ignored by the peer, but if the client sends a non-empty
262 // session ID, the server MUST send the change_cipher_spec as described
263 // [above].
264 //
265 // Technically, the usage of compatibility mode is fully up to the client
266 // sending a non-empty session ID. Nevertheless, when the policy requests
267 // it we send a CCS regardless. Note that this is perfectly legal and also
268 // satisfies some BoGo tests that expect this behaviour.
269 const bool client_requested_compatibility_mode = !m_handshake->state.client_hello().session_id().empty();
270
271 return policy().tls_13_middlebox_compatibility_mode() || client_requested_compatibility_mode;
272}
273
274void Server_Impl_13::handle_reply_to_client_hello(Server_Hello_13 server_hello) {
275 const auto& client_hello = m_handshake->state.client_hello();
276 const auto& exts = client_hello.extensions();
277
278 bool uses_psk = server_hello.extensions().has<PSK>();
279
280 const auto cipher_opt = Ciphersuite::by_id(server_hello.ciphersuite());
281 BOTAN_ASSERT_NOMSG(cipher_opt.has_value());
282 const auto& cipher = cipher_opt.value();
284 m_transcript_hash->set_algorithm(cipher.prf_algo());
285
286 std::unique_ptr<Cipher_State> psk_cipher_state;
287 if(uses_psk) {
288 auto* psk_extension = server_hello.extensions().get<PSK>();
289
290 psk_cipher_state = std::visit(
292 [&, this](Session session) {
293 m_handshake->resumed_session = std::move(session);
297 m_handshake->resumed_session->extract_master_secret(),
298 cipher.prf_algo());
299 },
300 [&, this](ExternalPSK psk) {
301 m_handshake->psk_identity = psk.identity();
302 const auto psk_type =
305 Connection_Side::Server, TLS_Flavor::TLS, psk_type, psk.extract_master_secret(), cipher.prf_algo());
306 },
307 },
308 psk_extension->take_session_to_resume_or_psk());
309 psk_cipher_state->set_secret_logger(secret_logger());
310
311 // RFC 8446 4.2.11
312 // Prior to accepting PSK key establishment, the server MUST validate
313 // the corresponding binder value (see Section 4.2.11.2 below). If this
314 // value is not present or does not validate, the server MUST abort the
315 // handshake.
316 // Servers SHOULD NOT attempt to validate multiple binders; rather,
317 // they SHOULD select a single PSK and validate solely the binder that
318 // corresponds to that PSK.
319 //
320 // Note: PSK selection was performed earlier, resulting in the existence
321 // of this extension in the first place.
322 if(!exts.get<PSK>()->validate_binder(*psk_extension,
323 psk_cipher_state->psk_binder_mac(m_transcript_hash->truncated()))) {
324 throw TLS_Exception(Alert::DecryptError, "PSK binder does not check out");
325 }
326
327 // RFC 8446 4.3.2
328 // Servers which are authenticating with a PSK MUST NOT send the
329 // CertificateRequest message in the main handshake
330 //
331 // A resumed session that does not satisfy the current client authentication
332 // policy is declined in favor of a full handshake. Checked only after binder
333 // validation, so an unauthenticated peer cannot probe for policy details.
334 if(m_handshake->resumed_session.has_value() && policy().require_client_certificate_authentication()) {
335 const auto credential_type = m_handshake->resumed_session->peer_credential_type();
336
337 if(!credential_type.has_value() ||
338 !value_exists(policy().accepted_client_certificate_types(), credential_type.value())) {
339 m_handshake->resumed_session.reset();
340 psk_cipher_state.reset();
341 server_hello.decline_psk();
342 uses_psk = false;
343 }
344 }
345
346 // RFC 8446 4.2.10
347 // For PSKs provisioned via NewSessionTicket, a server MUST validate
348 // that the ticket age for the selected PSK identity [...] is within a
349 // small tolerance of the time since the ticket was issued. If it is
350 // not, the server SHOULD proceed with the handshake but reject 0-RTT,
351 // and SHOULD NOT take any other action that assumes that this
352 // ClientHello is fresh.
353 //
354 // TODO: When implementing Early Data (0-RTT) we should take the above
355 // paragraph into account. Note that there are BoGo tests that
356 // validate this behaviour. Namely: TLS13-TicketAgeSkew-*
357 }
358
359 // This sends the server_hello to the peer.
360 // NOTE: the server_hello variable is moved into the handshake state. Later
361 // references to the Server Hello will need to consult the handshake
362 // state object!
363 auto server_hello_flight = Flight(*m_transcript_hash, callbacks()) //
364 .add(m_handshake->state.sending(std::move(server_hello)));
365
366 // RFC 9846 E.4
367 // The server sends a dummy change_cipher_spec record immediately after
368 // its first handshake message. This may either be after a ServerHello or
369 // a HelloRetryRequest.
370 if(compat_mode_ccs_requested() && !m_handshake->state.has_hello_retry_request()) {
371 server_hello_flight.add_dummy_change_cipher_spec();
372 }
373
374 send_flight(server_hello_flight.commit());
375
376 // Setup encryption for all the remaining handshake messages
378 // Currently, PSK without DHE is not implemented...
379 auto* const my_keyshare = m_handshake->state.server_hello().extensions().get<Key_Share>();
380 BOTAN_ASSERT_NONNULL(my_keyshare);
381
382 if(uses_psk) {
383 BOTAN_ASSERT_NONNULL(psk_cipher_state);
384 psk_cipher_state->advance_with_client_hello(m_transcript_hash->previous());
385 psk_cipher_state->advance_with_server_hello(
386 cipher, my_keyshare->take_shared_secret(), m_transcript_hash->current());
387
388 return std::move(psk_cipher_state);
389 } else {
392 my_keyshare->take_shared_secret(),
393 cipher,
394 m_transcript_hash->current(),
395 secret_logger());
396 }
397 }());
398
399 // Decide up front whether we will request client authentication so the
400 // EncryptedExtensions can attach client_certificate_type when applicable
401 // (RFC 7250 4.2 requires the two messages to agree).
402 auto certificate_request =
403 uses_psk ? std::nullopt
405
406 const bool is_resumption = m_handshake->resumed_session.has_value();
407 const bool requesting_client_auth = certificate_request.has_value();
408 auto flight = Flight(*m_transcript_hash, callbacks())
409 .add(m_handshake->state.sending(Encrypted_Extensions(
410 client_hello, policy(), callbacks(), is_resumption, requesting_client_auth)));
411
412 if(!uses_psk) {
413 // RFC 8446 4.3.2
414 // A server which is authenticating with a certificate MAY optionally
415 // request a certificate from the client. This message, if sent, MUST
416 // follow EncryptedExtensions.
417 if(certificate_request.has_value()) {
418 flight.add(m_handshake->state.sending(std::move(certificate_request.value())));
419 }
420
421 const auto& enc_exts = m_handshake->state.encrypted_extensions().extensions();
422
423 // RFC 7250 4.2
424 // This client_certificate_type extension in the server hello then
425 // indicates the type of certificates the client is requested to provide
426 // in a subsequent certificate payload.
427 //
428 // Note: TLS 1.3 carries this extension in the Encrypted Extensions
429 // message instead of the Server Hello.
430 if(const auto* client_cert_type = enc_exts.get<Client_Certificate_Type>()) {
431 set_selected_certificate_type(client_cert_type->selected_certificate_type());
432 }
433
434 // RFC 8446 4.4.2
435 // If the corresponding certificate type extension [...] was not
436 // negotiated in EncryptedExtensions, or the X.509 certificate type
437 // was negotiated, then each CertificateEntry contains a DER-encoded
438 // X.509 certificate.
439 const auto cert_type = [&] {
440 if(const auto* server_cert_type = enc_exts.get<Server_Certificate_Type>()) {
441 return server_cert_type->selected_certificate_type();
442 } else {
444 }
445 }();
446
447 if(!value_exists(policy().accepted_server_certificate_types(), cert_type)) {
448 throw TLS_Exception(Alert::UnsupportedCertificate,
449 "Client does not support a certificate type that our policy allows");
450 }
451
452 flight
453 .add(m_handshake->state.sending(Certificate_13(client_hello, credentials_manager(), callbacks(), cert_type)))
454 .add(m_handshake->state.sending(Certificate_Verify_13(m_handshake->state.server_certificate(),
455 client_hello.signature_schemes(),
456 client_hello.sni_hostname(),
457 m_transcript_hash->current(),
460 policy(),
461 callbacks(),
462 rng())));
463 }
464
465 flight.add(m_handshake->state.sending(Finished_13(m_cipher_state.get(), m_transcript_hash->current())));
466
467 if(client_hello.extensions().has<Record_Size_Limit>() &&
468 m_handshake->state.encrypted_extensions().extensions().has<Record_Size_Limit>()) {
469 // RFC 8449 4.
470 // When the "record_size_limit" extension is negotiated, an endpoint
471 // MUST NOT generate a protected record with plaintext that is larger
472 // than the RecordSizeLimit value it receives from its peer.
473 // Unprotected messages are not subject to this limit.
474 //
475 // Hence, the limit is set just before we start sending encrypted records.
476 //
477 // RFC 8449 4.
478 // The record size limit only applies to records sent toward the
479 // endpoint that advertises the limit. An endpoint can send records
480 // that are larger than the limit it advertises as its own limit.
481 //
482 // Hence, the "outgoing" limit is what the client requested and the
483 // "incoming" limit is what we will request in the Encrypted Extensions.
484 const auto* const outgoing_limit = client_hello.extensions().get<Record_Size_Limit>();
485 const auto* const incoming_limit =
486 m_handshake->state.encrypted_extensions().extensions().get<Record_Size_Limit>();
487 set_record_size_limits(outgoing_limit->limit(), incoming_limit->limit());
488 }
489
490 send_flight(flight.commit());
491
492 m_cipher_state->advance_with_server_finished(m_transcript_hash->current());
493
494 if(m_handshake->state.has_certificate_request()) {
495 // RFC 8446 4.4.2
496 // The client MUST send a Certificate message if and only if the server
497 // has requested client authentication via a CertificateRequest message
498 // [...]. If the server requests client authentication but no
499 // suitable certificate is available, the client MUST send a Certificate
500 // message containing no certificates [...].
501 m_handshake->transitions.set_expected_next(Handshake_Type::Certificate);
502 } else {
503 m_handshake->transitions.set_expected_next(Handshake_Type::Finished);
504 }
505}
506
507void Server_Impl_13::handle_reply_to_client_hello(Hello_Retry_Request hello_retry_request) {
509
510 auto cipher = Ciphersuite::by_id(hello_retry_request.ciphersuite());
511 BOTAN_ASSERT_NOMSG(cipher.has_value()); // should work, since we chose that suite
512
513 auto flight = Flight(*m_transcript_hash, callbacks()) //
514 .add(m_handshake->state.sending(std::move(hello_retry_request)));
515
516 // RFC 9846 E.4
517 // The server sends a dummy change_cipher_spec record immediately after
518 // its first handshake message. This may either be after a ServerHello or
519 // a HelloRetryRequest.
521 flight.add_dummy_change_cipher_spec();
522 }
523
524 send_flight(flight.commit());
525
528
529 m_handshake->transitions.set_expected_next(Handshake_Type::ClientHello);
530}
531
532void Server_Impl_13::handle(const Client_Hello_12_Shim& ch) {
533 // The detailed handling of the TLS 1.2 compliant Client Hello is left to
534 // the TLS 1.2 server implementation.
535 BOTAN_UNUSED(ch);
536 BOTAN_ASSERT_NONNULL(m_handshake);
537
538 // After we sent a Hello Retry Request we must not accept a downgrade.
539 if(m_handshake->state.has_hello_retry_request()) {
540 throw TLS_Exception(Alert::UnexpectedMessage, "Received a TLS 1.2 Client Hello after Hello Retry Request");
541 }
542
543#if !defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
544 throw TLS_Exception(Alert::ProtocolVersion, "Received an unsupported Client Hello");
545#else
546
547 // RFC 8446 Appendix D.2
548 // If the "supported_versions" extension is absent and the server only
549 // supports versions greater than ClientHello.legacy_version, the server
550 // MUST abort the handshake with a "protocol_version" alert.
551 //
552 // If we're not expecting a downgrade, we only support TLS 1.3.
553 if(!expects_downgrade()) {
554 throw TLS_Exception(Alert::ProtocolVersion, "Received a legacy Client Hello");
555 }
556
557 downgrade();
558#endif
559}
560
561void Server_Impl_13::handle(const Client_Hello_13& client_hello) {
562 BOTAN_ASSERT_NONNULL(m_handshake);
563
564 const auto& exts = client_hello.extensions();
565
566 const bool is_initial_client_hello = !m_handshake->state.has_hello_retry_request();
567
568 if(is_initial_client_hello) {
569 const auto preferred_version = client_hello.highest_supported_version(policy());
570 if(!preferred_version) {
571 throw TLS_Exception(Alert::ProtocolVersion, "No shared TLS version");
572 }
573
574 // RFC 8446 4.2.2
575 // Clients MUST NOT use cookies in their initial ClientHello in subsequent
576 // connections.
577 if(exts.has<Cookie>()) {
578 throw TLS_Exception(Alert::IllegalParameter, "Received a Cookie in the initial client hello");
579 }
580 }
581
582 // TODO: Implement support for PSK. For now, we ignore any such extensions
583 // and always revert to a standard key exchange.
584 if(!exts.has<Supported_Groups>()) {
585 // RFC 8446 4.2.9
586 // psk_dhe_ke: PSK with (EC)DHE key establishment. In this mode, the
587 // client and server MUST supply "key_share" values as described in
588 // Section 4.2.8.
589 const auto* psk_modes = exts.get<PSK_Key_Exchange_Modes>();
590 if(psk_modes != nullptr && value_exists(psk_modes->modes(), PSK_Key_Exchange_Mode::PSK_DHE_KE)) {
591 throw TLS_Exception(Alert::MissingExtension, "Client offered psk_dhe_ke without a key_share");
592 }
593 throw TLS_Exception(Alert::HandshakeFailure, "PSK-only key exchange is not supported");
594 }
595
596 // RFC 8446 9.2
597 // If containing a "supported_groups" extension, [Client Hello] MUST
598 // also contain a "key_share" extension, and vice versa.
599 //
600 // This was validated before in the Client_Hello_13 constructor.
601 BOTAN_ASSERT_NOMSG(exts.has<Key_Share>());
602
603 if(!is_initial_client_hello) {
604 const auto& hrr_exts = m_handshake->state.hello_retry_request().extensions();
605 const auto offered_groups = exts.get<Key_Share>()->offered_groups();
606 const auto* hrr_key_share = hrr_exts.get<Key_Share>();
607 BOTAN_ASSERT_NONNULL(hrr_key_share);
608 const auto selected_group = hrr_key_share->selected_group();
609 if(offered_groups.size() != 1 || offered_groups.at(0) != selected_group) {
610 throw TLS_Exception(Alert::IllegalParameter, "Client did not comply with the requested key exchange group");
611 }
612
613 // RFC 9846 4.3.2
614 // When sending the new ClientHello, the client MUST copy the contents
615 // of the extension received in the HelloRetryRequest into a "cookie"
616 // extension in the new ClientHello.
617 const auto* hrr_cookie = hrr_exts.get<Cookie>();
618 const auto* client_cookie = exts.get<Cookie>();
619 if((hrr_cookie == nullptr) != (client_cookie == nullptr) ||
620 (hrr_cookie != nullptr && hrr_cookie->get_cookie() != client_cookie->get_cookie())) {
621 throw TLS_Exception(Alert::IllegalParameter, "Client did not echo the cookie of the HelloRetryRequest");
622 }
623 }
624
625 callbacks().tls_examine_extensions(exts, Connection_Side::Client, client_hello.type());
626 std::visit([this](auto msg) { handle_reply_to_client_hello(std::move(msg)); },
627 Server_Hello_13::create(client_hello,
628 is_initial_client_hello,
631 rng(),
632 policy(),
633 callbacks()));
634}
635
636void Server_Impl_13::handle(const Certificate_13& certificate_msg) {
637 BOTAN_ASSERT_NONNULL(m_handshake);
638
639 // RFC 8446 4.3.2
640 // certificate_request_context: [...] This field SHALL be zero length
641 // unless used for the post-handshake authentication exchanges [...].
642 if(!is_handshake_complete() && !certificate_msg.request_context().empty()) {
643 throw TLS_Exception(Alert::DecodeError, "Received a client certificate message with non-empty request context");
644 }
645
646 // RFC 8446 4.4.2
647 // Extensions in the Certificate message from the client MUST correspond
648 // to extensions in the CertificateRequest message from the server.
649 certificate_msg.validate_extensions(m_handshake->state.certificate_request().extensions().extension_types(),
650 callbacks());
651
652 // RFC 8446 4.4.2.4
653 // If the client does not send any certificates (i.e., it sends an empty
654 // Certificate message), the server MAY at its discretion either continue
655 // the handshake without client authentication or abort the handshake with
656 // a "certificate_required" alert.
657 if(certificate_msg.empty()) {
658 if(policy().require_client_certificate_authentication()) {
659 throw TLS_Exception(Alert::CertificateRequired, "Policy requires client send a certificate, but it did not");
660 }
661
662 // RFC 8446 4.4.2
663 // A Finished message MUST be sent regardless of whether the
664 // Certificate message is empty.
665 m_handshake->transitions.set_expected_next(Handshake_Type::Finished);
666 } else {
667 // RFC 8446 4.4.2.4
668 // [...], if some aspect of the certificate chain was unacceptable
669 // (e.g., it was not signed by a known, trusted CA), the server MAY at
670 // its discretion either continue the handshake (considering the client
671 // unauthenticated) or abort the handshake.
672 //
673 // TODO: We could make this dependent on Policy::require_client_auth().
674 // Though, apps may also override Callbacks::tls_verify_cert_chain()
675 // and 'ignore' validation issues to a certain extent.
676
677 const bool use_ocsp = m_handshake->state.certificate_request().extensions().has<Certificate_Status_Request>();
678 certificate_msg.verify(
679 callbacks(), policy(), credentials_manager(), m_handshake->state.client_hello().sni_hostname(), use_ocsp);
680
681 // RFC 8446 4.4.3
682 // Clients MUST send this message whenever authenticating via a
683 // certificate (i.e., when the Certificate message
684 // is non-empty). When sent, this message MUST appear immediately after
685 // the Certificate message [...].
686 m_handshake->transitions.set_expected_next(Handshake_Type::CertificateVerify);
687 }
688}
689
690void Server_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) {
691 BOTAN_ASSERT_NONNULL(m_handshake);
693
694 // RFC 8446 4.4.3
695 // If sent by a client, the signature algorithm used in the signature
696 // MUST be one of those present in the supported_signature_algorithms
697 // field of the "signature_algorithms" extension in the
698 // CertificateRequest message.
699 const auto offered = m_handshake->state.certificate_request().signature_schemes();
700 if(!value_exists(offered, certificate_verify_msg.signature_scheme())) {
701 throw TLS_Exception(Alert::IllegalParameter,
702 "We did not offer the usage of " + certificate_verify_msg.signature_scheme().to_string() +
703 " as a signature scheme");
704 }
705
706 BOTAN_ASSERT_NOMSG(m_handshake->state.has_client_certificate_msg() &&
707 !m_handshake->state.client_certificate().empty());
708 const bool sig_valid = certificate_verify_msg.verify(
709 *m_handshake->state.client_certificate().public_key(), callbacks(), m_transcript_hash->previous());
710
711 // RFC 8446 4.4.3
712 // If the verification fails, the receiver MUST terminate the handshake
713 // with a "decrypt_error" alert.
714 if(!sig_valid) {
715 throw TLS_Exception(Alert::DecryptError, "Client certificate verification failed");
716 }
717
718 m_handshake->transitions.set_expected_next(Handshake_Type::Finished);
719}
720
721void Server_Impl_13::handle(const Finished_13& finished_msg) {
722 BOTAN_ASSERT_NONNULL(m_handshake);
724
725 // RFC 8446 4.4.4
726 // Recipients of Finished messages MUST verify that the contents are
727 // correct and if incorrect MUST terminate the connection with a
728 // "decrypt_error" alert.
729 if(!finished_msg.verify(m_cipher_state.get(), m_transcript_hash->previous())) {
730 throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify");
731 }
732
733 m_handshake->state.confirm_peer_finished_verified();
734
735 // Give the application a chance for a final veto before fully
736 // establishing the connection.
738 Session_Summary(m_handshake->state.server_hello(),
742 m_handshake->psk_identity,
743 m_handshake->resumed_session.has_value(),
744 Server_Information(m_handshake->state.client_hello().sni_hostname()),
745 callbacks().tls_current_timestamp()));
746
747 m_cipher_state->advance_with_client_finished(m_transcript_hash->current());
748
749 // no more handshake messages expected
750 m_handshake->transitions.set_expected_next({});
751
752 // Extract post-handshake state before signaling activation.
753 {
754 const auto extract_certs = [&]() -> std::vector<X509_Certificate> {
755 if(m_handshake->state.has_client_certificate_msg() &&
756 m_handshake->state.client_certificate().has_certificate_chain()) {
757 return m_handshake->state.client_certificate().cert_chain();
758 }
759 if(m_handshake->resumed_session.has_value()) {
760 return m_handshake->resumed_session->peer_certs();
761 }
762 return {};
763 };
764
765 const auto extract_raw_pk = [&]() -> std::shared_ptr<const Public_Key> {
766 if(m_handshake->state.has_client_certificate_msg() &&
767 m_handshake->state.client_certificate().is_raw_public_key()) {
768 return m_handshake->state.client_certificate().public_key();
769 }
770 if(m_handshake->resumed_session.has_value()) {
771 return m_handshake->resumed_session->peer_raw_public_key();
772 }
773 return nullptr;
774 };
775
776 const bool supports_psk_dhe =
777 m_handshake->state.client_hello().extensions().has<PSK_Key_Exchange_Modes>() &&
778 value_exists(m_handshake->state.client_hello().extensions().get<PSK_Key_Exchange_Modes>()->modes(),
780
781 m_active_state = Active_Connection_State_13(m_handshake->state,
782 extract_certs(),
783 extract_raw_pk(),
784 m_handshake->psk_identity,
785 m_handshake->state.client_hello().sni_hostname(),
786 supports_psk_dhe);
787 }
788
789 m_handshake.reset();
790 m_transcript_hash.reset();
792
794 send_new_session_tickets(policy().new_session_tickets_upon_handshake_success());
795 }
796}
797
798} // namespace Botan::TLS
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
virtual void tls_session_activated()
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_ssl_key_log_data(std::string_view label, std::span< const uint8_t > client_random, std::span< const uint8_t > secret) const
virtual void tls_inspect_handshake_msg(const Handshake_Message &message)
static std::optional< Certificate_Request_13 > maybe_create(const Client_Hello_13 &sni_hostname, Credentials_Manager &cred_mgr, Callbacks &callbacks, const Policy &policy)
std::shared_ptr< Cipher_State > m_cipher_state
Cipher_State & setup_cipher_state(std::unique_ptr< Cipher_State > cipher_state)
const Policy & policy() const
void send_flight(std::vector< Flight::Message > flight)
Credentials_Manager & credentials_manager()
RandomNumberGenerator & rng()
std::optional< Transcript_Hash_State > m_transcript_hash
virtual bool compat_mode_ccs_requested() const =0
std::optional< Active_Connection_State_13 > m_active_state
SecretLoggerFn secret_logger() const
virtual void process_dummy_change_cipher_spec()=0
Session_Manager & session_manager()
bool is_closed() const override
void set_selected_certificate_type(Certificate_Type cert_type)
void set_record_size_limits(uint16_t outgoing_limit, uint16_t incoming_limit)
static std::unique_ptr< Cipher_State > init_with_psk(Connection_Side side, TLS_Flavor flavor, PSK_Type type, secure_vector< uint8_t > &&psk, std::string_view prf_algo)
static std::unique_ptr< Cipher_State > init_with_server_hello(Connection_Side side, TLS_Flavor flavor, secure_vector< uint8_t > &&shared_secret, const Ciphersuite &cipher, const Transcript_Hash &transcript_hash, SecretLoggerFn secret_logger)
static std::optional< Ciphersuite > by_id(uint16_t suite)
virtual bool tls_13_middlebox_compatibility_mode() const
virtual std::chrono::seconds session_ticket_lifetime() const
static std::variant< Hello_Retry_Request, Server_Hello_13 > create(const Client_Hello_13 &ch, bool hello_retry_request_allowed, Session_Manager &session_mgr, Credentials_Manager &credentials_mgr, RandomNumberGenerator &rng, const Policy &policy, Callbacks &cb)
std::vector< X509_Certificate > peer_cert_chain() const override
size_t send_new_session_tickets(size_t tickets) override
std::optional< std::string > external_psk_identity() const override
std::shared_ptr< const Public_Key > peer_raw_public_key() const override
bool is_handshake_complete() const override
static std::shared_ptr< Server_Impl_13 > create(const std::shared_ptr< Callbacks > &callbacks, const std::shared_ptr< Session_Manager > &session_manager, const std::shared_ptr< Credentials_Manager > &credentials_manager, const std::shared_ptr< const Policy > &policy, const std::shared_ptr< RandomNumberGenerator > &rng)
std::string application_protocol() const override
bool new_session_ticket_supported() const override
static Transcript_Hash_State recreate_after_hello_retry_request(std::string_view algo_spec, const Transcript_Hash_State &prev_transcript_hash_state)
std::variant< Client_Hello_13, Client_Hello_12_Shim, Server_Hello_13, Server_Hello_12_Shim, Hello_Retry_Request, Encrypted_Extensions, Certificate_13, Certificate_Request_13, Certificate_Verify_13, Finished_13 > Handshake_Message_13
std::variant< New_Session_Ticket_13, Key_Update > Post_Handshake_Message_13
constexpr std::optional< SpecificVariantT > specialize_to(GeneralVariantT &&v)
Converts a given variant into another variant whose type states are a subset of the given variant.
Definition stl_util.h:117
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44
overloaded(Ts...) -> overloaded< Ts... >
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504