• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 22045650098

16 Feb 2026 12:06AM UTC coverage: 90.042% (-0.001%) from 90.043%
22045650098

Pull #5343

github

web-flow
Merge 497a2bc56 into c5489e013
Pull Request #5343: Avoid using <algorithm> in tls_session_id.h

102324 of 113640 relevant lines covered (90.04%)

11427682.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.76
/src/lib/tls/tls13/msg_client_hello_13.cpp
1
/*
2
* TLS Client Hello Messages
3
* (C) 2004-2011,2015,2016 Jack Lloyd
4
*     2021 Elektrobit Automotive GmbH
5
*     2022 René Meusel, Hannes Rantzsch - neXenio GmbH
6
*     2026 René Meusel - Rohde & Schwarz Cybersecurity GmbH
7
*
8
* Botan is released under the Simplified BSD License (see license.txt)
9
*/
10

11
#include <botan/tls_messages_13.h>
12

13
#include <botan/assert.h>
14
#include <botan/tls_alert.h>
15
#include <botan/tls_callbacks.h>
16
#include <botan/tls_exceptn.h>
17
#include <botan/tls_policy.h>
18
#include <botan/internal/tls_handshake_layer_13.h>
19
#include <botan/internal/tls_messages_internal.h>
20
#include <botan/internal/tls_transcript_hash_13.h>
21
#include <algorithm>
22

23
namespace Botan::TLS {
24

25
Client_Hello_13::Client_Hello_13(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
465✔
26
   const auto& exts = m_data->extensions();
465✔
27

28
   // RFC 8446 4.1.2
29
   //    TLS 1.3 ClientHellos are identified as having a legacy_version of
30
   //    0x0303 and a "supported_versions" extension present with 0x0304 as the
31
   //    highest version indicated therein.
32
   //
33
   // Note that we already checked for "supported_versions" before entering this
34
   // c'tor in `Client_Hello_13::parse()`. This is just to be doubly sure.
35
   BOTAN_ASSERT_NOMSG(exts.has<Supported_Versions>());
465✔
36

37
   // RFC 8446 4.2.1
38
   //    Servers MAY abort the handshake upon receiving a ClientHello with
39
   //    legacy_version 0x0304 or later.
40
   if(m_data->legacy_version().is_tls_13_or_later()) {
465✔
41
      throw TLS_Exception(Alert::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version");
1✔
42
   }
43

44
   // RFC 8446 4.1.2
45
   //    For every TLS 1.3 ClientHello, [the compression method] MUST contain
46
   //    exactly one byte, set to zero, [...].  If a TLS 1.3 ClientHello is
47
   //    received with any other value in this field, the server MUST abort the
48
   //    handshake with an "illegal_parameter" alert.
49
   if(m_data->comp_methods().size() != 1 || m_data->comp_methods().front() != 0) {
464✔
50
      throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
4✔
51
   }
52

53
   // RFC 8446 4.2.9
54
   //    A client MUST provide a "psk_key_exchange_modes" extension if it
55
   //    offers a "pre_shared_key" extension. If clients offer "pre_shared_key"
56
   //    without a "psk_key_exchange_modes" extension, servers MUST abort
57
   //    the handshake.
58
   if(exts.has<PSK>()) {
460✔
59
      if(!exts.has<PSK_Key_Exchange_Modes>()) {
116✔
60
         throw TLS_Exception(Alert::MissingExtension,
1✔
61
                             "Client Hello offered a PSK without a psk_key_exchange_modes extension");
1✔
62
      }
63

64
      // RFC 8446 4.2.11
65
      //     The "pre_shared_key" extension MUST be the last extension in the
66
      //     ClientHello [...]. Servers MUST check that it is the last extension
67
      //     and otherwise fail the handshake with an "illegal_parameter" alert.
68
      if(exts.all().back()->type() != Extension_Code::PresharedKey) {
115✔
69
         throw TLS_Exception(Alert::IllegalParameter, "PSK extension was not at the very end of the Client Hello");
2✔
70
      }
71
   }
72

73
   // RFC 8446 9.2
74
   //    [A TLS 1.3 ClientHello] message MUST meet the following requirements:
75
   //
76
   //     -  If not containing a "pre_shared_key" extension, it MUST contain
77
   //        both a "signature_algorithms" extension and a "supported_groups"
78
   //        extension.
79
   //
80
   //     -  If containing a "supported_groups" extension, it MUST also contain
81
   //        a "key_share" extension, and vice versa.  An empty
82
   //        KeyShare.client_shares vector is permitted.
83
   //
84
   //    Servers receiving a ClientHello which does not conform to these
85
   //    requirements MUST abort the handshake with a "missing_extension"
86
   //    alert.
87
   if(!exts.has<PSK>()) {
457✔
88
      if(!exts.has<Supported_Groups>() || !exts.has<Signature_Algorithms>()) {
687✔
89
         throw TLS_Exception(
2✔
90
            Alert::MissingExtension,
91
            "Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions");
2✔
92
      }
93
   }
94
   if(exts.has<Supported_Groups>() != exts.has<Key_Share>()) {
455✔
95
      throw TLS_Exception(Alert::MissingExtension,
2✔
96
                          "Client Hello must either contain both key_share and supported_groups extensions or neither");
2✔
97
   }
98

99
   if(exts.has<Key_Share>()) {
453✔
100
      auto* const supported_ext = exts.get<Supported_Groups>();
453✔
101
      BOTAN_ASSERT_NONNULL(supported_ext);
453✔
102
      const auto supports = supported_ext->groups();
453✔
103
      const auto offers = exts.get<Key_Share>()->offered_groups();
453✔
104

105
      // RFC 8446 4.2.8
106
      //    Each KeyShareEntry value MUST correspond to a group offered in the
107
      //    "supported_groups" extension and MUST appear in the same order.
108
      //    [...]
109
      //    Clients MUST NOT offer any KeyShareEntry values for groups not
110
      //    listed in the client's "supported_groups" extension.
111
      //
112
      // Note: We can assume that both `offers` and `supports` are unique lists
113
      //       as this is ensured in the parsing code of the extensions.
114
      auto found_in_supported_groups = [&supports, support_offset = -1](auto group) mutable {
2,363✔
115
         const auto i = std::find(supports.begin(), supports.end(), group);
1,910✔
116
         if(i == supports.end()) {
1,910✔
117
            return false;
118
         }
119

120
         const auto found_at = std::distance(supports.begin(), i);
1,910✔
121
         if(found_at <= support_offset) {
1,910✔
122
            return false;  // The order that groups appear in "key_share" and
123
                           // "supported_groups" must be the same
124
         }
125

126
         support_offset = static_cast<decltype(support_offset)>(found_at);
1,910✔
127
         return true;
1,910✔
128
      };
453✔
129

130
      for(const auto offered : offers) {
2,363✔
131
         // RFC 8446 4.2.8
132
         //    Servers MAY check for violations of these rules and abort the
133
         //    handshake with an "illegal_parameter" alert if one is violated.
134
         if(!found_in_supported_groups(offered)) {
1,910✔
135
            throw TLS_Exception(Alert::IllegalParameter,
×
136
                                "Offered key exchange groups do not align with claimed supported groups");
×
137
         }
138
      }
139
   }
906✔
140

141
   // TODO: Reject oid_filters extension if found (which is the only known extension that
142
   //       must not occur in the TLS 1.3 client hello.
143
   // RFC 8446 4.2.5
144
   //    [The oid_filters extension] MUST only be sent in the CertificateRequest message.
145
}
465✔
146

147
/*
148
 * Create a new Client Hello message
149
 */
150
Client_Hello_13::Client_Hello_13(const Policy& policy,
988✔
151
                                 Callbacks& cb,
152
                                 RandomNumberGenerator& rng,
153
                                 std::string_view hostname,
154
                                 const std::vector<std::string>& next_protocols,
155
                                 std::optional<Session_with_Handle>& session,
156
                                 std::vector<ExternalPSK> psks) {
988✔
157
   // RFC 8446 4.1.2
158
   //    In TLS 1.3, the client indicates its version preferences in the
159
   //    "supported_versions" extension (Section 4.2.1) and the
160
   //    legacy_version field MUST be set to 0x0303, which is the version
161
   //    number for TLS 1.2.
162
   m_data->m_legacy_version = Protocol_Version::TLS_V12;
988✔
163
   m_data->m_random = make_hello_random(rng, cb, policy);
988✔
164
   m_data->m_suites = policy.ciphersuite_list(Protocol_Version::TLS_V13);
988✔
165

166
   if(policy.allow_tls12()) {
988✔
167
      // Note: DTLS 1.3 is NYI, hence dtls_12 is not checked
168
      const auto legacy_suites = policy.ciphersuite_list(Protocol_Version::TLS_V12);
959✔
169
      m_data->m_suites.insert(m_data->m_suites.end(), legacy_suites.cbegin(), legacy_suites.cend());
959✔
170
   }
959✔
171

172
   if(policy.tls_13_middlebox_compatibility_mode()) {
988✔
173
      // RFC 8446 4.1.2
174
      //    In compatibility mode (see Appendix D.4), this field MUST be non-empty,
175
      //    so a client not offering a pre-TLS 1.3 session MUST generate a new
176
      //    32-byte value.
177
      //
178
      // Note: we won't ever offer a TLS 1.2 session. In such a case we would
179
      //       have instantiated a TLS 1.2 client in the first place.
180
      m_data->m_session_id = Session_ID(make_hello_random(rng, cb, policy));
975✔
181
   }
182

183
   // NOLINTBEGIN(*-owning-memory)
184
   if(Server_Name_Indicator::hostname_acceptable_for_sni(hostname)) {
988✔
185
      m_data->extensions().add(new Server_Name_Indicator(hostname));
964✔
186
   }
187

188
   m_data->extensions().add(new Supported_Groups(policy.key_exchange_groups()));
988✔
189

190
   m_data->extensions().add(new Key_Share(policy, cb, rng));
988✔
191

192
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13, policy));
988✔
193

194
   m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
988✔
195
   if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
988✔
196
      // RFC 8446 4.2.3
197
      //    Implementations which have the same policy in both cases MAY omit
198
      //    the "signature_algorithms_cert" extension.
199
      m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
×
200
   }
×
201

202
   // TODO: Support for PSK-only mode without a key exchange.
203
   //       This should be configurable in TLS::Policy and should allow no PSK
204
   //       support at all (e.g. to disable support for session resumption).
205
   m_data->extensions().add(new PSK_Key_Exchange_Modes({PSK_Key_Exchange_Mode::PSK_DHE_KE}));
988✔
206

207
   if(policy.support_cert_status_message()) {
988✔
208
      m_data->extensions().add(new Certificate_Status_Request({}, {}));
212✔
209
   }
210

211
   // We currently support "record_size_limit" for TLS 1.3 exclusively. Hence,
212
   // when TLS 1.2 is advertised as a supported protocol, we must not offer this
213
   // extension.
214
   if(policy.record_size_limit().has_value() && !policy.allow_tls12()) {
988✔
215
      m_data->extensions().add(new Record_Size_Limit(policy.record_size_limit().value()));
16✔
216
   }
217

218
   if(!next_protocols.empty()) {
988✔
219
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocols));
11✔
220
   }
221

222
   // RFC 7250 4.1
223
   //    In order to indicate the support of raw public keys, clients include
224
   //    the client_certificate_type and/or the server_certificate_type
225
   //    extensions in an extended client hello message.
226
   m_data->extensions().add(new Client_Certificate_Type(policy.accepted_client_certificate_types()));
1,976✔
227
   m_data->extensions().add(new Server_Certificate_Type(policy.accepted_server_certificate_types()));
1,976✔
228

229
   if(policy.allow_tls12()) {
988✔
230
      m_data->extensions().add(new Renegotiation_Extension());
959✔
231
      m_data->extensions().add(new Session_Ticket_Extension());
959✔
232

233
      // EMS must always be used with TLS 1.2, regardless of the policy
234
      m_data->extensions().add(new Extended_Master_Secret);
959✔
235

236
      if(policy.negotiate_encrypt_then_mac()) {
959✔
237
         m_data->extensions().add(new Encrypt_then_MAC);
959✔
238
      }
239

240
      if(m_data->extensions().has<Supported_Groups>() &&
1,918✔
241
         !m_data->extensions().get<Supported_Groups>()->ec_groups().empty()) {
1,918✔
242
         m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
957✔
243
      }
244
   }
245

246
   if(session.has_value() || !psks.empty()) {
988✔
247
      m_data->extensions().add(new PSK(session, std::move(psks), cb));
108✔
248
   }
249
   // NOLINTEND(*-owning-memory)
250

251
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
988✔
252

253
   if(m_data->extensions().has<PSK>()) {
988✔
254
      // RFC 8446 4.2.11
255
      //    The "pre_shared_key" extension MUST be the last extension in the
256
      //    ClientHello (this facilitates implementation [...]).
257
      if(m_data->extensions().all().back()->type() != Extension_Code::PresharedKey) {
108✔
258
         throw TLS_Exception(Alert::InternalError,
×
259
                             "Application modified extensions of Client Hello, PSK is not last anymore");
×
260
      }
261
      calculate_psk_binders({});
108✔
262
   }
263
}
988✔
264

265
std::variant<Client_Hello_13, Client_Hello_12_Shim> Client_Hello_13::parse(const std::vector<uint8_t>& buf) {
1,004✔
266
   auto data = std::make_unique<Client_Hello_Internal>(buf);
1,004✔
267
   const auto version = data->version();
978✔
268

269
   if(version.is_pre_tls_13()) {
978✔
270
      return Client_Hello_12_Shim(std::move(data));
1,026✔
271
   } else {
272
      return Client_Hello_13(std::move(data));
918✔
273
   }
274
}
978✔
275

276
void Client_Hello_13::retry(const Hello_Retry_Request& hrr,
61✔
277
                            const Transcript_Hash_State& transcript_hash_state,
278
                            Callbacks& cb,
279
                            RandomNumberGenerator& rng) {
280
   BOTAN_STATE_CHECK(m_data->extensions().has<Supported_Groups>());
61✔
281
   BOTAN_STATE_CHECK(m_data->extensions().has<Key_Share>());
61✔
282

283
   auto* hrr_ks = hrr.extensions().get<Key_Share>();
61✔
284
   const auto& supported_groups = m_data->extensions().get<Supported_Groups>()->groups();
61✔
285

286
   if(hrr.extensions().has<Key_Share>()) {
61✔
287
      m_data->extensions().get<Key_Share>()->retry_offer(*hrr_ks, supported_groups, cb, rng);
60✔
288
   }
289

290
   // RFC 8446 4.2.2
291
   //    When sending the new ClientHello, the client MUST copy
292
   //    the contents of the extension received in the HelloRetryRequest into
293
   //    a "cookie" extension in the new ClientHello.
294
   //
295
   // RFC 8446 4.2.2
296
   //    Clients MUST NOT use cookies in their initial ClientHello in subsequent
297
   //    connections.
298
   if(hrr.extensions().has<Cookie>()) {
58✔
299
      BOTAN_STATE_CHECK(!m_data->extensions().has<Cookie>());
3✔
300
      m_data->extensions().add(new Cookie(hrr.extensions().get<Cookie>()->get_cookie()));  // NOLINT(*-owning-memory)
3✔
301
   }
302

303
   // Note: the consumer of the TLS implementation won't be able to distinguish
304
   //       invocations to this callback due to the first Client_Hello or the
305
   //       retried Client_Hello after receiving a Hello_Retry_Request. We assume
306
   //       that the user keeps and detects this state themselves.
307
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
58✔
308

309
   auto* psk = m_data->extensions().get<PSK>();
58✔
310
   if(psk != nullptr) {
58✔
311
      // Cipher suite should always be a known suite as this is checked upstream
312
      const auto cipher = Ciphersuite::by_id(hrr.ciphersuite());
11✔
313
      BOTAN_ASSERT_NOMSG(cipher.has_value());
11✔
314

315
      // RFC 8446 4.1.4
316
      //    In [...] its updated ClientHello, the client SHOULD NOT offer
317
      //    any pre-shared keys associated with a hash other than that of the
318
      //    selected cipher suite.
319
      psk->filter(cipher.value());
11✔
320

321
      // RFC 8446 4.2.11.2
322
      //    If the server responds with a HelloRetryRequest and the client
323
      //    then sends ClientHello2, its binder will be computed over: [...].
324
      calculate_psk_binders(transcript_hash_state.clone());
11✔
325
   }
326
}
58✔
327

328
void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) {
44✔
329
   // RFC 8446 4.1.2
330
   //    The client will also send a ClientHello when the server has responded
331
   //    to its ClientHello with a HelloRetryRequest. In that case, the client
332
   //    MUST send the same ClientHello without modification, except as follows:
333

334
   if(m_data->session_id() != new_ch.m_data->session_id() || m_data->random() != new_ch.m_data->random() ||
44✔
335
      m_data->ciphersuites() != new_ch.m_data->ciphersuites() ||
88✔
336
      m_data->comp_methods() != new_ch.m_data->comp_methods()) {
44✔
337
      throw TLS_Exception(Alert::IllegalParameter, "Client Hello core values changed after Hello Retry Request");
×
338
   }
339

340
   const auto oldexts = extension_types();
44✔
341
   const auto newexts = new_ch.extension_types();
44✔
342

343
   // Check that extension omissions are justified
344
   for(const auto oldext : oldexts) {
502✔
345
      if(!newexts.contains(oldext)) {
918✔
346
         auto* const ext = extensions().get(oldext);
1✔
347

348
         // We don't make any assumptions about unimplemented extensions.
349
         if(!ext->is_implemented()) {
1✔
350
            continue;
×
351
         }
352

353
         // RFC 8446 4.1.2
354
         //    Removing the "early_data" extension (Section 4.2.10) if one was
355
         //    present.  Early data is not permitted after a HelloRetryRequest.
356
         if(oldext == EarlyDataIndication::static_type()) {
1✔
357
            continue;
×
358
         }
359

360
         // RFC 8446 4.1.2
361
         //    Optionally adding, removing, or changing the length of the
362
         //    "padding" extension.
363
         //
364
         // TODO: implement the Padding extension
365
         // if(oldext == Padding::static_type())
366
         //    continue;
367

368
         throw TLS_Exception(Alert::IllegalParameter, "Extension removed in updated Client Hello");
1✔
369
      }
370
   }
371

372
   // Check that extension additions are justified
373
   for(const auto newext : newexts) {
495✔
374
      if(!oldexts.contains(newext)) {
904✔
375
         auto* const ext = new_ch.extensions().get(newext);
2✔
376

377
         // We don't make any assumptions about unimplemented extensions.
378
         if(!ext->is_implemented()) {
2✔
379
            continue;
1✔
380
         }
381

382
         // RFC 8446 4.1.2
383
         //    Including a "cookie" extension if one was provided in the
384
         //    HelloRetryRequest.
385
         if(newext == Cookie::static_type()) {
1✔
386
            continue;
1✔
387
         }
388

389
         // RFC 8446 4.1.2
390
         //    Optionally adding, removing, or changing the length of the
391
         //    "padding" extension.
392
         //
393
         // TODO: implement the Padding extension
394
         // if(newext == Padding::static_type())
395
         //    continue;
396

397
         throw TLS_Exception(Alert::UnsupportedExtension, "Added an extension in updated Client Hello");
×
398
      }
399
   }
400

401
   // RFC 8446 4.1.2
402
   //    Removing the "early_data" extension (Section 4.2.10) if one was
403
   //    present.  Early data is not permitted after a HelloRetryRequest.
404
   if(new_ch.extensions().has<EarlyDataIndication>()) {
43✔
405
      throw TLS_Exception(Alert::IllegalParameter, "Updated Client Hello indicates early data");
×
406
   }
407

408
   // TODO: Contents of extensions are not checked for update compatibility, see:
409
   //
410
   // RFC 8446 4.1.2
411
   //    If a "key_share" extension was supplied in the HelloRetryRequest,
412
   //    replacing the list of shares with a list containing a single
413
   //    KeyShareEntry from the indicated group.
414
   //
415
   //    Updating the "pre_shared_key" extension if present by recomputing
416
   //    the "obfuscated_ticket_age" and binder values and (optionally)
417
   //    removing any PSKs which are incompatible with the server's
418
   //    indicated cipher suite.
419
   //
420
   //    Optionally adding, removing, or changing the length of the
421
   //    "padding" extension.
422
}
44✔
423

424
void Client_Hello_13::calculate_psk_binders(Transcript_Hash_State transcript_hash) {
119✔
425
   auto* psk = m_data->extensions().get<PSK>();
119✔
426
   if(psk == nullptr || psk->empty()) {
119✔
427
      return;
1✔
428
   }
429

430
   // RFC 8446 4.2.11.2
431
   //    Each entry in the binders list is computed as an HMAC over a
432
   //    transcript hash (see Section 4.4.1) containing a partial ClientHello
433
   //    [...].
434
   //
435
   // Therefore we marshal the entire message prematurely to obtain the
436
   // (truncated) transcript hash, calculate the PSK binders with it, update
437
   // the Client Hello thus finalizing the message. Down the road, it will be
438
   // re-marshalled with the correct binders and sent over the wire.
439
   Handshake_Layer::prepare_message(*this, transcript_hash);
118✔
440
   psk->calculate_binders(transcript_hash);
118✔
441
}
442

443
std::optional<Protocol_Version> Client_Hello_13::highest_supported_version(const Policy& policy) const {
390✔
444
   // RFC 8446 4.2.1
445
   //    The "supported_versions" extension is used by the client to indicate
446
   //    which versions of TLS it supports and by the server to indicate which
447
   //    version it is using. The extension contains a list of supported
448
   //    versions in preference order, with the most preferred version first.
449
   auto* const supvers = m_data->extensions().get<Supported_Versions>();
390✔
450
   BOTAN_ASSERT_NONNULL(supvers);
390✔
451

452
   std::optional<Protocol_Version> result;
390✔
453

454
   for(const auto& v : supvers->versions()) {
1,977✔
455
      // RFC 8446 4.2.1
456
      //    Servers MUST only select a version of TLS present in that extension
457
      //    and MUST ignore any unknown versions that are present in that
458
      //    extension.
459
      if(!v.known_version() || !policy.acceptable_protocol_version(v)) {
1,587✔
460
         continue;
899✔
461
      }
462

463
      result = (result.has_value()) ? std::optional(std::max(result.value(), v)) : std::optional(v);
986✔
464
   }
465

466
   return result;
390✔
467
}
468

469
}  // namespace Botan::TLS
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc