Botan 3.9.0
Crypto and TLS for C&
msg_client_hello.cpp
Go to the documentation of this file.
1/*
2* TLS Hello Request and Client Hello Messages
3* (C) 2004-2011,2015,2016 Jack Lloyd
4* 2016 Matthias Gierlings
5* 2017 Harry Reimann, Rohde & Schwarz Cybersecurity
6* 2021 Elektrobit Automotive GmbH
7* 2022 René Meusel, Hannes Rantzsch - neXenio GmbH
8*
9* Botan is released under the Simplified BSD License (see license.txt)
10*/
11
12#include <botan/tls_messages.h>
13
14#include <botan/credentials_manager.h>
15#include <botan/hash.h>
16#include <botan/rng.h>
17#include <botan/tls_callbacks.h>
18#include <botan/tls_exceptn.h>
19#include <botan/tls_version.h>
20
21#include <botan/internal/parsing.h>
22#include <botan/internal/stl_util.h>
23#include <botan/internal/tls_handshake_hash.h>
24#include <botan/internal/tls_handshake_io.h>
25#include <botan/internal/tls_reader.h>
26#include <botan/internal/tls_session_key.h>
27
28#ifdef BOTAN_HAS_TLS_13
29 #include <botan/internal/tls_handshake_layer_13.h>
30 #include <botan/internal/tls_transcript_hash_13.h>
31#endif
32
33#include <chrono>
34#include <iterator>
35
36namespace Botan::TLS {
37
38std::vector<uint8_t> make_hello_random(RandomNumberGenerator& rng, Callbacks& cb, const Policy& policy) {
39 auto buf = rng.random_vec<std::vector<uint8_t>>(32);
40
41 if(policy.hash_hello_random()) {
42 auto sha256 = HashFunction::create_or_throw("SHA-256");
43 sha256->update(buf);
44 sha256->final(buf);
45 }
46
47 // TLS 1.3 does not require the insertion of a timestamp in the client hello
48 // random. When offering both TLS 1.2 and 1.3 we nevertheless comply with the
49 // legacy specification.
50 if(policy.include_time_in_hello_random() && (policy.allow_tls12() || policy.allow_dtls12())) {
51 const uint32_t time32 = static_cast<uint32_t>(std::chrono::system_clock::to_time_t(cb.tls_current_timestamp()));
52
53 store_be(time32, buf.data());
54 }
55
56 return buf;
57}
58
59/**
60 * Version-agnostic internal client hello data container that allows
61 * parsing Client_Hello messages without prior knowledge of the contained
62 * protocol version.
63 */
64class Client_Hello_Internal {
65 public:
66 Client_Hello_Internal() : m_comp_methods({0}) {}
67
68 explicit Client_Hello_Internal(const std::vector<uint8_t>& buf) {
69 if(buf.size() < 41) {
70 throw Decoding_Error("Client_Hello: Packet corrupted");
71 }
72
73 TLS_Data_Reader reader("ClientHello", buf);
74
75 const uint8_t major_version = reader.get_byte();
76 const uint8_t minor_version = reader.get_byte();
77
78 m_legacy_version = Protocol_Version(major_version, minor_version);
79 m_random = reader.get_fixed<uint8_t>(32);
80 m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
81
82 if(m_legacy_version.is_datagram_protocol()) {
83 auto sha256 = HashFunction::create_or_throw("SHA-256");
84 sha256->update(reader.get_data_read_so_far());
85
86 m_hello_cookie = reader.get_range<uint8_t>(1, 0, 255);
87
88 sha256->update(reader.get_remaining());
89 m_cookie_input_bits = sha256->final_stdvec();
90 }
91
92 m_suites = reader.get_range_vector<uint16_t>(2, 1, 32767);
93 m_comp_methods = reader.get_range_vector<uint8_t>(1, 1, 255);
94
95 m_extensions.deserialize(reader, Connection_Side::Client, Handshake_Type::ClientHello);
96 }
97
98 /**
99 * This distinguishes between a TLS 1.3 compliant Client Hello (containing
100 * the "supported_version" extension) and legacy Client Hello messages.
101 *
102 * @return TLS 1.3 if the Client Hello contains "supported_versions", or
103 * the content of the "legacy_version" version field if it
104 * indicates (D)TLS 1.2 or older, or
105 * (D)TLS 1.2 if the "legacy_version" was some other odd value.
106 */
107 Protocol_Version version() const {
108 // RFC 8446 4.2.1
109 // If [the "supported_versions"] extension is not present, servers
110 // which are compliant with this specification and which also support
111 // TLS 1.2 MUST negotiate TLS 1.2 or prior as specified in [RFC5246],
112 // even if ClientHello.legacy_version is 0x0304 or later.
113 //
114 // RFC 8446 4.2.1
115 // Servers MUST be prepared to receive ClientHellos that include
116 // [the supported_versions] extension but do not include 0x0304 in
117 // the list of versions.
118 //
119 // RFC 8446 4.1.2
120 // TLS 1.3 ClientHellos are identified as having a legacy_version of
121 // 0x0303 and a supported_versions extension present with 0x0304 as
122 // the highest version indicated therein.
123 if(!extensions().has<Supported_Versions>() ||
124 !extensions().get<Supported_Versions>()->supports(Protocol_Version::TLS_V13)) {
125 // The exact legacy_version is ignored we just inspect it to
126 // distinguish TLS and DTLS.
127 return (m_legacy_version.is_datagram_protocol()) ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12;
128 }
129
130 // Note: The Client_Hello_13 class will make sure that legacy_version
131 // is exactly 0x0303 (aka ossified TLS 1.2)
132 return Protocol_Version::TLS_V13;
133 }
134
135 Protocol_Version legacy_version() const { return m_legacy_version; }
136
137 const Session_ID& session_id() const { return m_session_id; }
138
139 const std::vector<uint8_t>& random() const { return m_random; }
140
141 const std::vector<uint16_t>& ciphersuites() const { return m_suites; }
142
143 const std::vector<uint8_t>& comp_methods() const { return m_comp_methods; }
144
145 const std::vector<uint8_t>& hello_cookie() const { return m_hello_cookie; }
146
147 const std::vector<uint8_t>& hello_cookie_input_bits() const { return m_cookie_input_bits; }
148
149 const Extensions& extensions() const { return m_extensions; }
150
151 Extensions& extensions() { return m_extensions; }
152
153 public:
154 Protocol_Version m_legacy_version; // NOLINT(*-non-private-member-variable*)
155 Session_ID m_session_id; // NOLINT(*-non-private-member-variable*)
156 std::vector<uint8_t> m_random; // NOLINT(*-non-private-member-variable*)
157 std::vector<uint16_t> m_suites; // NOLINT(*-non-private-member-variable*)
158 std::vector<uint8_t> m_comp_methods; // NOLINT(*-non-private-member-variable*)
159 Extensions m_extensions; // NOLINT(*-non-private-member-variable*)
160
161 // These fields are only for DTLS:
162 std::vector<uint8_t> m_hello_cookie; // NOLINT(*-non-private-member-variable*)
163 std::vector<uint8_t> m_cookie_input_bits; // NOLINT(*-non-private-member-variable*)
164};
165
166Client_Hello::Client_Hello(Client_Hello&&) noexcept = default;
167Client_Hello& Client_Hello::operator=(Client_Hello&&) noexcept = default;
168
169Client_Hello::~Client_Hello() = default;
170
171Client_Hello::Client_Hello() : m_data(std::make_unique<Client_Hello_Internal>()) {}
172
173/*
174* Read a counterparty client hello
175*/
176Client_Hello::Client_Hello(std::unique_ptr<Client_Hello_Internal> data) : m_data(std::move(data)) {
178}
179
183
185 return m_data->legacy_version();
186}
187
188const std::vector<uint8_t>& Client_Hello::random() const {
189 return m_data->random();
190}
191
193 return m_data->session_id();
194}
195
196const std::vector<uint8_t>& Client_Hello::compression_methods() const {
197 return m_data->comp_methods();
198}
199
200const std::vector<uint16_t>& Client_Hello::ciphersuites() const {
201 return m_data->ciphersuites();
202}
203
204std::set<Extension_Code> Client_Hello::extension_types() const {
205 return m_data->extensions().extension_types();
206}
207
209 return m_data->extensions();
210}
211
213 BOTAN_STATE_CHECK(m_data->legacy_version().is_datagram_protocol());
214
215 m_data->m_hello_cookie = hello_verify.cookie();
216}
217
218/*
219* Serialize a Client Hello message
220*/
221std::vector<uint8_t> Client_Hello::serialize() const {
222 std::vector<uint8_t> buf;
223 buf.reserve(1024); // working around GCC warning
224
225 buf.push_back(m_data->legacy_version().major_version());
226 buf.push_back(m_data->legacy_version().minor_version());
227 buf += m_data->random();
228
229 append_tls_length_value(buf, m_data->session_id().get(), 1);
230
231 if(m_data->legacy_version().is_datagram_protocol()) {
232 append_tls_length_value(buf, m_data->hello_cookie(), 1);
233 }
234
235 append_tls_length_value(buf, m_data->ciphersuites(), 2);
236 append_tls_length_value(buf, m_data->comp_methods(), 1);
237
238 /*
239 * May not want to send extensions at all in some cases. If so,
240 * should include SCSV value (if reneg info is empty, if not we are
241 * renegotiating with a modern server)
242 */
243
244 buf += m_data->extensions().serialize(Connection_Side::Client);
245
246 return buf;
247}
248
249std::vector<uint8_t> Client_Hello::cookie_input_data() const {
250 BOTAN_STATE_CHECK(!m_data->hello_cookie_input_bits().empty());
251
252 return m_data->hello_cookie_input_bits();
253}
254
255/*
256* Check if we offered this ciphersuite
257*/
258bool Client_Hello::offered_suite(uint16_t ciphersuite) const {
259 return std::find(m_data->ciphersuites().cbegin(), m_data->ciphersuites().cend(), ciphersuite) !=
260 m_data->ciphersuites().cend();
261}
262
263std::vector<Signature_Scheme> Client_Hello::signature_schemes() const {
264 if(Signature_Algorithms* sigs = m_data->extensions().get<Signature_Algorithms>()) {
265 return sigs->supported_schemes();
266 }
267 return {};
268}
269
270std::vector<Signature_Scheme> Client_Hello::certificate_signature_schemes() const {
271 // RFC 8446 4.2.3
272 // If no "signature_algorithms_cert" extension is present, then the
273 // "signature_algorithms" extension also applies to signatures appearing
274 // in certificates.
275 if(Signature_Algorithms_Cert* sigs = m_data->extensions().get<Signature_Algorithms_Cert>()) {
276 return sigs->supported_schemes();
277 } else {
278 return signature_schemes();
279 }
280}
281
282std::vector<Group_Params> Client_Hello::supported_ecc_curves() const {
283 if(Supported_Groups* groups = m_data->extensions().get<Supported_Groups>()) {
284 return groups->ec_groups();
285 }
286 return {};
287}
288
289std::vector<Group_Params> Client_Hello::supported_dh_groups() const {
290 if(Supported_Groups* groups = m_data->extensions().get<Supported_Groups>()) {
291 return groups->dh_groups();
292 }
293 return std::vector<Group_Params>();
294}
295
297 if(Supported_Point_Formats* ecc_formats = m_data->extensions().get<Supported_Point_Formats>()) {
298 return ecc_formats->prefers_compressed();
299 }
300 return false;
301}
302
303std::string Client_Hello::sni_hostname() const {
304 if(Server_Name_Indicator* sni = m_data->extensions().get<Server_Name_Indicator>()) {
305 return sni->host_name();
306 }
307 return "";
308}
309
311 return m_data->extensions().has<Renegotiation_Extension>();
312}
313
314std::vector<uint8_t> Client_Hello_12::renegotiation_info() const {
315 if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
316 return reneg->renegotiation_info();
317 }
318 return {};
319}
320
321std::vector<Protocol_Version> Client_Hello::supported_versions() const {
322 if(Supported_Versions* versions = m_data->extensions().get<Supported_Versions>()) {
323 return versions->versions();
324 }
325 return {};
326}
327
329 return m_data->extensions().has<Session_Ticket_Extension>();
330}
331
333 if(auto* ticket = m_data->extensions().get<Session_Ticket_Extension>()) {
334 return ticket->contents();
335 }
336 return {};
337}
338
339std::optional<Session_Handle> Client_Hello_12::session_handle() const {
340 // RFC 5077 3.4
341 // If a ticket is presented by the client, the server MUST NOT attempt
342 // to use the Session ID in the ClientHello for stateful session
343 // resumption.
344 if(auto ticket = session_ticket(); !ticket.empty()) {
345 return Session_Handle(ticket);
346 } else if(const auto& id = session_id(); !id.empty()) {
347 return Session_Handle(id);
348 } else {
349 return std::nullopt;
350 }
351}
352
354 return m_data->extensions().has<Application_Layer_Protocol_Notification>();
355}
356
358 return m_data->extensions().has<Extended_Master_Secret>();
359}
360
362 return m_data->extensions().has<Certificate_Status_Request>();
363}
364
366 return m_data->extensions().has<Encrypt_then_MAC>();
367}
368
370 return m_data->extensions().has<Signature_Algorithms>();
371}
372
373std::vector<std::string> Client_Hello::next_protocols() const {
374 if(auto* alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
375 return alpn->protocols();
376 }
377 return {};
378}
379
380std::vector<uint16_t> Client_Hello::srtp_profiles() const {
381 if(SRTP_Protection_Profiles* srtp = m_data->extensions().get<SRTP_Protection_Profiles>()) {
382 return srtp->profiles();
383 }
384 return {};
385}
386
387const std::vector<uint8_t>& Client_Hello::cookie() const {
388 return m_data->hello_cookie();
389}
390
391/*
392* Create a new Hello Request message
393*/
397
398/*
399* Deserialize a Hello Request message
400*/
401Hello_Request::Hello_Request(const std::vector<uint8_t>& buf) {
402 if(!buf.empty()) {
403 throw Decoding_Error("Bad Hello_Request, has non-zero size");
404 }
405}
406
407/*
408* Serialize a Hello Request message
409*/
410std::vector<uint8_t> Hello_Request::serialize() const {
411 return std::vector<uint8_t>();
412}
413
414void Client_Hello_12::add_tls12_supported_groups_extensions(const Policy& policy) {
415 // RFC 7919 3.
416 // A client that offers a group MUST be able and willing to perform a DH
417 // key exchange using that group.
418 //
419 // We don't support hybrid key exchange in TLS 1.2
420 const std::vector<Group_Params> kex_groups = policy.key_exchange_groups();
421 std::vector<Group_Params> compatible_kex_groups;
422 std::copy_if(kex_groups.begin(), kex_groups.end(), std::back_inserter(compatible_kex_groups), [](const auto group) {
423 return !group.is_post_quantum();
424 });
425
426 auto supported_groups = std::make_unique<Supported_Groups>(std::move(compatible_kex_groups));
427
428 if(!supported_groups->ec_groups().empty()) {
429 // NOLINTNEXTLINE(*-owning-memory)
430 m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
431 }
432
433 m_data->extensions().add(std::move(supported_groups));
434}
435
436Client_Hello_12::Client_Hello_12(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
437 const uint16_t TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF;
438
439 if(offered_suite(static_cast<uint16_t>(TLS_EMPTY_RENEGOTIATION_INFO_SCSV))) {
440 if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
441 if(!reneg->renegotiation_info().empty()) {
442 throw TLS_Exception(Alert::HandshakeFailure, "Client sent renegotiation SCSV and non-empty extension");
443 }
444 } else {
445 // add fake extension
446 m_data->extensions().add(new Renegotiation_Extension()); // NOLINT(*-owning-memory)
447 }
448 }
449}
450
451namespace {
452
453// Avoid sending an IPv4/IPv6 address in SNI as this is prohibitied
454bool hostname_acceptable_for_sni(std::string_view hostname) {
455 if(hostname.empty()) {
456 return false;
457 }
458
459 if(string_to_ipv4(hostname).has_value()) {
460 return false;
461 }
462
463 // IPv6? Anyway ':' is not valid in DNS
464 if(hostname.find(':') != std::string_view::npos) {
465 return false;
466 }
467
468 return true;
469}
470
471} // namespace
472
473// Note: This delegates to the Client_Hello_12 constructor to take advantage
474// of the sanity checks there.
475Client_Hello_12::Client_Hello_12(const std::vector<uint8_t>& buf) :
476 Client_Hello_12(std::make_unique<Client_Hello_Internal>(buf)) {}
477
478/*
479* Create a new Client Hello message
480*/
482 Handshake_Hash& hash,
483 const Policy& policy,
484 Callbacks& cb,
486 const std::vector<uint8_t>& reneg_info,
487 const Client_Hello_12::Settings& client_settings,
488 const std::vector<std::string>& next_protocols) {
489 m_data->m_legacy_version = client_settings.protocol_version();
490 m_data->m_random = make_hello_random(rng, cb, policy);
491 m_data->m_suites = policy.ciphersuite_list(client_settings.protocol_version());
492
493 if(!policy.acceptable_protocol_version(m_data->legacy_version())) {
494 throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
495 " but our own policy does not accept it");
496 }
497
498 /*
499 * Place all empty extensions in front to avoid a bug in some systems
500 * which reject hellos when the last extension in the list is empty.
501 */
502
503 // NOLINTBEGIN(*-owning-memory)
504
505 // EMS must always be used with TLS 1.2, regardless of the policy used.
506
507 m_data->extensions().add(new Extended_Master_Secret);
508
509 if(policy.negotiate_encrypt_then_mac()) {
510 m_data->extensions().add(new Encrypt_then_MAC);
511 }
512
513 m_data->extensions().add(new Session_Ticket_Extension());
514
515 m_data->extensions().add(new Renegotiation_Extension(reneg_info));
516
517 m_data->extensions().add(new Supported_Versions(m_data->legacy_version(), policy));
518
519 if(hostname_acceptable_for_sni(client_settings.hostname())) {
520 m_data->extensions().add(new Server_Name_Indicator(client_settings.hostname()));
521 }
522
523 if(policy.support_cert_status_message()) {
524 m_data->extensions().add(new Certificate_Status_Request({}, {}));
525 }
526
527 add_tls12_supported_groups_extensions(policy);
528
529 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
530 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
531 // RFC 8446 4.2.3
532 // TLS 1.2 implementations SHOULD also process this extension.
533 // Implementations which have the same policy in both cases MAY omit
534 // the "signature_algorithms_cert" extension.
535 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
536 }
537
538 if(reneg_info.empty() && !next_protocols.empty()) {
540 }
541
542 if(m_data->legacy_version().is_datagram_protocol()) {
543 m_data->extensions().add(new SRTP_Protection_Profiles(policy.srtp_profiles()));
544 }
545
546 // NOLINTEND(*-owning-memory)
547
549
550 hash.update(io.send(*this));
551}
552
553/*
554* Create a new Client Hello message (session resumption case)
555*/
557 Handshake_Hash& hash,
558 const Policy& policy,
559 Callbacks& cb,
561 const std::vector<uint8_t>& reneg_info,
562 const Session_with_Handle& session,
563 const std::vector<std::string>& next_protocols) {
564 m_data->m_legacy_version = session.session.version();
565 m_data->m_random = make_hello_random(rng, cb, policy);
566
567 // RFC 5077 3.4
568 // When presenting a ticket, the client MAY generate and include a
569 // Session ID in the TLS ClientHello. [...] If a ticket is presented by
570 // the client, the server MUST NOT attempt to use the Session ID in the
571 // ClientHello for stateful session resumption.
572 m_data->m_session_id = session.handle.id().value_or(Session_ID(make_hello_random(rng, cb, policy)));
573 m_data->m_suites = policy.ciphersuite_list(m_data->legacy_version());
574
575 if(!policy.acceptable_protocol_version(session.session.version())) {
576 throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
577 " but our own policy does not accept it");
578 }
579
580 if(!value_exists(m_data->ciphersuites(), session.session.ciphersuite_code())) {
581 m_data->m_suites.push_back(session.session.ciphersuite_code());
582 }
583
584 /*
585 * As EMS must always be used with TLS 1.2, add it even if it wasn't used
586 * in the original session. If the server understands it and follows the
587 * RFC it should reject our resume attempt and upgrade us to a new session
588 * with the EMS protection.
589 */
590 // NOLINTBEGIN(*-owning-memory)
591 m_data->extensions().add(new Extended_Master_Secret);
592
593 if(session.session.supports_encrypt_then_mac()) {
594 m_data->extensions().add(new Encrypt_then_MAC);
595 }
596
597 if(session.handle.is_ticket()) {
598 m_data->extensions().add(new Session_Ticket_Extension(session.handle.ticket().value()));
599 }
600
601 m_data->extensions().add(new Renegotiation_Extension(reneg_info));
602
603 const std::string hostname = session.session.server_info().hostname();
604
605 if(hostname_acceptable_for_sni(hostname)) {
606 m_data->extensions().add(new Server_Name_Indicator(hostname));
607 }
608
609 if(policy.support_cert_status_message()) {
610 m_data->extensions().add(new Certificate_Status_Request({}, {}));
611 }
612
613 add_tls12_supported_groups_extensions(policy);
614
615 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
616 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
617 // RFC 8446 4.2.3
618 // TLS 1.2 implementations SHOULD also process this extension.
619 // Implementations which have the same policy in both cases MAY omit
620 // the "signature_algorithms_cert" extension.
621 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
622 }
623
624 if(reneg_info.empty() && !next_protocols.empty()) {
626 }
627 // NOLINTEND(*-owning-memory)
628
630
631 hash.update(io.send(*this));
632}
633
634#if defined(BOTAN_HAS_TLS_13)
635
636Client_Hello_13::Client_Hello_13(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
637 const auto& exts = m_data->extensions();
638
639 // RFC 8446 4.1.2
640 // TLS 1.3 ClientHellos are identified as having a legacy_version of
641 // 0x0303 and a "supported_versions" extension present with 0x0304 as the
642 // highest version indicated therein.
643 //
644 // Note that we already checked for "supported_versions" before entering this
645 // c'tor in `Client_Hello_13::parse()`. This is just to be doubly sure.
647
648 // RFC 8446 4.2.1
649 // Servers MAY abort the handshake upon receiving a ClientHello with
650 // legacy_version 0x0304 or later.
651 if(m_data->legacy_version().is_tls_13_or_later()) {
652 throw TLS_Exception(Alert::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version");
653 }
654
655 // RFC 8446 4.1.2
656 // For every TLS 1.3 ClientHello, [the compression method] MUST contain
657 // exactly one byte, set to zero, [...]. If a TLS 1.3 ClientHello is
658 // received with any other value in this field, the server MUST abort the
659 // handshake with an "illegal_parameter" alert.
660 if(m_data->comp_methods().size() != 1 || m_data->comp_methods().front() != 0) {
661 throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
662 }
663
664 // RFC 8446 4.2.9
665 // A client MUST provide a "psk_key_exchange_modes" extension if it
666 // offers a "pre_shared_key" extension. If clients offer "pre_shared_key"
667 // without a "psk_key_exchange_modes" extension, servers MUST abort
668 // the handshake.
669 if(exts.has<PSK>()) {
670 if(!exts.has<PSK_Key_Exchange_Modes>()) {
671 throw TLS_Exception(Alert::MissingExtension,
672 "Client Hello offered a PSK without a psk_key_exchange_modes extension");
673 }
674
675 // RFC 8446 4.2.11
676 // The "pre_shared_key" extension MUST be the last extension in the
677 // ClientHello [...]. Servers MUST check that it is the last extension
678 // and otherwise fail the handshake with an "illegal_parameter" alert.
679 if(exts.all().back()->type() != Extension_Code::PresharedKey) {
680 throw TLS_Exception(Alert::IllegalParameter, "PSK extension was not at the very end of the Client Hello");
681 }
682 }
683
684 // RFC 8446 9.2
685 // [A TLS 1.3 ClientHello] message MUST meet the following requirements:
686 //
687 // - If not containing a "pre_shared_key" extension, it MUST contain
688 // both a "signature_algorithms" extension and a "supported_groups"
689 // extension.
690 //
691 // - If containing a "supported_groups" extension, it MUST also contain
692 // a "key_share" extension, and vice versa. An empty
693 // KeyShare.client_shares vector is permitted.
694 //
695 // Servers receiving a ClientHello which does not conform to these
696 // requirements MUST abort the handshake with a "missing_extension"
697 // alert.
698 if(!exts.has<PSK>()) {
699 if(!exts.has<Supported_Groups>() || !exts.has<Signature_Algorithms>()) {
700 throw TLS_Exception(
701 Alert::MissingExtension,
702 "Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions");
703 }
704 }
705 if(exts.has<Supported_Groups>() != exts.has<Key_Share>()) {
706 throw TLS_Exception(Alert::MissingExtension,
707 "Client Hello must either contain both key_share and supported_groups extensions or neither");
708 }
709
710 if(exts.has<Key_Share>()) {
711 auto* const supported_ext = exts.get<Supported_Groups>();
712 BOTAN_ASSERT_NONNULL(supported_ext);
713 const auto supports = supported_ext->groups();
714 const auto offers = exts.get<Key_Share>()->offered_groups();
715
716 // RFC 8446 4.2.8
717 // Each KeyShareEntry value MUST correspond to a group offered in the
718 // "supported_groups" extension and MUST appear in the same order.
719 // [...]
720 // Clients MUST NOT offer any KeyShareEntry values for groups not
721 // listed in the client's "supported_groups" extension.
722 //
723 // Note: We can assume that both `offers` and `supports` are unique lists
724 // as this is ensured in the parsing code of the extensions.
725 auto found_in_supported_groups = [&supports, support_offset = -1](auto group) mutable {
726 const auto i = std::find(supports.begin(), supports.end(), group);
727 if(i == supports.end()) {
728 return false;
729 }
730
731 const auto found_at = std::distance(supports.begin(), i);
732 if(found_at <= support_offset) {
733 return false; // The order that groups appear in "key_share" and
734 // "supported_groups" must be the same
735 }
736
737 support_offset = static_cast<decltype(support_offset)>(found_at);
738 return true;
739 };
740
741 for(const auto offered : offers) {
742 // RFC 8446 4.2.8
743 // Servers MAY check for violations of these rules and abort the
744 // handshake with an "illegal_parameter" alert if one is violated.
745 if(!found_in_supported_groups(offered)) {
746 throw TLS_Exception(Alert::IllegalParameter,
747 "Offered key exchange groups do not align with claimed supported groups");
748 }
749 }
750 }
751
752 // TODO: Reject oid_filters extension if found (which is the only known extension that
753 // must not occur in the TLS 1.3 client hello.
754 // RFC 8446 4.2.5
755 // [The oid_filters extension] MUST only be sent in the CertificateRequest message.
756}
757
758/*
759* Create a new Client Hello message
760*/
762 Callbacks& cb,
764 std::string_view hostname,
765 const std::vector<std::string>& next_protocols,
766 std::optional<Session_with_Handle>& session,
767 std::vector<ExternalPSK> psks) {
768 // RFC 8446 4.1.2
769 // In TLS 1.3, the client indicates its version preferences in the
770 // "supported_versions" extension (Section 4.2.1) and the
771 // legacy_version field MUST be set to 0x0303, which is the version
772 // number for TLS 1.2.
773 m_data->m_legacy_version = Protocol_Version::TLS_V12;
774 m_data->m_random = make_hello_random(rng, cb, policy);
775 m_data->m_suites = policy.ciphersuite_list(Protocol_Version::TLS_V13);
776
777 if(policy.allow_tls12()) {
778 // Note: DTLS 1.3 is NYI, hence dtls_12 is not checked
779 const auto legacy_suites = policy.ciphersuite_list(Protocol_Version::TLS_V12);
780 m_data->m_suites.insert(m_data->m_suites.end(), legacy_suites.cbegin(), legacy_suites.cend());
781 }
782
784 // RFC 8446 4.1.2
785 // In compatibility mode (see Appendix D.4), this field MUST be non-empty,
786 // so a client not offering a pre-TLS 1.3 session MUST generate a new
787 // 32-byte value.
788 //
789 // Note: we won't ever offer a TLS 1.2 session. In such a case we would
790 // have instantiated a TLS 1.2 client in the first place.
791 m_data->m_session_id = Session_ID(make_hello_random(rng, cb, policy));
792 }
793
794 // NOLINTBEGIN(*-owning-memory)
795 if(hostname_acceptable_for_sni(hostname)) {
796 m_data->extensions().add(new Server_Name_Indicator(hostname));
797 }
798
799 m_data->extensions().add(new Supported_Groups(policy.key_exchange_groups()));
800
801 m_data->extensions().add(new Key_Share(policy, cb, rng));
802
803 m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13, policy));
804
805 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
806 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
807 // RFC 8446 4.2.3
808 // Implementations which have the same policy in both cases MAY omit
809 // the "signature_algorithms_cert" extension.
810 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
811 }
812
813 // TODO: Support for PSK-only mode without a key exchange.
814 // This should be configurable in TLS::Policy and should allow no PSK
815 // support at all (e.g. to disable support for session resumption).
817
818 if(policy.support_cert_status_message()) {
819 m_data->extensions().add(new Certificate_Status_Request({}, {}));
820 }
821
822 // We currently support "record_size_limit" for TLS 1.3 exclusively. Hence,
823 // when TLS 1.2 is advertised as a supported protocol, we must not offer this
824 // extension.
825 if(policy.record_size_limit().has_value() && !policy.allow_tls12()) {
826 m_data->extensions().add(new Record_Size_Limit(policy.record_size_limit().value()));
827 }
828
829 if(!next_protocols.empty()) {
831 }
832
833 // RFC 7250 4.1
834 // In order to indicate the support of raw public keys, clients include
835 // the client_certificate_type and/or the server_certificate_type
836 // extensions in an extended client hello message.
839
840 if(policy.allow_tls12()) {
841 m_data->extensions().add(new Renegotiation_Extension());
842 m_data->extensions().add(new Session_Ticket_Extension());
843
844 // EMS must always be used with TLS 1.2, regardless of the policy
845 m_data->extensions().add(new Extended_Master_Secret);
846
847 if(policy.negotiate_encrypt_then_mac()) {
848 m_data->extensions().add(new Encrypt_then_MAC);
849 }
850
851 if(m_data->extensions().has<Supported_Groups>() &&
852 !m_data->extensions().get<Supported_Groups>()->ec_groups().empty()) {
853 m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
854 }
855 }
856
857 if(session.has_value() || !psks.empty()) {
858 m_data->extensions().add(new PSK(session, std::move(psks), cb));
859 }
860 // NOLINTEND(*-owning-memory)
861
863
864 if(m_data->extensions().has<PSK>()) {
865 // RFC 8446 4.2.11
866 // The "pre_shared_key" extension MUST be the last extension in the
867 // ClientHello (this facilitates implementation [...]).
868 if(m_data->extensions().all().back()->type() != Extension_Code::PresharedKey) {
869 throw TLS_Exception(Alert::InternalError,
870 "Application modified extensions of Client Hello, PSK is not last anymore");
871 }
872 calculate_psk_binders({});
873 }
874}
875
876std::variant<Client_Hello_13, Client_Hello_12> Client_Hello_13::parse(const std::vector<uint8_t>& buf) {
877 auto data = std::make_unique<Client_Hello_Internal>(buf);
878 const auto version = data->version();
879
880 if(version.is_pre_tls_13()) {
881 return Client_Hello_12(std::move(data));
882 } else {
883 return Client_Hello_13(std::move(data));
884 }
885}
886
888 const Transcript_Hash_State& transcript_hash_state,
889 Callbacks& cb,
891 BOTAN_STATE_CHECK(m_data->extensions().has<Supported_Groups>());
892 BOTAN_STATE_CHECK(m_data->extensions().has<Key_Share>());
893
894 auto* hrr_ks = hrr.extensions().get<Key_Share>();
895 const auto& supported_groups = m_data->extensions().get<Supported_Groups>()->groups();
896
897 if(hrr.extensions().has<Key_Share>()) {
898 m_data->extensions().get<Key_Share>()->retry_offer(*hrr_ks, supported_groups, cb, rng);
899 }
900
901 // RFC 8446 4.2.2
902 // When sending the new ClientHello, the client MUST copy
903 // the contents of the extension received in the HelloRetryRequest into
904 // a "cookie" extension in the new ClientHello.
905 //
906 // RFC 8446 4.2.2
907 // Clients MUST NOT use cookies in their initial ClientHello in subsequent
908 // connections.
909 if(hrr.extensions().has<Cookie>()) {
910 BOTAN_STATE_CHECK(!m_data->extensions().has<Cookie>());
911 m_data->extensions().add(new Cookie(hrr.extensions().get<Cookie>()->get_cookie())); // NOLINT(*-owning-memory)
912 }
913
914 // Note: the consumer of the TLS implementation won't be able to distinguish
915 // invocations to this callback due to the first Client_Hello or the
916 // retried Client_Hello after receiving a Hello_Retry_Request. We assume
917 // that the user keeps and detects this state themselves.
919
920 auto* psk = m_data->extensions().get<PSK>();
921 if(psk != nullptr) {
922 // Cipher suite should always be a known suite as this is checked upstream
923 const auto cipher = Ciphersuite::by_id(hrr.ciphersuite());
924 BOTAN_ASSERT_NOMSG(cipher.has_value());
925
926 // RFC 8446 4.1.4
927 // In [...] its updated ClientHello, the client SHOULD NOT offer
928 // any pre-shared keys associated with a hash other than that of the
929 // selected cipher suite.
930 psk->filter(cipher.value());
931
932 // RFC 8446 4.2.11.2
933 // If the server responds with a HelloRetryRequest and the client
934 // then sends ClientHello2, its binder will be computed over: [...].
935 calculate_psk_binders(transcript_hash_state.clone());
936 }
937}
938
940 // RFC 8446 4.1.2
941 // The client will also send a ClientHello when the server has responded
942 // to its ClientHello with a HelloRetryRequest. In that case, the client
943 // MUST send the same ClientHello without modification, except as follows:
944
945 if(m_data->session_id() != new_ch.m_data->session_id() || m_data->random() != new_ch.m_data->random() ||
946 m_data->ciphersuites() != new_ch.m_data->ciphersuites() ||
947 m_data->comp_methods() != new_ch.m_data->comp_methods()) {
948 throw TLS_Exception(Alert::IllegalParameter, "Client Hello core values changed after Hello Retry Request");
949 }
950
951 const auto oldexts = extension_types();
952 const auto newexts = new_ch.extension_types();
953
954 // Check that extension omissions are justified
955 for(const auto oldext : oldexts) {
956 if(!newexts.contains(oldext)) {
957 auto* const ext = extensions().get(oldext);
958
959 // We don't make any assumptions about unimplemented extensions.
960 if(!ext->is_implemented()) {
961 continue;
962 }
963
964 // RFC 8446 4.1.2
965 // Removing the "early_data" extension (Section 4.2.10) if one was
966 // present. Early data is not permitted after a HelloRetryRequest.
967 if(oldext == EarlyDataIndication::static_type()) {
968 continue;
969 }
970
971 // RFC 8446 4.1.2
972 // Optionally adding, removing, or changing the length of the
973 // "padding" extension.
974 //
975 // TODO: implement the Padding extension
976 // if(oldext == Padding::static_type())
977 // continue;
978
979 throw TLS_Exception(Alert::IllegalParameter, "Extension removed in updated Client Hello");
980 }
981 }
982
983 // Check that extension additions are justified
984 for(const auto newext : newexts) {
985 if(!oldexts.contains(newext)) {
986 auto* const ext = new_ch.extensions().get(newext);
987
988 // We don't make any assumptions about unimplemented extensions.
989 if(!ext->is_implemented()) {
990 continue;
991 }
992
993 // RFC 8446 4.1.2
994 // Including a "cookie" extension if one was provided in the
995 // HelloRetryRequest.
996 if(newext == Cookie::static_type()) {
997 continue;
998 }
999
1000 // RFC 8446 4.1.2
1001 // Optionally adding, removing, or changing the length of the
1002 // "padding" extension.
1003 //
1004 // TODO: implement the Padding extension
1005 // if(newext == Padding::static_type())
1006 // continue;
1007
1008 throw TLS_Exception(Alert::UnsupportedExtension, "Added an extension in updated Client Hello");
1009 }
1010 }
1011
1012 // RFC 8446 4.1.2
1013 // Removing the "early_data" extension (Section 4.2.10) if one was
1014 // present. Early data is not permitted after a HelloRetryRequest.
1015 if(new_ch.extensions().has<EarlyDataIndication>()) {
1016 throw TLS_Exception(Alert::IllegalParameter, "Updated Client Hello indicates early data");
1017 }
1018
1019 // TODO: Contents of extensions are not checked for update compatibility, see:
1020 //
1021 // RFC 8446 4.1.2
1022 // If a "key_share" extension was supplied in the HelloRetryRequest,
1023 // replacing the list of shares with a list containing a single
1024 // KeyShareEntry from the indicated group.
1025 //
1026 // Updating the "pre_shared_key" extension if present by recomputing
1027 // the "obfuscated_ticket_age" and binder values and (optionally)
1028 // removing any PSKs which are incompatible with the server's
1029 // indicated cipher suite.
1030 //
1031 // Optionally adding, removing, or changing the length of the
1032 // "padding" extension.
1033}
1034
1035void Client_Hello_13::calculate_psk_binders(Transcript_Hash_State ths) {
1036 auto* psk = m_data->extensions().get<PSK>();
1037 if(psk == nullptr || psk->empty()) {
1038 return;
1039 }
1040
1041 // RFC 8446 4.2.11.2
1042 // Each entry in the binders list is computed as an HMAC over a
1043 // transcript hash (see Section 4.4.1) containing a partial ClientHello
1044 // [...].
1045 //
1046 // Therefore we marshal the entire message prematurely to obtain the
1047 // (truncated) transcript hash, calculate the PSK binders with it, update
1048 // the Client Hello thus finalizing the message. Down the road, it will be
1049 // re-marshalled with the correct binders and sent over the wire.
1051 psk->calculate_binders(ths);
1052}
1053
1054std::optional<Protocol_Version> Client_Hello_13::highest_supported_version(const Policy& policy) const {
1055 // RFC 8446 4.2.1
1056 // The "supported_versions" extension is used by the client to indicate
1057 // which versions of TLS it supports and by the server to indicate which
1058 // version it is using. The extension contains a list of supported
1059 // versions in preference order, with the most preferred version first.
1060 auto* const supvers = m_data->extensions().get<Supported_Versions>();
1061 BOTAN_ASSERT_NONNULL(supvers);
1062
1063 std::optional<Protocol_Version> result;
1064
1065 for(const auto& v : supvers->versions()) {
1066 // RFC 8446 4.2.1
1067 // Servers MUST only select a version of TLS present in that extension
1068 // and MUST ignore any unknown versions that are present in that
1069 // extension.
1070 if(!v.known_version() || !policy.acceptable_protocol_version(v)) {
1071 continue;
1072 }
1073
1074 result = (result.has_value()) ? std::optional(std::max(result.value(), v)) : std::optional(v);
1075 }
1076
1077 return result;
1078}
1079
1080#endif // BOTAN_HAS_TLS_13
1081
1082} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:114
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:298
void random_vec(std::span< uint8_t > v)
Definition rng.h:199
virtual void tls_modify_extensions(Extensions &extn, Connection_Side which_side, Handshake_Type which_message)
virtual std::chrono::system_clock::time_point tls_current_timestamp()
static std::optional< Ciphersuite > by_id(uint16_t suite)
const std::string & hostname() const
Protocol_Version protocol_version() const
Client_Hello_12(const std::vector< uint8_t > &buf)
void update_hello_cookie(const Hello_Verify_Request &hello_verify)
std::vector< uint8_t > renegotiation_info() const
Session_Ticket session_ticket() const
std::optional< Session_Handle > session_handle() const
void validate_updates(const Client_Hello_13 &new_ch)
static std::variant< Client_Hello_13, Client_Hello_12 > parse(const std::vector< uint8_t > &buf)
std::optional< Protocol_Version > highest_supported_version(const Policy &policy) const
Client_Hello_13(const Policy &policy, Callbacks &cb, RandomNumberGenerator &rng, std::string_view hostname, const std::vector< std::string > &next_protocols, std::optional< Session_with_Handle > &session, std::vector< ExternalPSK > psks)
void retry(const Hello_Retry_Request &hrr, const Transcript_Hash_State &transcript_hash_state, Callbacks &cb, RandomNumberGenerator &rng)
const std::vector< uint8_t > & cookie() const
std::string sni_hostname() const
std::vector< uint8_t > serialize() const override
const std::vector< uint8_t > & random() const
std::vector< Signature_Scheme > signature_schemes() const
const Extensions & extensions() const
bool offered_suite(uint16_t ciphersuite) const
std::unique_ptr< Client_Hello_Internal > m_data
std::vector< Group_Params > supported_ecc_curves() const
std::vector< Signature_Scheme > certificate_signature_schemes() const
const std::vector< uint16_t > & ciphersuites() const
std::vector< uint8_t > cookie_input_data() const
std::set< Extension_Code > extension_types() const
std::vector< Group_Params > supported_dh_groups() const
std::vector< std::string > next_protocols() const
const Session_ID & session_id() const
Protocol_Version legacy_version() const
const std::vector< uint8_t > & compression_methods() const
std::vector< uint16_t > srtp_profiles() const
Handshake_Type type() const override
std::vector< Protocol_Version > supported_versions() const
Client_Hello(const Client_Hello &)=delete
const std::vector< uint8_t > & get_cookie() const
static Extension_Code static_type()
static Extension_Code static_type()
void update(const uint8_t in[], size_t length)
virtual std::vector< uint8_t > send(const Handshake_Message &msg)=0
static std::vector< uint8_t > prepare_message(Handshake_Message_13_Ref message, Transcript_Hash_State &transcript_hash)
virtual std::vector< uint8_t > serialize() const =0
const std::vector< uint8_t > & cookie() const
virtual bool include_time_in_hello_random() const
virtual bool allow_tls12() const
virtual std::vector< uint16_t > ciphersuite_list(Protocol_Version version) const
virtual std::vector< Certificate_Type > accepted_server_certificate_types() const
virtual std::vector< Certificate_Type > accepted_client_certificate_types() const
virtual std::vector< Group_Params > key_exchange_groups() const
virtual bool tls_13_middlebox_compatibility_mode() const
virtual bool negotiate_encrypt_then_mac() const
virtual bool acceptable_protocol_version(Protocol_Version version) const
virtual std::vector< uint16_t > srtp_profiles() const
virtual bool support_cert_status_message() const
virtual std::optional< std::vector< Signature_Scheme > > acceptable_certificate_signature_schemes() const
virtual bool hash_hello_random() const
virtual std::vector< Signature_Scheme > acceptable_signature_schemes() const
virtual bool use_ecc_point_compression() const
virtual bool allow_dtls12() const
virtual std::optional< uint16_t > record_size_limit() const
const Extensions & extensions() const
Protocol_Version version() const
bool supports_encrypt_then_mac() const
uint16_t ciphersuite_code() const
const Server_Information & server_info() const
Helper class to embody a session handle in all protocol versions.
Definition tls_session.h:63
std::optional< Session_Ticket > ticket() const
std::optional< Session_ID > id() const
std::vector< Group_Params > ec_groups() const
bool empty() const noexcept(noexcept(this->get().empty()))
void append_tls_length_value(std::vector< uint8_t, Alloc > &buf, const T *vals, size_t vals_size, size_t tag_size)
Definition tls_reader.h:184
std::vector< uint8_t > make_hello_random(RandomNumberGenerator &rng, Callbacks &cb, const Policy &policy)
Strong< std::vector< uint8_t >, struct Session_ID_ > Session_ID
holds a TLS 1.2 session ID for stateful resumption
Definition tls_session.h:31
Strong< std::vector< uint8_t >, struct Session_Ticket_ > Session_Ticket
holds a TLS 1.2 session ticket for stateless resumption
Definition tls_session.h:34
std::optional< uint32_t > string_to_ipv4(std::string_view str)
Definition parsing.cpp:156
bool value_exists(const std::vector< T > &vec, const OT &val)
Definition stl_util.h:52
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745