Botan 3.14.1
Crypto and TLS for C&
tls_client_impl_13.cpp
Go to the documentation of this file.
1/*
2* TLS Client - implementation for TLS 1.3
3* (C) 2022 Jack Lloyd
4* 2021 Elektrobit Automotive GmbH
5* 2022 Hannes Rantzsch, René Meusel - neXenio GmbH
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#include <botan/internal/tls_client_impl_13.h>
11
12#include <botan/credentials_manager.h>
13#include <botan/tls_callbacks.h>
14#include <botan/tls_extensions_13.h>
15#include <botan/tls_messages_13.h>
16#include <botan/tls_policy.h>
17#include <botan/x509cert.h>
18#include <botan/internal/stl_util.h>
19#include <botan/internal/tls_channel_impl_13.h>
20#include <botan/internal/tls_cipher_state.h>
21
22#include <utility>
23
24namespace Botan::TLS {
25
26std::shared_ptr<Client_Impl_13> Client_Impl_13::create(const std::shared_ptr<Callbacks>& callbacks,
27 const std::shared_ptr<Session_Manager>& session_manager,
28 const std::shared_ptr<Credentials_Manager>& creds,
29 const std::shared_ptr<const Policy>& policy,
30 const std::shared_ptr<RandomNumberGenerator>& rng,
31 Server_Information server_info,
32 const std::vector<std::string>& next_protocols) {
33 auto self = std::make_shared<Client_Impl_13>(
34 Private{}, callbacks, session_manager, creds, policy, rng, std::move(server_info));
35
36#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
37 if(policy->allow_tls12()) {
38 self->expect_downgrade(self->m_info, next_protocols);
39 }
40#endif
41
42 if(auto session = self->find_session_for_resumption()) {
43 if(session->session.version().is_tls_13_or_later()) {
44 self->m_handshake->resumed_session = std::move(session);
45 }
46#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
47 else if(self->expects_downgrade()) {
48 // If we found a session that was created with TLS 1.2, we downgrade
49 // the implementation right away, before even issuing a Client Hello.
50 self->request_downgrade_for_resumption(std::move(session.value()));
51 return self;
52 }
53#endif
54 }
55
56 BOTAN_ASSERT_NOMSG(self->m_transcript_hash.has_value());
57
58 auto flight = Flight(*self->m_transcript_hash, self->callbacks())
59 .add(self->m_handshake->state.sending(
61 *callbacks,
62 *rng,
63 self->m_info.hostname(),
64 next_protocols,
65 self->m_handshake->resumed_session,
66 creds->find_preshared_keys(self->m_info.hostname(), Connection_Side::Client),
68
69 // RFC 9846 E.4
70 // [...] If offering early data, the [dummy Change Cipher Spec record]
71 // is placed immediately after the first ClientHello.
72 //
73 // TODO(0-RTT): When implementing early data, we need to add the dummy CCS
74 // record to this initial ClientHello flight!
75
76 self->send_flight(flight.commit());
77
78 self->m_handshake->transitions.set_expected_next({Handshake_Type::ServerHello, Handshake_Type::HelloRetryRequest});
79
80 return self;
81}
82
83void Client_Impl_13::process_handshake_msg(Handshake_Message_13 message) {
84 BOTAN_STATE_CHECK(m_handshake != nullptr);
85
86 // first verify that the message was expected by the state machine
87 // (and only then store it in the handshake state)
88 m_handshake->transitions.confirm_transition_to(std::visit([](const auto& msg) { return msg.type(); }, message));
89
90 std::visit(
91 [&](auto msg) {
92 // ... then allow the library user to abort on their discretion
94
95 // ... finally handle the message
96 handle(msg.get());
97 },
98 m_handshake->state.received(std::move(message)));
99}
100
101void Client_Impl_13::process_post_handshake_msg(Post_Handshake_Message_13 message) {
103
104 const auto msg = specialize_to<Server_Post_Handshake_13_Message>(std::move(message));
105 if(!msg) {
106 throw TLS_Exception(Alert::UnexpectedMessage, "received an unexpected post-handshake message");
107 }
108
109 std::visit(
110 [&](auto&& m) {
112 handle(m);
113 },
114 *msg);
115}
116
118 // RFC 8446 5.
119 // If an implementation detects a change_cipher_spec record received before
120 // the first ClientHello message or after the peer's Finished message, it MUST be
121 // treated as an unexpected record type [("unexpected_message" alert)].
122 if(!m_handshake || !m_handshake->state.has_client_hello() || m_handshake->state.has_server_finished()) {
123 throw TLS_Exception(Alert::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec");
124 }
125
126 // RFC 8446 5.
127 // An implementation may receive an unencrypted record of type change_cipher_spec [...]
128 // at any time after the first ClientHello message has been sent or received
129 // and before the peer's Finished message has been received [...]
130 // and MUST simply drop it without further processing.
131 //
132 // ... no further processing.
133}
134
136 return m_active_state.has_value();
137}
138
139std::optional<Session_with_Handle> Client_Impl_13::find_session_for_resumption() {
140 // RFC 8446 4.6.1
141 // Clients MUST only resume if the new SNI value is valid for the
142 // server certificate presented in the original session and SHOULD only
143 // resume if the SNI value matches the one used in the original session.
144 //
145 // Below we search sessions based on their SNI value. Assuming that a
146 // 3rd party session manager does not lie to the implementation, we don't
147 // explicitly re-check that the SNI values match.
148 //
149 // Also, the default implementation did verify that very same SNI information
150 // against the server's certificate (via Callbacks::tls_verify_cert_chain())
151 // before storing it in the session.
152 //
153 // We therefore assume that the session returned by the `Session_Manager` is
154 // suitable for resumption in this context.
155 auto sessions = session_manager().find(m_info, callbacks(), policy());
156 if(sessions.empty()) {
157 return std::nullopt;
158 }
159
160 // TODO: TLS 1.3 allows sending more than one ticket (for resumption) in a
161 // Client Hello. Currently, we do not support that. The Session_Manager
162 // does imply otherwise with its API, though.
163 auto& session_to_resume = sessions.front();
164
165 return std::move(session_to_resume);
166}
167
168void Client_Impl_13::handle(const Server_Hello_12_Shim& server_hello_msg) {
169 BOTAN_ASSERT_NONNULL(m_handshake);
170
171 if(m_handshake->state.has_hello_retry_request()) {
172 throw TLS_Exception(Alert::UnexpectedMessage, "Version downgrade received after Hello Retry");
173 }
174
175#if !defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
176 BOTAN_UNUSED(server_hello_msg);
177 throw TLS_Exception(Alert::ProtocolVersion, "Received an unsupported Server Hello");
178#else
179
180 // RFC 8446 Appendix D.1
181 // If the version chosen by the server is not supported by the client
182 // (or is not acceptable), the client MUST abort the handshake with a
183 // "protocol_version" alert.
184 if(!expects_downgrade()) {
185 throw TLS_Exception(Alert::ProtocolVersion, "Received an unexpected legacy Server Hello");
186 }
187
188 // RFC 8446 4.1.3
189 // TLS 1.3 has a downgrade protection mechanism embedded in the server's
190 // random value. TLS 1.3 servers which negotiate TLS 1.2 or below in
191 // response to a ClientHello MUST set the last 8 bytes of their Random
192 // value specially in their ServerHello.
193 //
194 // TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
195 // MUST check that the [downgrade indication is not set]. [...] If a match
196 // is found, the client MUST abort the handshake with an
197 // "illegal_parameter" alert.
198 if(server_hello_msg.random_signals_downgrade().has_value()) {
199 throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected");
200 }
201
202 // RFC 8446 4.2.1
203 // A server which negotiates a version of TLS prior to TLS 1.3 [...]
204 // MUST NOT send the "supported_versions" extension.
205 //
206 // Note that this condition should never happen, as the Server_Hello parsing
207 // code decides to create a Server_Hello_12 based on the absence of this extension.
208 if(server_hello_msg.extensions().has<Supported_Versions>()) {
209 throw TLS_Exception(Alert::IllegalParameter, "Unexpected extension received");
210 }
211
212 // These extensions offered in our ClientHello are not defined for a TLS 1.2 ServerHello
213 const auto& sh_exts = server_hello_msg.extensions();
214 for(const auto tls13_only : {Extension_Code::KeyShare,
220 if(sh_exts.has(tls13_only)) {
221 throw TLS_Exception(Alert::IllegalParameter, "TLS 1.2 Server Hello contained a TLS 1.3 extension");
222 }
223 }
224
225 // RFC 8446 Appendix D.1
226 // If the version chosen by the server is not supported by the client
227 // (or is not acceptable), the client MUST abort the handshake with a
228 // "protocol_version" alert.
229 const auto& client_hello_exts = m_handshake->state.client_hello().extensions();
230 BOTAN_ASSERT_NOMSG(client_hello_exts.has<Supported_Versions>());
231 if(!client_hello_exts.get<Supported_Versions>()->supports(server_hello_msg.selected_version())) {
232 throw TLS_Exception(Alert::ProtocolVersion, "Protocol version was not offered");
233 }
234
235 if(policy().tls_13_middlebox_compatibility_mode() &&
236 m_handshake->state.client_hello().session_id() == server_hello_msg.session_id()) {
237 // In compatibility mode, the server will reflect the session ID we sent in the client hello.
238 // However, a TLS 1.2 server that wants to downgrade cannot have found the random session ID
239 // we sent. Therefore, we have to consider this as an attack.
240 // (Thanks BoGo test EchoTLS13CompatibilitySessionID!)
241 throw TLS_Exception(Alert::IllegalParameter, "Unexpected session ID during downgrade");
242 }
243
244 preserve_client_hello(m_handshake->state.take_client_hello());
245 request_downgrade();
246
247 // After this, no further messages are expected here because this instance will be replaced
248 // by a Client_Impl_12.
249 m_handshake->transitions.set_expected_next({});
250#endif
251}
252
253namespace {
254// validate Server_Hello_13 and Hello_Retry_Request
255void validate_server_hello_ish(const Client_Hello_13& ch, const Server_Hello_13& sh) {
256 // RFC 8446 4.1.3
257 // A client which receives a legacy_session_id_echo field that does not match what
258 // it sent in the ClientHello MUST abort the handshake with an "illegal_parameter" alert.
259 if(ch.session_id() != sh.session_id()) {
260 throw TLS_Exception(Alert::IllegalParameter, "echoed session id did not match");
261 }
262
263 // RFC 8446 4.1.3
264 // A client which receives a cipher suite that was not offered MUST abort the handshake
265 // with an "illegal_parameter" alert.
266 if(!ch.offered_suite(sh.ciphersuite())) {
267 throw TLS_Exception(Alert::IllegalParameter, "Server replied with ciphersuite we didn't send");
268 }
269
270 // RFC 8446 4.2.1
271 // If the "supported_versions" extension in the ServerHello contains a
272 // version not offered by the client or contains a version prior to
273 // TLS 1.3, the client MUST abort the handshake with an "illegal_parameter" alert.
274 //
275 // Note: Server_Hello_13 parsing checks that its selected version is TLS 1.3
276 BOTAN_ASSERT_NOMSG(ch.extensions().has<Supported_Versions>());
277 if(!ch.extensions().get<Supported_Versions>()->supports(sh.selected_version())) {
278 throw TLS_Exception(Alert::IllegalParameter, "Protocol version was not offered");
279 }
280}
281} // namespace
282
283void Client_Impl_13::handle(const Server_Hello_13& sh) {
284 // Note: Basic checks (that do not require contextual information) were already
285 // performed during the construction of the Server_Hello_13 object.
286 BOTAN_ASSERT_NONNULL(m_handshake);
288
289 const auto& ch = m_handshake->state.client_hello();
290
291 validate_server_hello_ish(ch, sh);
292
293 // RFC 8446 4.1.3: TLS 1.3 servers downgrading to TLS 1.2 or below set
294 // the last 8 bytes of ServerHello.random to a magic value so the client
295 // can detect a stripped-supported_versions downgrade attack. The Shim
296 // path (Server_Hello_12_Shim) already enforces this; catch it here too
297 // as defense in depth in case a misbehaving server writes the sentinel
298 // into an actual TLS 1.3 ServerHello.
299 if(sh.random_signals_downgrade().has_value()) {
300 throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected");
301 }
302
303 // RFC 8446 4.2
304 // Implementations MUST NOT send extension responses if the remote
305 // endpoint did not send the corresponding extension requests, [...]. Upon
306 // receiving such an extension, an endpoint MUST abort the handshake
307 // with an "unsupported_extension" alert.
308 if(sh.extensions().contains_other_than(ch.extensions().extension_types())) {
309 throw TLS_Exception(Alert::UnsupportedExtension, "Unsupported extension found in Server Hello");
310 }
311
312 if(m_handshake->state.has_hello_retry_request()) {
313 const auto& hrr = m_handshake->state.hello_retry_request();
314
315 // RFC 8446 4.1.4
316 // Upon receiving the ServerHello, clients MUST check that the cipher suite
317 // supplied in the ServerHello is the same as that in the HelloRetryRequest
318 // and otherwise abort the handshake with an "illegal_parameter" alert.
319 if(hrr.ciphersuite() != sh.ciphersuite()) {
320 throw TLS_Exception(Alert::IllegalParameter, "server changed its chosen ciphersuite");
321 }
322
323 // RFC 8446 4.1.4
324 // The value of selected_version in the HelloRetryRequest "supported_versions"
325 // extension MUST be retained in the ServerHello, and a client MUST abort the
326 // handshake with an "illegal_parameter" alert if the value changes.
327 if(hrr.selected_version() != sh.selected_version()) {
328 throw TLS_Exception(Alert::IllegalParameter, "server changed its chosen protocol version");
329 }
330 }
331
332 auto cipher = Ciphersuite::by_id(sh.ciphersuite());
333 BOTAN_ASSERT_NOMSG(cipher.has_value()); // should work, since we offered this suite
334
335 // RFC 8446 Appendix B.4
336 // Although TLS 1.3 uses the same cipher suite space as previous versions
337 // of TLS [...] cipher suites for TLS 1.2 and lower cannot be used with
338 // TLS 1.3.
339 if(!cipher->usable_in_version(Protocol_Version::TLS_V13)) {
340 throw TLS_Exception(Alert::IllegalParameter,
341 "Server replied using a ciphersuite not allowed in version it offered");
342 }
343
344 // RFC 8446 4.2.11
345 // Clients MUST verify that [...] a server "key_share" extension is present
346 // if required by the ClientHello "psk_key_exchange_modes" extension. If
347 // these values are not consistent, the client MUST abort the handshake
348 // with an "illegal_parameter" alert.
349 //
350 // Currently, we don't support PSK-only mode, hence a key share extension is
351 // considered mandatory.
352 //
353 // TODO: Implement PSK-only mode.
354 if(!sh.extensions().has<Key_Share>()) {
355 throw TLS_Exception(Alert::IllegalParameter, "Server Hello did not contain a key share extension");
356 }
357
358 auto* my_keyshare = ch.extensions().get<Key_Share>();
359 auto shared_secret = my_keyshare->decapsulate(*sh.extensions().get<Key_Share>(), policy(), callbacks(), rng());
360
361 m_transcript_hash->set_algorithm(cipher.value().prf_algo());
362
364 if(sh.extensions().has<PSK>()) {
365 std::unique_ptr<Cipher_State> new_cipher_state;
366 std::tie(m_handshake->psk_identity, new_cipher_state) =
367 ch.extensions().get<PSK>()->take_selected_psk_info(*sh.extensions().get<PSK>(), cipher.value());
368 new_cipher_state->set_secret_logger(secret_logger());
369
370 // If we offered a session for resumption *and* an externally provided PSK
371 // and the latter was chosen by the server over the offered resumption, we
372 // want to invalidate the now-outdated session in m_handshake->resumed_session.
373 if(m_handshake->psk_identity.has_value() && m_handshake->resumed_session.has_value()) {
374 m_handshake->resumed_session.reset();
375 }
376
377 // TODO: When implementing early data, `advance_with_client_hello` must
378 // happen _before_ encrypting any early application data.
379 // Same when we want to support early key export.
380 new_cipher_state->advance_with_client_hello(m_transcript_hash->previous());
381 new_cipher_state->advance_with_server_hello(
382 cipher.value(), std::move(shared_secret), m_transcript_hash->current());
383
384 return new_cipher_state;
385 } else {
386 m_handshake->resumed_session.reset(); // might have been set if we attempted a resumption
389 std::move(shared_secret),
390 cipher.value(),
391 m_transcript_hash->current(),
392 secret_logger());
393 }
394 }());
395
397
398 m_handshake->transitions.set_expected_next(Handshake_Type::EncryptedExtensions);
399}
400
401void Client_Impl_13::handle(const Hello_Retry_Request& hrr) {
402 // Note: Basic checks (that do not require contextual information) were already
403 // performed during the construction of the Hello_Retry_Request object as
404 // a subclass of Server_Hello_13.
405 BOTAN_ASSERT_NONNULL(m_handshake);
407
408 auto& ch = m_handshake->state.client_hello();
409
410 validate_server_hello_ish(ch, hrr);
411
412 // RFC 8446 4.1.4.
413 // A HelloRetryRequest MUST NOT contain any
414 // extensions that were not first offered by the client in its
415 // ClientHello, with the exception of optionally the "cookie".
416 auto allowed_exts = ch.extensions().extension_types();
417 allowed_exts.insert(Extension_Code::Cookie);
418 if(hrr.extensions().contains_other_than(allowed_exts)) {
419 throw TLS_Exception(Alert::UnsupportedExtension, "Unsupported extension found in Hello Retry Request");
420 }
421
422 auto cipher = Ciphersuite::by_id(hrr.ciphersuite());
423 BOTAN_ASSERT_NOMSG(cipher.has_value()); // should work, since we offered this suite
424
425 // RFC 8446 4.1.4 / Appendix B.4
426 // Similarly, cipher suites for TLS 1.2 and lower cannot be used with
427 // TLS 1.3.
428 if(!cipher->usable_in_version(Protocol_Version::TLS_V13)) {
429 throw TLS_Exception(Alert::IllegalParameter, "HelloRetryRequest selected a cipher suite not usable in TLS 1.3");
430 }
431
434
435 ch.retry(hrr, *m_transcript_hash, callbacks(), rng());
436
438
439 auto flight = Flight(*m_transcript_hash, callbacks());
440
441 // RFC 9846 E.4
442 // If not offering early data, the client sends a dummy
443 // change_cipher_spec record [...] immediately before its second
444 // flight. This may either be before its second ClientHello or before
445 // its encrypted handshake flight.
446 //
447 // Here, we are in the HelloRetryRequest flow, so we send the CCS before
448 // the second ClientHello.
450 flight.add_dummy_change_cipher_spec();
451 }
452 flight.add(ch);
453
454 send_flight(flight.commit());
455
456 // RFC 8446 4.1.4
457 // If a client receives a second HelloRetryRequest in the same connection [...],
458 // it MUST abort the handshake with an "unexpected_message" alert.
459 m_handshake->transitions.set_expected_next(Handshake_Type::ServerHello);
460}
461
462void Client_Impl_13::handle(const Encrypted_Extensions& encrypted_extensions_msg) {
463 BOTAN_ASSERT_NONNULL(m_handshake);
464
465 const auto& exts = encrypted_extensions_msg.extensions();
466
467 // RFC 8446 4.2
468 // Implementations MUST NOT send extension responses if the remote
469 // endpoint did not send the corresponding extension requests, [...]. Upon
470 // receiving such an extension, an endpoint MUST abort the handshake
471 // with an "unsupported_extension" alert.
472 const auto& requested_exts = m_handshake->state.client_hello().extensions().extension_types();
473 if(exts.contains_other_than(requested_exts)) {
474 throw TLS_Exception(Alert::UnsupportedExtension,
475 "Encrypted Extensions contained an extension that was not offered");
476 }
477
478 // Note: As per RFC 6066 3. we can check for an empty SNI extensions to
479 // determine if the server used the SNI we sent here.
480
481 if(exts.has<Application_Layer_Protocol_Notification>()) {
482 // RFC 7301 3.2
483 // The "extension_data" field of the [...] "application_layer_protocol_negotiation"
484 // extension [...] SHALL include the server's selection of a protocol from among
485 // the list that was advertised by the client.
486 const auto* server_alpn = exts.get<Application_Layer_Protocol_Notification>();
487 const auto selected = server_alpn->single_protocol();
488 const auto* client_alpn =
489 m_handshake->state.client_hello().extensions().get<Application_Layer_Protocol_Notification>();
490 BOTAN_ASSERT_NONNULL(client_alpn); // unrequested extension check above ensures this
491 const auto& offered = client_alpn->protocols();
492 if(!value_exists(offered, selected)) {
493 throw TLS_Exception(Alert::IllegalParameter, "Server selected an ALPN protocol not offered by the client");
494 }
495 }
496
497 if(exts.has<Record_Size_Limit>() && m_handshake->state.client_hello().extensions().has<Record_Size_Limit>()) {
498 // RFC 8449 4.
499 // The record size limit only applies to records sent toward the
500 // endpoint that advertises the limit. An endpoint can send records
501 // that are larger than the limit it advertises as its own limit.
502 //
503 // Hence, the "outgoing" limit is what the server requested and the
504 // "incoming" limit is what we requested in the Client Hello.
505 const auto* const outgoing_limit = exts.get<Record_Size_Limit>();
506 const auto* const incoming_limit = m_handshake->state.client_hello().extensions().get<Record_Size_Limit>();
507 set_record_size_limits(outgoing_limit->limit(), incoming_limit->limit());
508 }
509
510 if(exts.has<Server_Certificate_Type>()) {
511 // The unrequested-extension check above ensures the client offered this.
512 BOTAN_ASSERT_NOMSG(m_handshake->state.client_hello().extensions().has<Server_Certificate_Type>());
513 const auto* server_cert_type = exts.get<Server_Certificate_Type>();
514 const auto* our_server_cert_types = m_handshake->state.client_hello().extensions().get<Server_Certificate_Type>();
515 our_server_cert_types->validate_selection(*server_cert_type);
516
517 // RFC 7250 4.2
518 // With the server_certificate_type extension in the server hello, the
519 // TLS server indicates the certificate type carried in the Certificate
520 // payload.
521 //
522 // Note: TLS 1.3 carries this extension in the Encrypted Extensions
523 // message instead of the Server Hello.
524 set_selected_certificate_type(server_cert_type->selected_certificate_type());
525 }
526
527 if(const auto* client_cert_type = exts.get<Client_Certificate_Type>()) {
528 // RFC 7250 4.2
529 // The value conveyed in the client_certificate_type extension MUST be
530 // selected from one of the values provided in the
531 // client_certificate_type extension sent in the client hello.
532 m_handshake->state.client_hello().extensions().get<Client_Certificate_Type>()->validate_selection(
533 *client_cert_type);
534
535 // RFC 7250 4.2
536 // If the server does not send a certificate_request payload [...],
537 // then the client_certificate_type payload in the server hello MUST
538 // be omitted.
539 //
540 // A server authenticating with a PSK cannot send a certificate_request.
541 // Otherwise this is checked once the server's Finished arrived.
542 //
543 // TODO(RFC 9973): this needs an extension when certificates may be used with an external PSK
544 if(m_handshake->state.server_hello().extensions().has<PSK>()) {
545 throw TLS_Exception(Alert::IllegalParameter,
546 "Server selected a client certificate type without requesting a certificate");
547 }
548 }
549
551
552 if(m_handshake->state.server_hello().extensions().has<PSK>()) {
553 // RFC 8446 2.2
554 // As the server is authenticating via a PSK, it does not send a
555 // Certificate or a CertificateVerify message.
556 m_handshake->transitions.set_expected_next(Handshake_Type::Finished);
557 } else {
558 m_handshake->transitions.set_expected_next({Handshake_Type::Certificate, Handshake_Type::CertificateRequest});
559 }
560}
561
562void Client_Impl_13::handle(const Certificate_Request_13& certificate_request_msg) {
563 BOTAN_ASSERT_NONNULL(m_handshake);
564
565 // RFC 8446 4.3.2
566 // [The 'context' field] SHALL be zero length unless used for the
567 // post-handshake authentication exchanges described in Section 4.6.2.
568 if(!is_handshake_complete() && !certificate_request_msg.context().empty()) {
569 throw TLS_Exception(Alert::DecodeError, "Certificate_Request context must be empty in the main handshake");
570 }
571
573 certificate_request_msg.extensions(), Connection_Side::Server, Handshake_Type::CertificateRequest);
574 m_handshake->transitions.set_expected_next(Handshake_Type::Certificate);
575}
576
577void Client_Impl_13::handle(const Certificate_13& certificate_msg) {
578 BOTAN_ASSERT_NONNULL(m_handshake);
579
580 // RFC 8446 4.4.2
581 // certificate_request_context: [...] In the case of server authentication,
582 // this field SHALL be zero length.
583 if(!certificate_msg.request_context().empty()) {
584 throw TLS_Exception(Alert::DecodeError, "Received a server certificate message with non-empty request context");
585 }
586
587 // RFC 8446 4.4.2
588 // Extensions in the Certificate message from the server MUST correspond
589 // to ones from the ClientHello message.
590 certificate_msg.validate_extensions(m_handshake->state.client_hello().extensions().extension_types(), callbacks());
591 certificate_msg.verify(callbacks(),
592 policy(),
594 m_info.hostname(),
595 m_handshake->state.client_hello().extensions().has<Certificate_Status_Request>());
596
597 m_handshake->transitions.set_expected_next(Handshake_Type::CertificateVerify);
598}
599
600void Client_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) {
601 BOTAN_ASSERT_NONNULL(m_handshake);
603
604 // RFC 8446 4.4.3
605 // If the CertificateVerify message is sent by a server, the signature
606 // algorithm MUST be one offered in the client's "signature_algorithms"
607 // extension unless no valid certificate chain can be produced without
608 // unsupported algorithms.
609 //
610 // Note: if the server failed to produce a certificate chain without using
611 // an unsupported signature scheme, we opt to abort the handshake.
612 const auto offered = m_handshake->state.client_hello().signature_schemes();
613 if(!value_exists(offered, certificate_verify_msg.signature_scheme())) {
614 throw TLS_Exception(Alert::IllegalParameter,
615 "We did not offer the usage of " + certificate_verify_msg.signature_scheme().to_string() +
616 " as a signature scheme");
617 }
618
619 const bool sig_valid = certificate_verify_msg.verify(
620 *m_handshake->state.server_certificate().public_key(), callbacks(), m_transcript_hash->previous());
621
622 if(!sig_valid) {
623 throw TLS_Exception(Alert::DecryptError, "Server certificate verification failed");
624 }
625
626 m_handshake->transitions.set_expected_next(Handshake_Type::Finished);
627}
628
629void Client_Impl_13::create_client_authentication_flight(Flight& flight) {
630 BOTAN_ASSERT_NONNULL(m_handshake);
632 BOTAN_ASSERT_NOMSG(m_handshake->state.has_certificate_request());
633 const auto& cert_request = m_handshake->state.certificate_request();
634
635 const auto cert_type = [&] {
636 const auto& exts = m_handshake->state.encrypted_extensions().extensions();
637 const auto& chexts = m_handshake->state.client_hello().extensions();
638 if(exts.has<Client_Certificate_Type>()) {
639 // The unrequested-extension check in handle(Encrypted_Extensions) ensures the client offered this.
640 BOTAN_ASSERT_NOMSG(chexts.has<Client_Certificate_Type>());
641 const auto* client_cert_type = exts.get<Client_Certificate_Type>();
642 chexts.get<Client_Certificate_Type>()->validate_selection(*client_cert_type);
643
644 // RFC 7250 4.2
645 // This client_certificate_type extension in the server hello then
646 // indicates the type of certificates the client is requested to
647 // provide in a subsequent certificate payload.
648 //
649 // Note: TLS 1.3 carries this extension in the Encrypted Extensions
650 // message instead of the Server Hello.
651 return client_cert_type->selected_certificate_type();
652 } else {
653 // RFC 8446 4.4.2
654 // If the corresponding certificate type extension [...] was not
655 // negotiated in EncryptedExtensions, [...] then each
656 // CertificateEntry contains a DER-encoded X.509 certificate.
658 }
659 }();
660
661 // RFC 8446 4.4.2
662 // certificate_request_context: If this message is in response to a
663 // CertificateRequest, the value of certificate_request_context in
664 // that message.
665 flight.add(m_handshake->state.sending(
666 Certificate_13(cert_request, m_info.hostname(), credentials_manager(), callbacks(), cert_type)));
667
668 // RFC 8446 4.4.2
669 // If the server requests client authentication but no suitable certificate
670 // is available, the client MUST send a Certificate message containing no
671 // certificates.
672 //
673 // In that case, no Certificate Verify message will be sent.
674 if(!m_handshake->state.client_certificate().empty()) {
675 flight.add(m_handshake->state.sending(Certificate_Verify_13(m_handshake->state.client_certificate(),
676 cert_request.signature_schemes(),
677 m_info.hostname(),
678 m_transcript_hash->current(),
681 policy(),
682 callbacks(),
683 rng())));
684 }
685}
686
687void Client_Impl_13::handle(const Finished_13& finished_msg) {
688 BOTAN_ASSERT_NONNULL(m_handshake);
690
691 // RFC 8446 4.4.4
692 // Recipients of Finished messages MUST verify that the contents are
693 // correct and if incorrect MUST terminate the connection with a
694 // "decrypt_error" alert.
695 if(!finished_msg.verify(m_cipher_state.get(), m_transcript_hash->previous())) {
696 throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify");
697 }
698
699 m_handshake->state.confirm_peer_finished_verified();
700
701 if(m_handshake->state.encrypted_extensions().extensions().has<Client_Certificate_Type>() &&
702 !m_handshake->state.has_certificate_request()) {
703 throw TLS_Exception(Alert::IllegalParameter,
704 "Server selected a client certificate type without requesting a certificate");
705 }
706
707 // Give the application a chance for a final veto before fully
708 // establishing the connection.
709 callbacks().tls_session_established(Session_Summary(m_handshake->state.server_hello(),
714 m_handshake->resumed_session.has_value(),
715 m_info,
716 callbacks().tls_current_timestamp()));
717
718 // Derives the secrets for receiving application data but defers
719 // the derivation of sending application data.
720 m_cipher_state->advance_with_server_finished(m_transcript_hash->current());
721
722 auto flight = Flight(*m_transcript_hash, callbacks());
723
724 // RFC 9846 E.4
725 // If not offering early data, the client sends a dummy
726 // change_cipher_spec record [...] immediately before its second
727 // flight. This may either be before its second ClientHello or before
728 // its encrypted handshake flight.
729 //
730 // If we didn't handle a HelloRetryRequest before, this is our second
731 // flight and we send the CCS. Otherwise, we are already sending our third
732 // flight and the CCS was already sent before the second ClientHello.
733 if(compat_mode_ccs_requested() && !m_handshake->state.has_hello_retry_request()) {
734 flight.add_dummy_change_cipher_spec();
735 }
736
737 // RFC 8446 4.4.2
738 // The client MUST send a Certificate message if and only if the server
739 // has requested client authentication via a CertificateRequest message.
740 if(m_handshake->state.has_certificate_request()) {
741 create_client_authentication_flight(flight);
742 }
743
744 // send client finished handshake message (still using handshake traffic secrets)
745 flight.add(m_handshake->state.sending(Finished_13(m_cipher_state.get(), m_transcript_hash->current())));
746
747 send_flight(flight.commit());
748
749 // derives the sending application traffic secrets
750 m_cipher_state->advance_with_client_finished(m_transcript_hash->current());
751
752 // TODO: Create a dummy session object and invoke tls_session_established.
753 // Alternatively, consider changing the expectations described in the
754 // callback's doc string.
755
756 // no more handshake messages expected
757 m_handshake->transitions.set_expected_next({});
758
759 // Extract post-handshake state before signaling activation.
760 // After this point, only m_active_state should be consulted
761 // for connection properties.
762 {
763 const auto extract_certs = [&]() -> std::vector<X509_Certificate> {
764 if(m_handshake->state.has_server_certificate_msg() &&
765 m_handshake->state.server_certificate().has_certificate_chain()) {
766 return m_handshake->state.server_certificate().cert_chain();
767 }
768 if(m_handshake->resumed_session.has_value()) {
769 return m_handshake->resumed_session->session.peer_certs();
770 }
771 return {};
772 };
773
774 const auto extract_raw_pk = [&]() -> std::shared_ptr<const Public_Key> {
775 if(m_handshake->state.has_server_certificate_msg() &&
776 m_handshake->state.server_certificate().is_raw_public_key()) {
777 return m_handshake->state.server_certificate().public_key();
778 }
779 if(m_handshake->resumed_session.has_value()) {
780 return m_handshake->resumed_session->session.peer_raw_public_key();
781 }
782 return nullptr;
783 };
784
785 m_active_state = Active_Connection_State_13(m_handshake->state,
786 extract_certs(),
787 extract_raw_pk(),
788 m_handshake->psk_identity,
789 m_info.hostname(),
790 false /* peer_supports_psk_dhe_ke - client doesn't need this */);
791 }
792
793 m_handshake.reset();
794 m_transcript_hash.reset();
796}
797
798void TLS::Client_Impl_13::handle(const New_Session_Ticket_13& new_session_ticket) {
799 BOTAN_STATE_CHECK(m_active_state.has_value());
800
801 if(const size_t max_tickets = policy().maximum_session_tickets_per_connection();
802 max_tickets > 0 && m_session_tickets_received >= max_tickets) {
803 // Silently ignore excess tickets rather than terminating the connection,
804 // since the server may have legitimate reasons to send many tickets.
805 return;
806 }
807 ++m_session_tickets_received;
808
809 callbacks().tls_examine_extensions(
810 new_session_ticket.extensions(), Connection_Side::Server, Handshake_Type::NewSessionTicket);
811
812 const Session session(m_cipher_state->psk(new_session_ticket.nonce()),
813 new_session_ticket.early_data_byte_limit(),
814 new_session_ticket.ticket_age_add(),
815 new_session_ticket.lifetime_hint(),
816 m_active_state->version(),
817 m_active_state->ciphersuite_code(),
819 peer_cert_chain(),
820 peer_raw_public_key(),
821 m_info,
822 callbacks().tls_current_timestamp());
823
824 if(callbacks().tls_should_persist_resumption_information(session)) {
825 session_manager().store(session, Session_Handle(new_session_ticket.handle()));
826 }
827}
828
829std::vector<X509_Certificate> Client_Impl_13::peer_cert_chain() const {
830 if(m_active_state.has_value()) {
831 return m_active_state->peer_certs();
832 }
833
834 // During handshake, before m_active_state is populated
835 if(m_handshake) {
836 if(m_handshake->state.has_server_certificate_msg() &&
837 m_handshake->state.server_certificate().has_certificate_chain()) {
838 return m_handshake->state.server_certificate().cert_chain();
839 }
840
841 if(m_handshake->resumed_session.has_value()) {
842 return m_handshake->resumed_session->session.peer_certs();
843 }
844 }
845
846 return {};
847}
848
849std::shared_ptr<const Public_Key> Client_Impl_13::peer_raw_public_key() const {
850 if(m_active_state.has_value()) {
851 return m_active_state->peer_raw_public_key();
852 }
853
854 // During handshake, before m_active_state is populated
855 if(m_handshake) {
856 if(m_handshake->state.has_server_certificate_msg() &&
857 m_handshake->state.server_certificate().is_raw_public_key()) {
858 return m_handshake->state.server_certificate().public_key();
859 }
860
861 if(m_handshake->resumed_session.has_value()) {
862 return m_handshake->resumed_session->session.peer_raw_public_key();
863 }
864 }
865
866 return nullptr;
867}
868
869std::optional<std::string> Client_Impl_13::external_psk_identity() const {
870 if(m_active_state.has_value()) {
871 return m_active_state->psk_identity();
872 }
873 if(m_handshake) {
874 return m_handshake->psk_identity;
875 }
876 return std::nullopt;
877}
878
880 // RFC 9846 E.4
881 // This "compatibility mode" is partially negotiated: the client can opt
882 // [in] or not [...].
883 if(!policy().tls_13_middlebox_compatibility_mode()) {
884 return false;
885 }
886
887 return true;
888}
889
890void Client_Impl_13::maybe_log_secret(std::string_view label, std::span<const uint8_t> secret) const {
891 if(policy().allow_ssl_key_log_file()) {
892 if(m_active_state.has_value()) {
893 callbacks().tls_ssl_key_log_data(label, m_active_state->client_random(), secret);
894 } else {
895 callbacks().tls_ssl_key_log_data(label, m_handshake->state.client_hello().random(), secret);
896 }
897 }
898}
899
901 if(m_active_state.has_value()) {
902 return m_active_state->application_protocol();
903 }
904
905 return "";
906}
907
908} // 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)
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()
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_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)
std::optional< std::string > external_psk_identity() const override
static std::shared_ptr< Client_Impl_13 > create(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, Server_Information server_info=Server_Information(), const std::vector< std::string > &next_protocols={})
std::string application_protocol() const override
std::shared_ptr< const Public_Key > peer_raw_public_key() const override
bool is_handshake_complete() const override
std::vector< X509_Certificate > peer_cert_chain() const override
Flight & add(Handshake_Message_13_Ref msg) &
Helper class to embody a session handle in all protocol versions.
virtual std::vector< Session_with_Handle > find(const Server_Information &info, Callbacks &callbacks, const Policy &policy)
Find all sessions that match a given server info.
bool supports(Protocol_Version version) const
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