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