Botan 3.14.1
Crypto and TLS for C&
tls_client_impl_12.cpp
Go to the documentation of this file.
1/*
2* TLS Client
3* (C) 2004-2011,2012,2015,2016 Jack Lloyd
4* 2016 Matthias Gierlings
5* 2017 Harry Reimann, Rohde & Schwarz Cybersecurity
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#include <botan/internal/tls_client_impl_12.h>
11
12#include <botan/exceptn.h>
13#include <botan/ocsp.h>
14#include <botan/tls_callbacks.h>
15#include <botan/tls_messages_12.h>
16#include <botan/tls_policy.h>
17#include <botan/internal/stl_util.h>
18#include <botan/internal/tls_handshake_state.h>
19#include <algorithm>
20#include <optional>
21#include <sstream>
22#include <utility>
23
24namespace Botan::TLS {
25
26namespace {
27
28class Client_Handshake_State_12 final : public Handshake_State {
29 public:
30 Client_Handshake_State_12(std::unique_ptr<Handshake_IO> io, Callbacks& cb) :
31 Handshake_State(std::move(io), cb), m_is_reneg(false) {}
32
33 const Public_Key& server_public_key() const {
34 BOTAN_ASSERT(m_server_public_key, "Server sent us a certificate");
35 return *m_server_public_key;
36 }
37
38 const Public_Key* maybe_server_public_key() const { return m_server_public_key.get(); }
39
40 void record_server_public_key(std::unique_ptr<Public_Key> spk) {
41 BOTAN_STATE_CHECK(!m_server_public_key);
42 m_server_public_key = std::move(spk);
43 }
44
45 bool is_a_resumption() const { return m_resumed_session.has_value(); }
46
47 void discard_resumption_state() { m_resumed_session.reset(); }
48
49 void record_resumption_info(std::optional<Session> session_info) {
50 BOTAN_STATE_CHECK(!m_resumed_session.has_value());
51 m_resumed_session = std::move(session_info);
52 }
53
54 bool is_a_renegotiation() const { return m_is_reneg; }
55
56 void mark_as_renegotiation() { m_is_reneg = true; }
57
58 size_t note_hello_verify_request() { return ++m_hello_verify_requests; }
59
60 const secure_vector<uint8_t>& resume_master_secret() const {
61 BOTAN_STATE_CHECK(is_a_resumption());
62 return m_resumed_session->master_secret();
63 }
64
65 const std::vector<X509_Certificate>& resume_peer_certs() const {
66 BOTAN_STATE_CHECK(is_a_resumption());
67 return m_resumed_session->peer_certs();
68 }
69
70 bool resumed_session_supports_extended_master_secret() const {
71 BOTAN_STATE_CHECK(is_a_resumption());
72 return m_resumed_session->supports_extended_master_secret();
73 }
74
75 uint16_t resumed_session_ciphersuite_code() const {
76 BOTAN_STATE_CHECK(is_a_resumption());
77 return m_resumed_session->ciphersuite_code();
78 }
79
80 bool resumed_session_supports_encrypt_then_mac() const {
81 BOTAN_STATE_CHECK(is_a_resumption());
82 return m_resumed_session->supports_encrypt_then_mac();
83 }
84
85 uint16_t resumed_session_dtls_srtp_profile() const {
86 BOTAN_STATE_CHECK(is_a_resumption());
87 return m_resumed_session->dtls_srtp_profile();
88 }
89
90 std::vector<X509_Certificate> peer_cert_chain() const override {
91 if(is_a_resumption()) {
92 return resume_peer_certs();
93 }
94 if(has_server_certs()) {
95 return server_certs().cert_chain();
96 }
97 return {};
98 }
99
100 private:
101 std::unique_ptr<Public_Key> m_server_public_key;
102
103 // Used during session resumption
104 std::optional<Session> m_resumed_session;
105 bool m_is_reneg = false;
106 size_t m_hello_verify_requests = 0;
107};
108
109} // namespace
110
111std::shared_ptr<Client_Impl_12> Client_Impl_12::create(const std::shared_ptr<Callbacks>& callbacks,
112 const std::shared_ptr<Session_Manager>& session_manager,
113 const std::shared_ptr<Credentials_Manager>& creds,
114 const std::shared_ptr<const Policy>& policy,
115 const std::shared_ptr<RandomNumberGenerator>& rng,
116 Server_Information server_info,
118 const std::vector<std::string>& next_protocols,
119 size_t reserved_io_buffer_size) {
120 auto self = std::make_shared<Client_Impl_12>(Private{},
121 callbacks,
123 creds,
124 policy,
125 rng,
126 std::move(server_info),
127 flavor,
128 reserved_io_buffer_size);
129
130 BOTAN_ASSERT_NONNULL(self->m_creds);
131 const auto version = (flavor == TLS_Flavor::DTLS) ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
132 Handshake_State& state = self->create_handshake_state(version);
133 self->send_client_hello(state, false, version, std::nullopt /* no a-priori session to resume */, next_protocols);
134
135 return self;
136}
137
138#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT)
139
140std::shared_ptr<Client_Impl_12> Client_Impl_12::create_for_downgrade(
141 Channel_Impl::Downgrade_Information& downgrade_info) {
142 auto self = std::make_shared<Client_Impl_12>(Private{}, downgrade_info);
143
144 const auto version =
145 (downgrade_info.flavor == TLS_Flavor::DTLS) ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
146
147 if(downgrade_info.client_hello.has_value()) {
148 // Downgrade detected after receiving a (D)TLS 1.2 server hello. We need
149 // to recreate the state as if this implementation issued the client
150 // hello.
151
152 // For DTLS we have to initialize the record sequence numbers as
153 // transferred from the TLS 1.3 implementation.
154 BOTAN_ASSERT_IMPLICATION(downgrade_info.flavor == TLS_Flavor::DTLS,
155 downgrade_info.epoch0_sequence_numbers.has_value(),
156 "downgrading DTLS requires transferring the record sequence numbers");
157
158 // TODO(C++23): Use std::optional::and_then() instead
159 const auto seqno_read = [](const std::optional<Epoch0_SequenceNumbers>& seq) -> std::optional<uint64_t> {
160 if(seq.has_value()) {
161 return seq->read;
162 }
163 return std::nullopt;
164 };
165 const auto seqno_write = [](const std::optional<Epoch0_SequenceNumbers>& seq) -> std::optional<uint64_t> {
166 if(seq.has_value()) {
167 return seq->write;
168 }
169 return std::nullopt;
170 };
171
172 auto& state = self->create_handshake_state(version,
173 false /* no epoch0 restart */,
174 seqno_read(downgrade_info.epoch0_sequence_numbers),
175 seqno_write(downgrade_info.epoch0_sequence_numbers));
176
177 state.client_hello(std::make_unique<Client_Hello_12>(
178 std::exchange(downgrade_info.client_hello, {}).value(), state.handshake_io(), state.hash()));
179
180 self->secure_renegotiation_check(state.maybe_client_hello());
181 if(downgrade_info.flavor == TLS_Flavor::DTLS) {
182 state.set_expected_next(Handshake_Type::HelloVerifyRequest); // optional
183 }
184 state.set_expected_next(Handshake_Type::ServerHello);
185 } else {
186 // Downgrade initiated after a (D)TLS 1.2 session was found. No communication
187 // has happened yet but the found session should be used for resumption.
188 BOTAN_ASSERT_NOMSG(downgrade_info.tls12_session.has_value() &&
189 downgrade_info.tls12_session->session.version().is_pre_tls_13());
190 BOTAN_ASSERT_NOMSG(downgrade_info.tls12_session->session.version().is_datagram_protocol() ==
191 (downgrade_info.flavor == TLS_Flavor::DTLS));
192
193 // When resuming based on an existing session, the (D)TLS 1.3
194 // implementation won't have emitted any data prior to the downgrade.
195 // Therefore, we can start with default sequence numbers.
196 auto& state = self->create_handshake_state(version);
197 self->send_client_hello(state,
198 false,
199 downgrade_info.tls12_session->session.version(),
200 downgrade_info.tls12_session,
201 downgrade_info.next_protocols);
202 }
203
204 return self;
205}
206
207#endif
208
209std::unique_ptr<Handshake_State> Client_Impl_12::new_handshake_state(std::unique_ptr<Handshake_IO> io) {
210 return std::make_unique<Client_Handshake_State_12>(std::move(io), callbacks());
211}
212
213/*
214* Send a new client hello to renegotiate
215*/
216void Client_Impl_12::initiate_handshake(Handshake_State& state, bool force_full_renegotiation) {
217 // we don't support TLS < 1.2 anymore and TLS 1.3 should not use this client impl
218 const auto version = state.version().is_datagram_protocol() ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
219 send_client_hello(state, force_full_renegotiation, version);
220}
221
222void Client_Impl_12::send_client_hello(Handshake_State& state_base,
223 bool force_full_renegotiation,
224 Protocol_Version version,
225 std::optional<Session_with_Handle> session_and_handle,
226 const std::vector<std::string>& next_protocols) {
227 Client_Handshake_State_12& state = dynamic_cast<Client_Handshake_State_12&>(state_base);
228
229 if(state.version().is_datagram_protocol()) {
230 state.set_expected_next(Handshake_Type::HelloVerifyRequest); // optional
231 }
232 state.set_expected_next(Handshake_Type::ServerHello);
233
234 if(!force_full_renegotiation) {
235 // if no session is provided, we need to try and find one opportunistically
236 if(!session_and_handle.has_value() && !m_info.empty()) {
237 if(auto sessions = session_manager().find(m_info, callbacks(), policy()); !sessions.empty()) {
238 session_and_handle = std::move(sessions.front());
239 }
240 }
241
242 if(session_and_handle.has_value()) {
243 /*
244 Ensure that the session protocol cipher and version are acceptable
245 If not skip the resume and establish a new session
246 */
247 auto& session_info = session_and_handle->session;
248 const bool exact_version = session_info.version() == version;
249 const bool ok_version = (session_info.version().is_datagram_protocol() == version.is_datagram_protocol()) &&
250 policy().acceptable_protocol_version(session_info.version());
251
252 const bool session_version_ok = policy().only_resume_with_exact_version() ? exact_version : ok_version;
253
254 // ciphersuite_list() throws if the policy allows no suite for the
255 // session's version, so check the version first
256 const bool session_suite_ok =
257 session_version_ok &&
258 value_exists(policy().ciphersuite_list(session_info.version()), session_info.ciphersuite_code());
259
260 // A session's DTLS-SRTP profile is re-offered on resumption, so it must still be acceptable
261 const bool session_srtp_ok = session_info.dtls_srtp_profile() == 0 ||
262 value_exists(policy().srtp_profiles(), session_info.dtls_srtp_profile());
263
264 if(session_suite_ok && session_srtp_ok) {
265 try {
266 state.client_hello(std::make_unique<Client_Hello_12>(state.handshake_io(),
267 state.hash(),
268 policy(),
269 callbacks(),
270 rng(),
272 session_and_handle.value(),
273 next_protocols));
274
275 state.record_resumption_info(std::move(session_info));
276
277 // RFC 5246 7.2.2
278 // Thus, any connection terminated with a fatal alert MUST NOT
279 // be resumed.
280 //
281 // Make sure the offered session is forgotten if this fails
282 if(!active_state().has_value()) {
283 note_resumption_handle(session_and_handle->handle);
284 }
285 } catch(Encoding_Error&) {
286 // The session's ticket cannot be encoded into the ClientHello
287 // (likely it is too large to fit; nothing was sent yet). It can
288 // never be used, so forget about it and perform a full handshake.
289 session_manager().remove(session_and_handle->handle);
290 }
291 }
292 }
293 }
294
295 if(!state.has_client_hello()) {
296 // not resuming
297 const Client_Hello_12::Settings client_settings(version, m_info.hostname());
298 state.client_hello(std::make_unique<Client_Hello_12>(state.handshake_io(),
299 state.hash(),
300 policy(),
301 callbacks(),
302 rng(),
304 client_settings,
305 next_protocols));
306 }
307
308 secure_renegotiation_check(state.maybe_client_hello());
309
310 // We just sent our first message that might get lost in transit. Hence, we
311 // kick-off a retransmission timer chain for users that implement the
312 // asynchronous timer callback introduced in Botan 3.14.0.
314}
315
316namespace {
317
318// RFC 5246 7.4.2
319// the certificate MUST allow the key to be used for encryption (the
320// keyEncipherment bit MUST be set if the key usage extension is present)
321// [...]
322// the certificate MUST allow the key to be used for signing (the
323// digitalSignature bit MUST be set if the key usage extension is present)
324bool key_usage_matches_ciphersuite(Key_Constraints usage, const Ciphersuite& suite) {
325 if(usage == Key_Constraints::None) {
326 return true; // anything goes ...
327 }
328
329 if(suite.kex_method() == Kex_Algo::STATIC_RSA) {
330 return usage.includes(Key_Constraints::KeyEncipherment);
331 } else {
332 return usage.includes(Key_Constraints::DigitalSignature);
333 }
334}
335
336} // namespace
337
338/*
339* Process a handshake message
340*/
341void Client_Impl_12::process_handshake_msg(Handshake_State& state_base,
342 Handshake_Type type,
343 const std::vector<uint8_t>& contents,
344 bool epoch0_restart) {
345 BOTAN_ASSERT_NOMSG(epoch0_restart == false); // only happens on server side
346
347 Client_Handshake_State_12& state = dynamic_cast<Client_Handshake_State_12&>(state_base);
348
349 if(type == Handshake_Type::HelloRequest && active_state().has_value()) {
350 const Hello_Request hello_request(contents);
351
352 // RFC 5246 Section 7.4.1.1
353 // This message will be ignored by the client if the client is
354 // currently negotiating a session.
355 if(state.has_client_hello()) {
356 return;
357 }
358
359 if(policy().allow_server_initiated_renegotiation()) {
360 if(secure_renegotiation_supported() || policy().allow_insecure_renegotiation()) {
361 state.mark_as_renegotiation();
362 initiate_handshake(state, true /* force_full_renegotiation */);
363 } else {
364 throw TLS_Exception(Alert::HandshakeFailure, "Client policy prohibits insecure renegotiation");
365 }
366 } else {
367 if(policy().abort_connection_on_undesired_renegotiation()) {
368 throw TLS_Exception(Alert::NoRenegotiation, "Client policy prohibits renegotiation");
369 } else {
370 // RFC 5746 section 4.2
371 send_warning_alert(Alert::NoRenegotiation);
372 }
373 }
374
375 return;
376 }
377
378 state.confirm_transition_to(type);
379
382 state.hash().update(state.handshake_io().format(contents, type));
383 }
384
386 // RFC 6347 4.2.1 requires tolerating more than one: "This may result in
387 // clients receiving multiple HelloVerifyRequest messages with different
388 // cookies. Clients SHOULD handle this by sending a new ClientHello with a
389 // cookie in response to the new HelloVerifyRequest."
390 //
391 // Each one makes us re-send the ClientHello, and a HelloVerifyRequest is
392 // unauthenticated epoch-zero data that resets the retransmission counter,
393 // so an unbounded stream of forged ones would have us flood the server
394 // indefinitely. Bound how many we will act on.
395 const size_t hello_verify_requests = state.note_hello_verify_request();
396 const std::optional<size_t> max_hello_verify_requests = policy().dtls_maximum_hello_verify_requests();
397
398 if(max_hello_verify_requests.has_value() && hello_verify_requests > max_hello_verify_requests.value()) {
399 throw TLS_Exception(Alert::UnexpectedMessage, "Too many DTLS HelloVerifyRequest messages");
400 }
401
402 state.set_expected_next(Handshake_Type::ServerHello);
403 state.set_expected_next(Handshake_Type::HelloVerifyRequest); // might get it again
404
405 const Hello_Verify_Request hello_verify_request(contents);
406 state.hello_verify_request(hello_verify_request);
407
408 // Cookie ClientHello is a new outgoing flight with a fresh deadline.
410 } else if(type == Handshake_Type::ServerHello) {
411 state.server_hello(std::make_unique<Server_Hello_12>(contents));
412
413 if(!state.server_hello().legacy_version().valid()) {
414 throw TLS_Exception(Alert::ProtocolVersion, "Server replied with an invalid version");
415 }
416
417 if(state.client_hello().legacy_version().is_datagram_protocol() !=
418 state.server_hello().legacy_version().is_datagram_protocol()) {
419 throw TLS_Exception(Alert::ProtocolVersion, "Server replied with different protocol type than we offered");
420 }
421
422 if(!state.client_hello().offered_suite(state.server_hello().ciphersuite())) {
423 throw TLS_Exception(Alert::HandshakeFailure, "Server replied with ciphersuite we didn't send");
424 }
425
426 const auto suite = Ciphersuite::by_id(state.server_hello().ciphersuite());
427 if(!suite || !suite->usable_in_version(state.server_hello().legacy_version())) {
428 throw TLS_Exception(Alert::HandshakeFailure,
429 "Server replied using a ciphersuite not allowed in version it offered");
430 }
431
432 // RFC 7366 3.:
433 // If a server receives an encrypt-then-MAC request extension from a client
434 // and then selects a stream or Authenticated Encryption with Associated
435 // Data (AEAD) ciphersuite, it MUST NOT send an encrypt-then-MAC
436 // response extension back to the client.
437 if(!suite->cbc_ciphersuite() && state.server_hello().supports_encrypt_then_mac()) {
438 throw TLS_Exception(Alert::IllegalParameter,
439 "Server replied using a non-CBC ciphersuite and an encrypt-then-MAC response extension");
440 }
441
442 if(Ciphersuite::is_scsv(state.server_hello().ciphersuite())) {
443 throw TLS_Exception(Alert::HandshakeFailure, "Server replied with a signaling ciphersuite");
444 }
445
446 if(state.server_hello().compression_method() != 0) {
447 throw TLS_Exception(Alert::IllegalParameter, "Server replied with non-null compression method");
448 }
449
450 const auto downgrade_signal = state.server_hello().random_signals_downgrade();
451 if(downgrade_signal.has_value()) {
452 // RFC 9846 4.2.3.:
453 // TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or
454 // below MUST check that the last 8 bytes are not equal to either of
455 // [the magic downgrade values].
456 //
457 // If `random_signals_downgrade()` returns any value, then the server
458 // is signaling a downgrade to TLS 1.2 or below.
459 if(state.client_hello().offered_tls13()) {
460 throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected");
461 }
462
463 // RFC 9846 4.2.3.:
464 // TLS 1.2 clients SHOULD also check that the last 8 bytes are not
465 // equal to the [magic value DOWNGRADE_TLS11] if the ServerHello
466 // indicates TLS 1.1 or below.
467 //
468 // Technically, this is dead code because we don't support TLS 1.1 or
469 // below anymore, but we keep it for completeness and to avoid future
470 // regressions.
471 if(state.client_hello().legacy_version() > state.server_hello().legacy_version() &&
472 downgrade_signal.value() <= Protocol_Version::TLS_V11) {
473 throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected");
474 }
475 }
476
477 const auto client_extn = state.client_hello().extension_types();
478 const auto server_extn = state.server_hello().extension_types();
479
480 std::vector<Extension_Code> diff;
481
482 std::set_difference(
483 server_extn.begin(), server_extn.end(), client_extn.begin(), client_extn.end(), std::back_inserter(diff));
484
485 if(!diff.empty()) {
486 // Server sent us back an extension we did not send!
487
488 std::ostringstream msg;
489 msg << "Server replied with unsupported extensions:";
490 for(auto&& d : diff) {
491 msg << " " << static_cast<int>(d);
492 }
493 throw TLS_Exception(Alert::UnsupportedExtension, msg.str());
494 }
495
496 if(const uint16_t srtp = state.server_hello().srtp_profile()) {
497 if(!value_exists(state.client_hello().srtp_profiles(), srtp)) {
498 throw TLS_Exception(Alert::HandshakeFailure, "Server replied with DTLS-SRTP alg we did not send");
499 }
500 }
501
503 state.server_hello().extensions(), Connection_Side::Server, Handshake_Type::ServerHello);
504
505 state.set_version(state.server_hello().legacy_version());
506
507 if(state.server_hello().extensions().has<Application_Layer_Protocol_Notification>()) {
508 const auto* server_alpn = state.server_hello().extensions().get<Application_Layer_Protocol_Notification>();
509 const auto selected = server_alpn->single_protocol();
510 const auto* client_alpn = state.client_hello().extensions().get<Application_Layer_Protocol_Notification>();
511 BOTAN_ASSERT_NONNULL(client_alpn);
512 const auto& offered = client_alpn->protocols();
513 if(!value_exists(offered, selected)) {
514 throw TLS_Exception(Alert::IllegalParameter, "Server selected an ALPN protocol not offered by the client");
515 }
516 }
517 if(active_state().has_value() && !state.client_hello().supports_alpn()) {
518 // The application protocol is a property of the connection, which a
519 // renegotiation that does not offer ALPN does not change. If it was
520 // offered, the server cleared its protocol unless it selected one.
521 m_application_protocol = active_state()->application_protocol();
522 } else {
523 m_application_protocol = state.server_hello().next_protocol();
524 }
525
526 secure_renegotiation_check(state.maybe_server_hello());
527
528 // RFC 7627 / RFC 9325 4.4: optionally require Extended Master Secret.
529 if(policy().require_extended_master_secret() && !state.server_hello().supports_extended_master_secret()) {
530 throw TLS_Exception(Alert::HandshakeFailure,
531 "Policy requires the Extended Master Secret extension but the server did not send it");
532 }
533
534 const bool server_returned_same_session_id =
535 !state.server_hello().session_id().empty() &&
536 (state.server_hello().session_id() == state.client_hello().session_id());
537
538 if(server_returned_same_session_id) {
539 // successful resumption
540 BOTAN_ASSERT_NOMSG(state.is_a_resumption());
541
542 /*
543 * In this case, we offered the version used in the original
544 * session, and the server must resume with the same version.
545 */
546 if(state.server_hello().legacy_version() != state.client_hello().legacy_version()) {
547 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but with wrong version");
548 }
549
550 // RFC 5246 7.4.1.2: when resuming a session, the server MUST use
551 // the same cipher suite that was negotiated in the original session.
552 if(state.server_hello().ciphersuite() != state.resumed_session_ciphersuite_code()) {
553 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session with a different ciphersuite");
554 }
555
556 if(state.server_hello().supports_extended_master_secret() &&
557 !state.resumed_session_supports_extended_master_secret()) {
558 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but added extended master secret");
559 }
560
561 if(!state.server_hello().supports_extended_master_secret() &&
562 state.resumed_session_supports_extended_master_secret()) {
563 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session and removed extended master secret");
564 }
565
566 // RFC 7366 3.1
567 // implementations MUST NOT renegotiate a downgrade from
568 // encrypt-then-MAC to MAC-then-encrypt.
569 if(state.server_hello().supports_encrypt_then_mac() != state.resumed_session_supports_encrypt_then_mac()) {
570 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but changed encrypt-then-MAC");
571 }
572
573 if(state.server_hello().srtp_profile() != state.resumed_session_dtls_srtp_profile()) {
574 throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but changed the DTLS-SRTP profile");
575 }
576
577 state.compute_session_keys(state.resume_master_secret());
578 if(policy().allow_ssl_key_log_file()) {
579 // draft-thomson-tls-keylogfile-00 Section 3.2
580 // An implementation of TLS 1.2 (and also earlier versions) use
581 // the label "CLIENT_RANDOM" to identify the "master" secret for
582 // the connection.
584 "CLIENT_RANDOM", state.client_hello().random(), state.session_keys().master_secret());
585 }
586
587 if(state.server_hello().supports_session_ticket()) {
588 state.set_expected_next(Handshake_Type::NewSessionTicket);
589 } else {
590 state.set_expected_next(Handshake_Type::HandshakeCCS);
591 }
592 } else {
593 // new session
594
595 if(active_state().has_value()) {
596 // Here we are testing things that should not change during a renegotiation,
597 // even if the server creates a new session. However they might change
598 // in a resumption scenario.
599
600 if(active_state()->version() != state.server_hello().legacy_version()) {
601 throw TLS_Exception(Alert::ProtocolVersion, "Server changed version after renegotiation");
602 }
603
604 if(state.server_hello().supports_extended_master_secret() !=
605 active_state()->supports_extended_master_secret()) {
606 throw TLS_Exception(Alert::HandshakeFailure, "Server changed its mind about extended master secret");
607 }
608 }
609
610 state.discard_resumption_state();
611
612 if(state.version() > state.client_hello().legacy_version()) {
613 throw TLS_Exception(Alert::HandshakeFailure, "Server replied with later version than client offered");
614 }
615
616 if(state.version().major_version() == 3 && state.version().minor_version() == 0) {
617 throw TLS_Exception(Alert::ProtocolVersion, "Server attempting to negotiate SSLv3 which is not supported");
618 }
619
620 if(!policy().acceptable_protocol_version(state.version())) {
621 throw TLS_Exception(Alert::ProtocolVersion,
622 "Server version " + state.version().to_string() + " is unacceptable by policy");
623 }
624
625 if(state.ciphersuite().is_certificate_required()) {
626 state.set_expected_next(Handshake_Type::Certificate);
627 } else if(state.ciphersuite().kex_method() == Kex_Algo::PSK) {
628 /* PSK is anonymous so no certificate/cert req message is
629 ever sent. The server may or may not send a server kex,
630 depending on if it has an identity hint for us.
631
632 (EC)DHE_PSK always sends a server key exchange for the
633 DH exchange portion, and is covered by block below
634 */
635
636 state.set_expected_next(Handshake_Type::ServerKeyExchange);
637 state.set_expected_next(Handshake_Type::ServerHelloDone);
638 } else {
639 // ECDHE_PSK ServerKeyExchange carries the ECDH parameters and
640 // immediately follows ServerHello.
641 //
642 // Suites using RSA key exchange or signature-authenticated ECDH
643 // were already routed to expect Certificate above.
644 state.set_expected_next(Handshake_Type::ServerKeyExchange);
645 }
646 }
647 } else if(type == Handshake_Type::Certificate) {
648 state.server_certs(std::make_unique<Certificate_12>(contents, policy()));
649
650 const std::vector<X509_Certificate>& server_certs = state.server_certs().cert_chain();
651
652 if(server_certs.empty()) {
653 throw TLS_Exception(Alert::HandshakeFailure, "Client: No certificates sent by server");
654 }
655
656 /*
657 If the server supports certificate status messages,
658 certificate verification happens after we receive the server hello done,
659 in case an OCSP response was also available
660 */
661
662 const X509_Certificate server_cert = server_certs[0];
663
664 if(active_state().has_value() && !active_state()->peer_certs().empty()) {
665 const X509_Certificate& current_cert = active_state()->peer_certs().at(0);
666
667 if(current_cert != server_cert) {
668 throw TLS_Exception(Alert::BadCertificate, "Server certificate changed during renegotiation");
669 }
670 }
671
672 auto peer_key = server_cert.subject_public_key();
673
674 const std::string expected_key_type =
675 state.ciphersuite().signature_used() ? state.ciphersuite().sig_algo() : "RSA";
676
677 if(peer_key->algo_name() != expected_key_type) {
678 throw TLS_Exception(Alert::IllegalParameter, "Certificate key type did not match ciphersuite");
679 }
680
681 if(!key_usage_matches_ciphersuite(server_cert.constraints(), state.ciphersuite())) {
682 throw TLS_Exception(Alert::BadCertificate, "Certificate usage constraints do not allow this ciphersuite");
683 }
684
685 // With a signing key this is also checked once the ServerKeyExchange
686 // signature is verified, but for RSA key exchange this is the only place
688
689 state.record_server_public_key(std::move(peer_key));
690
691 if(state.ciphersuite().kex_method() != Kex_Algo::STATIC_RSA) {
692 state.set_expected_next(Handshake_Type::ServerKeyExchange);
693 } else {
694 state.set_expected_next(Handshake_Type::CertificateRequest); // optional
695 state.set_expected_next(Handshake_Type::ServerHelloDone);
696 }
697
698 if(state.server_hello().supports_certificate_status_message()) {
699 state.set_expected_next(Handshake_Type::CertificateStatus); // optional
700 } else {
701 try {
702 const auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-client", m_info.hostname());
703
705 server_certs, {}, trusted_CAs, Usage_Type::TLS_SERVER_AUTH, m_info.hostname(), policy());
706 } catch(TLS_Exception&) {
707 throw;
708 } catch(std::exception& e) {
709 throw TLS_Exception(Alert::InternalError, e.what());
710 }
711 }
712 } else if(type == Handshake_Type::CertificateStatus) {
713 state.server_cert_status(std::make_unique<Certificate_Status>(contents, Connection_Side::Server));
714
715 if(state.ciphersuite().kex_method() != Kex_Algo::STATIC_RSA) {
716 state.set_expected_next(Handshake_Type::ServerKeyExchange);
717 } else {
718 state.set_expected_next(Handshake_Type::CertificateRequest); // optional
719 state.set_expected_next(Handshake_Type::ServerHelloDone);
720 }
721 } else if(type == Handshake_Type::ServerKeyExchange) {
722 if(!state.ciphersuite().psk_ciphersuite()) {
723 state.set_expected_next(Handshake_Type::CertificateRequest); // optional
724 }
725 state.set_expected_next(Handshake_Type::ServerHelloDone);
726
727 state.server_kex(std::make_unique<Server_Key_Exchange>(
728 contents, state.ciphersuite().kex_method(), state.ciphersuite().auth_method(), state.version()));
729
730 if(state.ciphersuite().signature_used()) {
731 const Public_Key& server_key = state.server_public_key();
732
733 if(!state.server_kex().verify(server_key, state, policy())) {
734 throw TLS_Exception(Alert::DecryptError, "Bad signature on server key exchange");
735 }
736 }
737 } else if(type == Handshake_Type::CertificateRequest) {
738 state.set_expected_next(Handshake_Type::ServerHelloDone);
739 state.cert_req(std::make_unique<Certificate_Request_12>(contents));
740 } else if(type == Handshake_Type::ServerHelloDone) {
741 state.server_hello_done(std::make_unique<Server_Hello_Done>(contents));
742
743 if(state.handshake_io().have_more_data()) {
744 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after ServerHelloDone");
745 }
746
747 if(state.has_server_certs() && state.server_hello().supports_certificate_status_message()) {
748 try {
749 const auto trusted_CAs = m_creds->trusted_certificate_authorities("tls-client", m_info.hostname());
750
751 std::vector<std::optional<OCSP::Response>> ocsp;
752 if(state.has_server_cert_status()) {
753 ocsp.emplace_back(callbacks().tls_parse_ocsp_response(state.server_cert_status().response()));
754 }
755
756 callbacks().tls_verify_cert_chain(state.server_certs().cert_chain(),
757 ocsp,
758 trusted_CAs,
760 m_info.hostname(),
761 policy());
762 } catch(TLS_Exception&) {
763 throw;
764 } catch(std::exception& e) {
765 throw TLS_Exception(Alert::InternalError, e.what());
766 }
767 }
768
769 if(state.received_handshake_msg(Handshake_Type::CertificateRequest)) {
770 const auto& cert_req = state.cert_req();
771
772 // RFC 5246 7.4.4
773 // - Any certificates provided by the client MUST be signed using a
774 // hash/signature algorithm pair found in supported_signature_algorithms.
775 //
776 // - The end-entity certificate provided by the client MUST contain a
777 // key that is compatible with certificate_types. If the key is a
778 // signature key, it MUST be usable with some hash/signature
779 // algorithm pair in supported_signature_algorithms.
780 //
781 // TLS 1.2 has no signature_algorithms_cert analog, so the one list
782 // constrains both.
783 const auto usable_key_types = filter_signature_schemes(cert_req.signature_schemes(), state.version());
784
785 std::vector<std::string> key_types;
786 for(const auto& cert_type : cert_req.acceptable_cert_types()) {
787 if(value_exists(usable_key_types, cert_type)) {
788 key_types.push_back(cert_type);
789 }
790 }
791
792 // RFC 5246 7.4.6
793 // If no suitable certificate is available, the client MUST send a
794 // certificate message containing no certificates.
795 //
796 // An empty list of key types would mean "no preference" to the
797 // credentials manager, so it is not asked at all.
798 std::vector<X509_Certificate> client_certs;
799 if(!key_types.empty()) {
800 client_certs = m_creds->find_cert_chain(key_types,
801 to_algorithm_identifiers(cert_req.signature_schemes()),
802 cert_req.acceptable_CAs(),
803 "tls-client",
804 m_info.hostname());
805 }
806
807 state.client_certs(std::make_unique<Certificate_12>(state.handshake_io(), state.hash(), client_certs));
808 }
809
810 state.client_kex(std::make_unique<Client_Key_Exchange>(
811 state.handshake_io(), state, policy(), *m_creds, state.maybe_server_public_key(), m_info.hostname(), rng()));
812
813 state.compute_session_keys();
814 if(policy().allow_ssl_key_log_file()) {
815 // draft-thomson-tls-keylogfile-00 Section 3.2
816 // An implementation of TLS 1.2 (and also earlier versions) use
817 // the label "CLIENT_RANDOM" to identify the "master" secret for
818 // the connection.
820 "CLIENT_RANDOM", state.client_hello().random(), state.session_keys().master_secret());
821 }
822
823 if(state.received_handshake_msg(Handshake_Type::CertificateRequest) && !state.client_certs().empty()) {
824 const auto private_key =
825 m_creds->private_key_for(state.client_certs().cert_chain()[0], "tls-client", m_info.hostname());
826
827 if(!private_key) {
828 throw TLS_Exception(Alert::InternalError, "Failed to get private key for signing");
829 }
830
831 state.client_verify(
832 std::make_unique<Certificate_Verify_12>(state.handshake_io(), state, policy(), rng(), private_key.get()));
833 }
834
835 state.handshake_io().send(Change_Cipher_Spec());
836
838
839 state.client_finished(std::make_unique<Finished_12>(state.handshake_io(), state, Connection_Side::Client));
840
841 // Flight is complete, we're now waiting for the peer to respond or for
842 // our timer to cause a retransmission.
844
845 if(state.server_hello().supports_session_ticket()) {
846 state.set_expected_next(Handshake_Type::NewSessionTicket);
847 } else {
848 state.set_expected_next(Handshake_Type::HandshakeCCS);
849 }
850 } else if(type == Handshake_Type::NewSessionTicket) {
851 state.new_session_ticket(std::make_unique<New_Session_Ticket_12>(contents));
852
853 state.set_expected_next(Handshake_Type::HandshakeCCS);
854 } else if(type == Handshake_Type::HandshakeCCS) {
855 state.set_expected_next(Handshake_Type::Finished);
856
858 } else if(type == Handshake_Type::Finished) {
859 if(state.handshake_io().have_more_data()) {
860 throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after Finished");
861 }
862
863 state.server_finished(std::make_unique<Finished_12>(contents));
864
865 if(!state.server_finished().verify(state, Connection_Side::Server)) {
866 throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify");
867 }
868
869 state.hash().update(state.handshake_io().format(contents, type));
870
871 if(!state.has_client_finished()) {
872 // session resume case
873 state.handshake_io().send(Change_Cipher_Spec());
875 state.client_finished(std::make_unique<Finished_12>(state.handshake_io(), state, Connection_Side::Client));
876 }
877
878 // Session Tickets (as defined in RFC 5077) contain a lifetime_hint,
879 // sessions identified via a Session_ID do not.
880 const std::chrono::seconds session_lifetime_hint = [&] {
881 if(state.has_new_session_ticket()) {
882 return std::chrono::seconds(state.new_session_ticket().ticket_lifetime_hint());
883 } else {
884 return std::chrono::seconds::max();
885 }
886 }();
887
888 Session session_info(state.session_keys().master_secret(),
889 state.server_hello().legacy_version(),
890 state.server_hello().ciphersuite(),
892 state.server_hello().supports_extended_master_secret(),
893 state.server_hello().supports_encrypt_then_mac(),
894 state.peer_cert_chain(),
895 m_info,
896 state.server_hello().srtp_profile(),
897 callbacks().tls_current_timestamp(),
898 session_lifetime_hint);
899
900 // RFC 5077 3.4
901 // If the client receives a session ticket from the server, then it
902 // discards any Session ID that was sent in the ServerHello.
903 const auto handle = [&]() -> std::optional<Session_Handle> {
904 /*
905 On successful resumption an empty (or absent) NewSessionTicket means "keep using
906 the old ticket" so we inherit it from the ClientHello. On a fresh negotiation
907 an empty NewSessionTicket means "no ticket for this session", so inheriting the
908 ClientHello's old ticket would store the new master secret under a ticket the
909 server has discarded.
910 */
911 if(const auto* nst = state.maybe_new_session_ticket(); nst != nullptr && !nst->ticket().empty()) {
912 return Session_Handle(nst->ticket());
913 }
914 if(state.is_a_resumption() && !state.client_hello().session_ticket().empty()) {
915 return Session_Handle(state.client_hello().session_ticket());
916 }
917 if(const auto& session_id = state.server_hello().session_id(); !session_id.empty()) {
918 return Session_Handle(session_id);
919 }
920 return std::nullopt;
921 }();
922
923 // Give the application a chance for a final veto before fully
924 // establishing the connection.
926 Session_Summary summary(session_info, state.is_a_resumption(), state.psk_identity());
927 summary.set_session_id(state.server_hello().session_id());
928 if(const auto* nst = state.maybe_new_session_ticket()) {
929 summary.set_session_ticket(nst->ticket());
930 }
931 return summary;
932 }());
933
934 if(handle.has_value()) {
935 const bool should_save = callbacks().tls_should_persist_resumption_information(session_info);
936
937 // RFC 5077 3.3
938 // If the server successfully verifies the client's ticket, then it
939 // MAY renew the ticket by including a NewSessionTicket handshake
940 // message after the ServerHello in the abbreviated handshake. The
941 // client should start using the new ticket as soon as possible
942 // after it verifies the server's Finished message for new
943 // connections.
944 if(state.is_a_resumption() && !state.client_hello().session_ticket().empty() && handle->is_ticket() &&
945 should_save) {
946 // renew the session ticket by removing the one we used to establish
947 // this connection and replace it with the one we just received
948 session_manager().remove(Session_Handle(state.client_hello().session_ticket()));
949 session_manager().store(session_info, handle.value());
950 }
951
952 if(!state.is_a_resumption()) {
953 if(should_save) {
954 session_manager().store(session_info, handle.value());
955 } else {
956 session_manager().remove(handle.value());
957 }
958 } else if(!should_save) {
959 // The application does not want this session to be resumed again
960 session_manager().remove(handle.value());
961 if(!state.client_hello().session_ticket().empty()) {
962 session_manager().remove(Session_Handle(state.client_hello().session_ticket()));
963 }
964 }
965 }
966
968
970 } else {
971 throw Unexpected_Message("Unknown handshake message received");
972 }
973}
974
975} // namespace Botan::TLS
#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
#define BOTAN_ASSERT_IMPLICATION(expr1, expr2, msg)
Definition assert.h:108
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
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 bool tls_should_persist_resumption_information(const Session &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
RandomNumberGenerator & rng()
void change_cipher_spec_reader(Connection_Side side)
void maybe_arm_dtls_retransmission_timer(TimerGeneration generation_policy=TimerGeneration::Advance)
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)
std::vector< uint8_t > secure_renegotiation_data_for_client_hello() const
void secure_renegotiation_check(const Client_Hello_12 *client_hello, bool fresh_handshake_mode=false)
const std::optional< Active_Connection_State_12 > & active_state() const
bool secure_renegotiation_supported() const override
void send_warning_alert(Alert::Type type)
static bool is_scsv(uint16_t suite)
static std::optional< Ciphersuite > by_id(uint16_t suite)
static std::shared_ptr< Client_Impl_12 > 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(), TLS_Flavor flavor=TLS_Flavor::TLS, const std::vector< std::string > &next_protocols={}, size_t reserved_io_buffer_size=TLS::Channel::IO_BUF_DEFAULT_SIZE)
virtual void check_peer_key_acceptable(const Public_Key &public_key) const
virtual std::optional< size_t > dtls_maximum_hello_verify_requests() const
virtual bool only_resume_with_exact_version() const
virtual bool acceptable_protocol_version(Protocol_Version version) const
virtual size_t remove(const Session_Handle &handle)=0
virtual void store(const Session &session, const Session_Handle &handle)=0
Save a Session under a Session_Handle (TLS Client).
std::vector< AlgorithmIdentifier > to_algorithm_identifiers(const std::vector< Signature_Scheme > &schemes)
std::vector< std::string > filter_signature_schemes(const std::vector< Signature_Scheme > &schemes, const Protocol_Version &version)
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