Botan 3.5.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 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
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-variables-in-classes)
155 Session_ID m_session_id; // NOLINT(*-non-private-member-variables-in-classes)
156 std::vector<uint8_t> m_random; // NOLINT(*-non-private-member-variables-in-classes)
157 std::vector<uint16_t> m_suites; // NOLINT(*-non-private-member-variables-in-classes)
158 std::vector<uint8_t> m_comp_methods; // NOLINT(*-non-private-member-variables-in-classes)
159 Extensions m_extensions; // NOLINT(*-non-private-member-variables-in-classes)
160
161 // These fields are only for DTLS:
162 std::vector<uint8_t> m_hello_cookie; // NOLINT(*-non-private-member-variables-in-classes)
163 std::vector<uint8_t> m_cookie_input_bits; // NOLINT(*-non-private-member-variables-in-classes)
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 ticket;
346 } else if(const auto& id = session_id(); !id.empty()) {
347 return 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 m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
430 }
431
432 m_data->extensions().add(std::move(supported_groups));
433}
434
435Client_Hello_12::Client_Hello_12(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
436 const uint16_t TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF;
437
438 if(offered_suite(static_cast<uint16_t>(TLS_EMPTY_RENEGOTIATION_INFO_SCSV))) {
439 if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
440 if(!reneg->renegotiation_info().empty()) {
441 throw TLS_Exception(Alert::HandshakeFailure, "Client sent renegotiation SCSV and non-empty extension");
442 }
443 } else {
444 // add fake extension
445 m_data->extensions().add(new Renegotiation_Extension());
446 }
447 }
448}
449
450namespace {
451
452// Avoid sending an IPv4/IPv6 address in SNI as this is prohibitied
453bool hostname_acceptable_for_sni(std::string_view hostname) {
454 if(hostname.empty()) {
455 return false;
456 }
457
458 if(string_to_ipv4(hostname).has_value()) {
459 return false;
460 }
461
462 // IPv6? Anyway ':' is not valid in DNS
463 if(hostname.find(':') != std::string_view::npos) {
464 return false;
465 }
466
467 return true;
468}
469
470} // namespace
471
472// Note: This delegates to the Client_Hello_12 constructor to take advantage
473// of the sanity checks there.
474Client_Hello_12::Client_Hello_12(const std::vector<uint8_t>& buf) :
475 Client_Hello_12(std::make_unique<Client_Hello_Internal>(buf)) {}
476
477/*
478* Create a new Client Hello message
479*/
481 Handshake_Hash& hash,
482 const Policy& policy,
483 Callbacks& cb,
485 const std::vector<uint8_t>& reneg_info,
486 const Client_Hello_12::Settings& client_settings,
487 const std::vector<std::string>& next_protocols) {
488 m_data->m_legacy_version = client_settings.protocol_version();
489 m_data->m_random = make_hello_random(rng, cb, policy);
490 m_data->m_suites = policy.ciphersuite_list(client_settings.protocol_version());
491
492 if(!policy.acceptable_protocol_version(m_data->legacy_version())) {
493 throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
494 " but our own policy does not accept it");
495 }
496
497 /*
498 * Place all empty extensions in front to avoid a bug in some systems
499 * which reject hellos when the last extension in the list is empty.
500 */
501
502 // EMS must always be used with TLS 1.2, regardless of the policy used.
503 m_data->extensions().add(new Extended_Master_Secret);
504
505 if(policy.negotiate_encrypt_then_mac()) {
506 m_data->extensions().add(new Encrypt_then_MAC);
507 }
508
509 m_data->extensions().add(new Session_Ticket_Extension());
510
511 m_data->extensions().add(new Renegotiation_Extension(reneg_info));
512
513 m_data->extensions().add(new Supported_Versions(m_data->legacy_version(), policy));
514
515 if(hostname_acceptable_for_sni(client_settings.hostname())) {
516 m_data->extensions().add(new Server_Name_Indicator(client_settings.hostname()));
517 }
518
519 if(policy.support_cert_status_message()) {
520 m_data->extensions().add(new Certificate_Status_Request({}, {}));
521 }
522
523 add_tls12_supported_groups_extensions(policy);
524
525 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
526 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
527 // RFC 8446 4.2.3
528 // TLS 1.2 implementations SHOULD also process this extension.
529 // Implementations which have the same policy in both cases MAY omit
530 // the "signature_algorithms_cert" extension.
531 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
532 }
533
534 if(reneg_info.empty() && !next_protocols.empty()) {
536 }
537
538 if(m_data->legacy_version().is_datagram_protocol()) {
539 m_data->extensions().add(new SRTP_Protection_Profiles(policy.srtp_profiles()));
540 }
541
543
544 hash.update(io.send(*this));
545}
546
547/*
548* Create a new Client Hello message (session resumption case)
549*/
551 Handshake_Hash& hash,
552 const Policy& policy,
553 Callbacks& cb,
555 const std::vector<uint8_t>& reneg_info,
556 const Session_with_Handle& session,
557 const std::vector<std::string>& next_protocols) {
558 m_data->m_legacy_version = session.session.version();
559 m_data->m_random = make_hello_random(rng, cb, policy);
560
561 // RFC 5077 3.4
562 // When presenting a ticket, the client MAY generate and include a
563 // Session ID in the TLS ClientHello. [...] If a ticket is presented by
564 // the client, the server MUST NOT attempt to use the Session ID in the
565 // ClientHello for stateful session resumption.
566 m_data->m_session_id = session.handle.id().value_or(Session_ID(make_hello_random(rng, cb, policy)));
567 m_data->m_suites = policy.ciphersuite_list(m_data->legacy_version());
568
569 if(!policy.acceptable_protocol_version(session.session.version())) {
570 throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
571 " but our own policy does not accept it");
572 }
573
574 if(!value_exists(m_data->ciphersuites(), session.session.ciphersuite_code())) {
575 m_data->m_suites.push_back(session.session.ciphersuite_code());
576 }
577
578 /*
579 * As EMS must always be used with TLS 1.2, add it even if it wasn't used
580 * in the original session. If the server understands it and follows the
581 * RFC it should reject our resume attempt and upgrade us to a new session
582 * with the EMS protection.
583 */
584 m_data->extensions().add(new Extended_Master_Secret);
585
586 if(session.session.supports_encrypt_then_mac()) {
587 m_data->extensions().add(new Encrypt_then_MAC);
588 }
589
590 if(session.handle.is_ticket()) {
591 m_data->extensions().add(new Session_Ticket_Extension(session.handle.ticket().value()));
592 }
593
594 m_data->extensions().add(new Renegotiation_Extension(reneg_info));
595
596 const std::string hostname = session.session.server_info().hostname();
597
598 if(hostname_acceptable_for_sni(hostname)) {
599 m_data->extensions().add(new Server_Name_Indicator(hostname));
600 }
601
602 if(policy.support_cert_status_message()) {
603 m_data->extensions().add(new Certificate_Status_Request({}, {}));
604 }
605
606 add_tls12_supported_groups_extensions(policy);
607
608 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
609 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
610 // RFC 8446 4.2.3
611 // TLS 1.2 implementations SHOULD also process this extension.
612 // Implementations which have the same policy in both cases MAY omit
613 // the "signature_algorithms_cert" extension.
614 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
615 }
616
617 if(reneg_info.empty() && !next_protocols.empty()) {
619 }
620
622
623 hash.update(io.send(*this));
624}
625
626#if defined(BOTAN_HAS_TLS_13)
627
628Client_Hello_13::Client_Hello_13(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
629 const auto& exts = m_data->extensions();
630
631 // RFC 8446 4.1.2
632 // TLS 1.3 ClientHellos are identified as having a legacy_version of
633 // 0x0303 and a "supported_versions" extension present with 0x0304 as the
634 // highest version indicated therein.
635 //
636 // Note that we already checked for "supported_versions" before entering this
637 // c'tor in `Client_Hello_13::parse()`. This is just to be doubly sure.
639
640 // RFC 8446 4.2.1
641 // Servers MAY abort the handshake upon receiving a ClientHello with
642 // legacy_version 0x0304 or later.
643 if(m_data->legacy_version().is_tls_13_or_later()) {
644 throw TLS_Exception(Alert::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version");
645 }
646
647 // RFC 8446 4.1.2
648 // For every TLS 1.3 ClientHello, [the compression method] MUST contain
649 // exactly one byte, set to zero, [...]. If a TLS 1.3 ClientHello is
650 // received with any other value in this field, the server MUST abort the
651 // handshake with an "illegal_parameter" alert.
652 if(m_data->comp_methods().size() != 1 || m_data->comp_methods().front() != 0) {
653 throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
654 }
655
656 // RFC 8446 4.2.9
657 // A client MUST provide a "psk_key_exchange_modes" extension if it
658 // offers a "pre_shared_key" extension. If clients offer "pre_shared_key"
659 // without a "psk_key_exchange_modes" extension, servers MUST abort
660 // the handshake.
661 if(exts.has<PSK>()) {
662 if(!exts.has<PSK_Key_Exchange_Modes>()) {
663 throw TLS_Exception(Alert::MissingExtension,
664 "Client Hello offered a PSK without a psk_key_exchange_modes extension");
665 }
666
667 // RFC 8446 4.2.11
668 // The "pre_shared_key" extension MUST be the last extension in the
669 // ClientHello [...]. Servers MUST check that it is the last extension
670 // and otherwise fail the handshake with an "illegal_parameter" alert.
671 if(exts.all().back()->type() != Extension_Code::PresharedKey) {
672 throw TLS_Exception(Alert::IllegalParameter, "PSK extension was not at the very end of the Client Hello");
673 }
674 }
675
676 // RFC 8446 9.2
677 // [A TLS 1.3 ClientHello] message MUST meet the following requirements:
678 //
679 // - If not containing a "pre_shared_key" extension, it MUST contain
680 // both a "signature_algorithms" extension and a "supported_groups"
681 // extension.
682 //
683 // - If containing a "supported_groups" extension, it MUST also contain
684 // a "key_share" extension, and vice versa. An empty
685 // KeyShare.client_shares vector is permitted.
686 //
687 // Servers receiving a ClientHello which does not conform to these
688 // requirements MUST abort the handshake with a "missing_extension"
689 // alert.
690 if(!exts.has<PSK>()) {
691 if(!exts.has<Supported_Groups>() || !exts.has<Signature_Algorithms>()) {
692 throw TLS_Exception(
693 Alert::MissingExtension,
694 "Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions");
695 }
696 }
697 if(exts.has<Supported_Groups>() != exts.has<Key_Share>()) {
698 throw TLS_Exception(Alert::MissingExtension,
699 "Client Hello must either contain both key_share and supported_groups extensions or neither");
700 }
701
702 if(exts.has<Key_Share>()) {
703 const auto supported_ext = exts.get<Supported_Groups>();
704 BOTAN_ASSERT_NONNULL(supported_ext);
705 const auto supports = supported_ext->groups();
706 const auto offers = exts.get<Key_Share>()->offered_groups();
707
708 // RFC 8446 4.2.8
709 // Each KeyShareEntry value MUST correspond to a group offered in the
710 // "supported_groups" extension and MUST appear in the same order.
711 // [...]
712 // Clients MUST NOT offer any KeyShareEntry values for groups not
713 // listed in the client's "supported_groups" extension.
714 //
715 // Note: We can assume that both `offers` and `supports` are unique lists
716 // as this is ensured in the parsing code of the extensions.
717 auto found_in_supported_groups = [&supports, support_offset = -1](auto group) mutable {
718 const auto i = std::find(supports.begin(), supports.end(), group);
719 if(i == supports.end()) {
720 return false;
721 }
722
723 const auto found_at = std::distance(supports.begin(), i);
724 if(found_at <= support_offset) {
725 return false; // The order that groups appear in "key_share" and
726 // "supported_groups" must be the same
727 }
728
729 support_offset = static_cast<decltype(support_offset)>(found_at);
730 return true;
731 };
732
733 for(const auto offered : offers) {
734 // RFC 8446 4.2.8
735 // Servers MAY check for violations of these rules and abort the
736 // handshake with an "illegal_parameter" alert if one is violated.
737 if(!found_in_supported_groups(offered)) {
738 throw TLS_Exception(Alert::IllegalParameter,
739 "Offered key exchange groups do not align with claimed supported groups");
740 }
741 }
742 }
743
744 // TODO: Reject oid_filters extension if found (which is the only known extension that
745 // must not occur in the TLS 1.3 client hello.
746 // RFC 8446 4.2.5
747 // [The oid_filters extension] MUST only be sent in the CertificateRequest message.
748}
749
750/*
751* Create a new Client Hello message
752*/
754 Callbacks& cb,
756 std::string_view hostname,
757 const std::vector<std::string>& next_protocols,
758 std::optional<Session_with_Handle>& session,
759 std::vector<ExternalPSK> psks) {
760 // RFC 8446 4.1.2
761 // In TLS 1.3, the client indicates its version preferences in the
762 // "supported_versions" extension (Section 4.2.1) and the
763 // legacy_version field MUST be set to 0x0303, which is the version
764 // number for TLS 1.2.
765 m_data->m_legacy_version = Protocol_Version::TLS_V12;
766 m_data->m_random = make_hello_random(rng, cb, policy);
767 m_data->m_suites = policy.ciphersuite_list(Protocol_Version::TLS_V13);
768
769 if(policy.allow_tls12()) // Note: DTLS 1.3 is NYI, hence dtls_12 is not checked
770 {
771 const auto legacy_suites = policy.ciphersuite_list(Protocol_Version::TLS_V12);
772 m_data->m_suites.insert(m_data->m_suites.end(), legacy_suites.cbegin(), legacy_suites.cend());
773 }
774
776 // RFC 8446 4.1.2
777 // In compatibility mode (see Appendix D.4), this field MUST be non-empty,
778 // so a client not offering a pre-TLS 1.3 session MUST generate a new
779 // 32-byte value.
780 //
781 // Note: we won't ever offer a TLS 1.2 session. In such a case we would
782 // have instantiated a TLS 1.2 client in the first place.
783 m_data->m_session_id = Session_ID(make_hello_random(rng, cb, policy));
784 }
785
786 if(hostname_acceptable_for_sni(hostname)) {
787 m_data->extensions().add(new Server_Name_Indicator(hostname));
788 }
789
790 m_data->extensions().add(new Supported_Groups(policy.key_exchange_groups()));
791
792 m_data->extensions().add(new Key_Share(policy, cb, rng));
793
794 m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13, policy));
795
796 m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
797 if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
798 // RFC 8446 4.2.3
799 // Implementations which have the same policy in both cases MAY omit
800 // the "signature_algorithms_cert" extension.
801 m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
802 }
803
804 // TODO: Support for PSK-only mode without a key exchange.
805 // This should be configurable in TLS::Policy and should allow no PSK
806 // support at all (e.g. to disable support for session resumption).
808
809 if(policy.support_cert_status_message()) {
810 m_data->extensions().add(new Certificate_Status_Request({}, {}));
811 }
812
813 // We currently support "record_size_limit" for TLS 1.3 exclusively. Hence,
814 // when TLS 1.2 is advertised as a supported protocol, we must not offer this
815 // extension.
816 if(policy.record_size_limit().has_value() && !policy.allow_tls12()) {
817 m_data->extensions().add(new Record_Size_Limit(policy.record_size_limit().value()));
818 }
819
820 if(!next_protocols.empty()) {
822 }
823
824 // RFC 7250 4.1
825 // In order to indicate the support of raw public keys, clients include
826 // the client_certificate_type and/or the server_certificate_type
827 // extensions in an extended client hello message.
830
831 if(policy.allow_tls12()) {
832 m_data->extensions().add(new Renegotiation_Extension());
833 m_data->extensions().add(new Session_Ticket_Extension());
834
835 // EMS must always be used with TLS 1.2, regardless of the policy
836 m_data->extensions().add(new Extended_Master_Secret);
837
838 if(policy.negotiate_encrypt_then_mac()) {
839 m_data->extensions().add(new Encrypt_then_MAC);
840 }
841
842 if(m_data->extensions().has<Supported_Groups>() &&
843 !m_data->extensions().get<Supported_Groups>()->ec_groups().empty()) {
844 m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
845 }
846 }
847
848 if(session.has_value() || !psks.empty()) {
849 m_data->extensions().add(new PSK(session, std::move(psks), cb));
850 }
851
853
854 if(m_data->extensions().has<PSK>()) {
855 // RFC 8446 4.2.11
856 // The "pre_shared_key" extension MUST be the last extension in the
857 // ClientHello (this facilitates implementation [...]).
858 if(m_data->extensions().all().back()->type() != Extension_Code::PresharedKey) {
859 throw TLS_Exception(Alert::InternalError,
860 "Application modified extensions of Client Hello, PSK is not last anymore");
861 }
862 calculate_psk_binders({});
863 }
864}
865
866std::variant<Client_Hello_13, Client_Hello_12> Client_Hello_13::parse(const std::vector<uint8_t>& buf) {
867 auto data = std::make_unique<Client_Hello_Internal>(buf);
868 const auto version = data->version();
869
870 if(version.is_pre_tls_13()) {
871 return Client_Hello_12(std::move(data));
872 } else {
873 return Client_Hello_13(std::move(data));
874 }
875}
876
878 const Transcript_Hash_State& transcript_hash_state,
879 Callbacks& cb,
881 BOTAN_STATE_CHECK(m_data->extensions().has<Supported_Groups>());
882 BOTAN_STATE_CHECK(m_data->extensions().has<Key_Share>());
883
884 auto hrr_ks = hrr.extensions().get<Key_Share>();
885 const auto& supported_groups = m_data->extensions().get<Supported_Groups>()->groups();
886
887 if(hrr.extensions().has<Key_Share>()) {
888 m_data->extensions().get<Key_Share>()->retry_offer(*hrr_ks, supported_groups, cb, rng);
889 }
890
891 // RFC 8446 4.2.2
892 // When sending the new ClientHello, the client MUST copy
893 // the contents of the extension received in the HelloRetryRequest into
894 // a "cookie" extension in the new ClientHello.
895 //
896 // RFC 8446 4.2.2
897 // Clients MUST NOT use cookies in their initial ClientHello in subsequent
898 // connections.
899 if(hrr.extensions().has<Cookie>()) {
900 BOTAN_STATE_CHECK(!m_data->extensions().has<Cookie>());
901 m_data->extensions().add(new Cookie(hrr.extensions().get<Cookie>()->get_cookie()));
902 }
903
904 // Note: the consumer of the TLS implementation won't be able to distinguish
905 // invocations to this callback due to the first Client_Hello or the
906 // retried Client_Hello after receiving a Hello_Retry_Request. We assume
907 // that the user keeps and detects this state themselves.
909
910 auto psk = m_data->extensions().get<PSK>();
911 if(psk) {
912 // Cipher suite should always be a known suite as this is checked upstream
913 const auto cipher = Ciphersuite::by_id(hrr.ciphersuite());
914 BOTAN_ASSERT_NOMSG(cipher.has_value());
915
916 // RFC 8446 4.1.4
917 // In [...] its updated ClientHello, the client SHOULD NOT offer
918 // any pre-shared keys associated with a hash other than that of the
919 // selected cipher suite.
920 psk->filter(cipher.value());
921
922 // RFC 8446 4.2.11.2
923 // If the server responds with a HelloRetryRequest and the client
924 // then sends ClientHello2, its binder will be computed over: [...].
925 calculate_psk_binders(transcript_hash_state.clone());
926 }
927}
928
930 // RFC 8446 4.1.2
931 // The client will also send a ClientHello when the server has responded
932 // to its ClientHello with a HelloRetryRequest. In that case, the client
933 // MUST send the same ClientHello without modification, except as follows:
934
935 if(m_data->session_id() != new_ch.m_data->session_id() || m_data->random() != new_ch.m_data->random() ||
936 m_data->ciphersuites() != new_ch.m_data->ciphersuites() ||
937 m_data->comp_methods() != new_ch.m_data->comp_methods()) {
938 throw TLS_Exception(Alert::IllegalParameter, "Client Hello core values changed after Hello Retry Request");
939 }
940
941 const auto oldexts = extension_types();
942 const auto newexts = new_ch.extension_types();
943
944 // Check that extension omissions are justified
945 for(const auto oldext : oldexts) {
946 if(!newexts.contains(oldext)) {
947 const auto ext = extensions().get(oldext);
948
949 // We don't make any assumptions about unimplemented extensions.
950 if(!ext->is_implemented()) {
951 continue;
952 }
953
954 // RFC 8446 4.1.2
955 // Removing the "early_data" extension (Section 4.2.10) if one was
956 // present. Early data is not permitted after a HelloRetryRequest.
957 if(oldext == EarlyDataIndication::static_type()) {
958 continue;
959 }
960
961 // RFC 8446 4.1.2
962 // Optionally adding, removing, or changing the length of the
963 // "padding" extension.
964 //
965 // TODO: implement the Padding extension
966 // if(oldext == Padding::static_type())
967 // continue;
968
969 throw TLS_Exception(Alert::IllegalParameter, "Extension removed in updated Client Hello");
970 }
971 }
972
973 // Check that extension additions are justified
974 for(const auto newext : newexts) {
975 if(!oldexts.contains(newext)) {
976 const auto ext = new_ch.extensions().get(newext);
977
978 // We don't make any assumptions about unimplemented extensions.
979 if(!ext->is_implemented()) {
980 continue;
981 }
982
983 // RFC 8446 4.1.2
984 // Including a "cookie" extension if one was provided in the
985 // HelloRetryRequest.
986 if(newext == Cookie::static_type()) {
987 continue;
988 }
989
990 // RFC 8446 4.1.2
991 // Optionally adding, removing, or changing the length of the
992 // "padding" extension.
993 //
994 // TODO: implement the Padding extension
995 // if(newext == Padding::static_type())
996 // continue;
997
998 throw TLS_Exception(Alert::UnsupportedExtension, "Added an extension in updated Client Hello");
999 }
1000 }
1001
1002 // RFC 8446 4.1.2
1003 // Removing the "early_data" extension (Section 4.2.10) if one was
1004 // present. Early data is not permitted after a HelloRetryRequest.
1005 if(new_ch.extensions().has<EarlyDataIndication>()) {
1006 throw TLS_Exception(Alert::IllegalParameter, "Updated Client Hello indicates early data");
1007 }
1008
1009 // TODO: Contents of extensions are not checked for update compatibility, see:
1010 //
1011 // RFC 8446 4.1.2
1012 // If a "key_share" extension was supplied in the HelloRetryRequest,
1013 // replacing the list of shares with a list containing a single
1014 // KeyShareEntry from the indicated group.
1015 //
1016 // Updating the "pre_shared_key" extension if present by recomputing
1017 // the "obfuscated_ticket_age" and binder values and (optionally)
1018 // removing any PSKs which are incompatible with the server's
1019 // indicated cipher suite.
1020 //
1021 // Optionally adding, removing, or changing the length of the
1022 // "padding" extension.
1023}
1024
1025void Client_Hello_13::calculate_psk_binders(Transcript_Hash_State ths) {
1026 auto psk = m_data->extensions().get<PSK>();
1027 if(!psk || psk->empty()) {
1028 return;
1029 }
1030
1031 // RFC 8446 4.2.11.2
1032 // Each entry in the binders list is computed as an HMAC over a
1033 // transcript hash (see Section 4.4.1) containing a partial ClientHello
1034 // [...].
1035 //
1036 // Therefore we marshal the entire message prematurely to obtain the
1037 // (truncated) transcript hash, calculate the PSK binders with it, update
1038 // the Client Hello thus finalizing the message. Down the road, it will be
1039 // re-marshalled with the correct binders and sent over the wire.
1041 psk->calculate_binders(ths);
1042}
1043
1044std::optional<Protocol_Version> Client_Hello_13::highest_supported_version(const Policy& policy) const {
1045 // RFC 8446 4.2.1
1046 // The "supported_versions" extension is used by the client to indicate
1047 // which versions of TLS it supports and by the server to indicate which
1048 // version it is using. The extension contains a list of supported
1049 // versions in preference order, with the most preferred version first.
1050 const auto supvers = m_data->extensions().get<Supported_Versions>();
1051 BOTAN_ASSERT_NONNULL(supvers);
1052
1053 std::optional<Protocol_Version> result;
1054
1055 for(const auto& v : supvers->versions()) {
1056 // RFC 8446 4.2.1
1057 // Servers MUST only select a version of TLS present in that extension
1058 // and MUST ignore any unknown versions that are present in that
1059 // extension.
1060 if(!v.known_version() || !policy.acceptable_protocol_version(v)) {
1061 continue;
1062 }
1063
1064 result = (result.has_value()) ? std::optional(std::max(result.value(), v)) : std::optional(v);
1065 }
1066
1067 return result;
1068}
1069
1070#endif // BOTAN_HAS_TLS_13
1071
1072} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:41
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:86
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:179
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
const std::vector< uint8_t > & get_cookie() const
static Extension_Code static_type()
static Extension_Code static_type()
void deserialize(TLS_Data_Reader &reader, Connection_Side from, Handshake_Type message_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)
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 std::vector< uint8_t > & renegotiation_info() 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
std::optional< Session_Ticket > ticket() const
std::optional< Session_ID > id() const
std::vector< Group_Params > ec_groups() const
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:180
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:32
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:60
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:707