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