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