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

randombit / botan / 5123321399

30 May 2023 04:06PM UTC coverage: 92.213% (+0.004%) from 92.209%
5123321399

Pull #3558

github

web-flow
Merge dd72f7389 into 057bcbc35
Pull Request #3558: Add braces around all if/else statements

75602 of 81986 relevant lines covered (92.21%)

11859779.3 hits per line

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

92.04
/src/lib/tls/msg_client_hello.cpp
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

35
namespace Botan::TLS {
36

37
enum {
38
   TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF,
39
};
40

41
std::vector<uint8_t> make_hello_random(RandomNumberGenerator& rng, Callbacks& cb, const Policy& policy) {
6,682✔
42
   auto buf = rng.random_vec<std::vector<uint8_t>>(32);
6,682✔
43

44
   if(policy.hash_hello_random()) {
6,682✔
45
      auto sha256 = HashFunction::create_or_throw("SHA-256");
6,671✔
46
      sha256->update(buf);
6,671✔
47
      sha256->final(buf);
6,671✔
48
   }
6,671✔
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())) {
6,682✔
54
      const uint32_t time32 = static_cast<uint32_t>(std::chrono::system_clock::to_time_t(cb.tls_current_timestamp()));
6,663✔
55

56
      store_be(time32, buf.data());
6,663✔
57
   }
58

59
   return buf;
6,682✔
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
 */
67
class Client_Hello_Internal {
68
   public:
69
      Client_Hello_Internal() : m_comp_methods({0}) {}
3,588✔
70

71
      Client_Hello_Internal(const std::vector<uint8_t>& buf) {
3,714✔
72
         if(buf.size() < 41) {
3,714✔
73
            throw Decoding_Error("Client_Hello: Packet corrupted");
45✔
74
         }
75

76
         TLS_Data_Reader reader("ClientHello", buf);
3,669✔
77

78
         const uint8_t major_version = reader.get_byte();
3,669✔
79
         const uint8_t minor_version = reader.get_byte();
3,669✔
80

81
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,669✔
82
         m_random = reader.get_fixed<uint8_t>(32);
3,669✔
83
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,669✔
84

85
         if(m_legacy_version.is_datagram_protocol()) {
2,829✔
86
            auto sha256 = HashFunction::create_or_throw("SHA-256");
744✔
87
            sha256->update(reader.get_data_read_so_far());
744✔
88

89
            m_hello_cookie = reader.get_range<uint8_t>(1, 0, 255);
744✔
90

91
            sha256->update(reader.get_remaining());
744✔
92
            m_cookie_input_bits = sha256->final_stdvec();
744✔
93
         }
744✔
94

95
         m_suites = reader.get_range_vector<uint16_t>(2, 1, 32767);
2,829✔
96
         m_comp_methods = reader.get_range_vector<uint8_t>(1, 1, 255);
2,705✔
97

98
         m_extensions.deserialize(reader, Connection_Side::Client, Handshake_Type::ClientHello);
2,705✔
99
      }
4,781✔
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 {
921✔
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>() ||
1,378✔
127
            !extensions().get<Supported_Versions>()->supports(Protocol_Version::TLS_V13)) {
457✔
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;
958✔
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;
442✔
136
      }
137

138
      Protocol_Version legacy_version() const { return m_legacy_version; }
14,224✔
139

140
      const Session_ID& session_id() const { return m_session_id; }
30✔
141

142
      const std::vector<uint8_t>& random() const { return m_random; }
4,178✔
143

144
      const std::vector<uint16_t>& ciphersuites() const { return m_suites; }
4,360✔
145

146
      const std::vector<uint8_t>& comp_methods() const { return m_comp_methods; }
4,589✔
147

148
      const std::vector<uint8_t>& hello_cookie() const { return m_hello_cookie; }
861✔
149

150
      const std::vector<uint8_t>& hello_cookie_input_bits() const { return m_cookie_input_bits; }
734✔
151

152
      const Extensions& extensions() const { return m_extensions; }
921✔
153

154
      Extensions& extensions() { return m_extensions; }
73,627✔
155

156
   public:
157
      Protocol_Version m_legacy_version;
158
      Session_ID m_session_id;
159
      std::vector<uint8_t> m_random;
160
      std::vector<uint16_t> m_suites;
161
      std::vector<uint8_t> m_comp_methods;
162
      Extensions m_extensions;
163

164
      std::vector<uint8_t> m_hello_cookie;       // DTLS only
165
      std::vector<uint8_t> m_cookie_input_bits;  // DTLS only
166
};
167

168
Client_Hello::Client_Hello(Client_Hello&&) noexcept = default;
9,933✔
169
Client_Hello& Client_Hello::operator=(Client_Hello&&) noexcept = default;
29✔
170

171
Client_Hello::~Client_Hello() = default;
16,179✔
172

173
Client_Hello::Client_Hello() : m_data(std::make_unique<Client_Hello_Internal>()) {}
3,588✔
174

175
/*
176
* Read a counterparty client hello
177
*/
178
Client_Hello::Client_Hello(std::unique_ptr<Client_Hello_Internal> data) : m_data(std::move(data)) {
2,675✔
179
   BOTAN_ASSERT_NONNULL(m_data);
2,675✔
180
}
2,675✔
181

182
Handshake_Type Client_Hello::type() const { return Handshake_Type::ClientHello; }
15,486✔
183

184
Protocol_Version Client_Hello::legacy_version() const { return m_data->legacy_version(); }
4,784✔
185

186
const std::vector<uint8_t>& Client_Hello::random() const { return m_data->random(); }
3,495✔
187

188
const Session_ID& Client_Hello::session_id() const { return m_data->session_id(); }
3,060✔
189

190
const std::vector<uint8_t>& Client_Hello::compression_methods() const { return m_data->comp_methods(); }
1,289✔
191

192
const std::vector<uint16_t>& Client_Hello::ciphersuites() const { return m_data->ciphersuites(); }
1,343✔
193

194
std::set<Extension_Code> Client_Hello::extension_types() const { return m_data->extensions().extension_types(); }
1,958✔
195

196
const Extensions& Client_Hello::extensions() const { return m_data->extensions(); }
8,527✔
197

198
void Client_Hello_12::update_hello_cookie(const Hello_Verify_Request& hello_verify) {
422✔
199
   BOTAN_STATE_CHECK(m_data->legacy_version().is_datagram_protocol());
422✔
200

201
   m_data->m_hello_cookie = hello_verify.cookie();
422✔
202
}
422✔
203

204
/*
205
* Serialize a Client Hello message
206
*/
207
std::vector<uint8_t> Client_Hello::serialize() const {
4,148✔
208
   std::vector<uint8_t> buf;
4,148✔
209
   buf.reserve(1024);  // working around GCC warning
4,148✔
210

211
   buf.push_back(m_data->legacy_version().major_version());
4,148✔
212
   buf.push_back(m_data->legacy_version().minor_version());
4,148✔
213
   buf += m_data->random();
4,148✔
214

215
   append_tls_length_value(buf, m_data->session_id().get(), 1);
4,148✔
216

217
   if(m_data->legacy_version().is_datagram_protocol()) {
4,148✔
218
      append_tls_length_value(buf, m_data->hello_cookie(), 1);
861✔
219
   }
220

221
   append_tls_length_value(buf, m_data->ciphersuites(), 2);
4,148✔
222
   append_tls_length_value(buf, m_data->comp_methods(), 1);
4,148✔
223

224
   /*
225
   * May not want to send extensions at all in some cases. If so,
226
   * should include SCSV value (if reneg info is empty, if not we are
227
   * renegotiating with a modern server)
228
   */
229

230
   buf += m_data->extensions().serialize(Connection_Side::Client);
4,148✔
231

232
   return buf;
4,148✔
233
}
×
234

235
std::vector<uint8_t> Client_Hello::cookie_input_data() const {
734✔
236
   BOTAN_STATE_CHECK(!m_data->hello_cookie_input_bits().empty());
734✔
237

238
   return m_data->hello_cookie_input_bits();
734✔
239
}
240

241
/*
242
* Check if we offered this ciphersuite
243
*/
244
bool Client_Hello::offered_suite(uint16_t ciphersuite) const {
5,009✔
245
   return std::find(m_data->ciphersuites().cbegin(), m_data->ciphersuites().cend(), ciphersuite) !=
5,009✔
246
          m_data->ciphersuites().cend();
5,009✔
247
}
248

249
std::vector<Signature_Scheme> Client_Hello::signature_schemes() const {
3,674✔
250
   if(Signature_Algorithms* sigs = m_data->extensions().get<Signature_Algorithms>()) {
3,674✔
251
      return sigs->supported_schemes();
3,672✔
252
   }
253
   return {};
2✔
254
}
255

256
std::vector<Signature_Scheme> Client_Hello::certificate_signature_schemes() const {
948✔
257
   // RFC 8446 4.2.3
258
   //   If no "signature_algorithms_cert" extension is present, then the
259
   //   "signature_algorithms" extension also applies to signatures appearing
260
   //   in certificates.
261
   if(Signature_Algorithms_Cert* sigs = m_data->extensions().get<Signature_Algorithms_Cert>()) {
948✔
262
      return sigs->supported_schemes();
×
263
   } else {
264
      return signature_schemes();
948✔
265
   }
266
}
267

268
std::vector<Group_Params> Client_Hello::supported_ecc_curves() const {
1,253✔
269
   if(Supported_Groups* groups = m_data->extensions().get<Supported_Groups>()) {
1,253✔
270
      return groups->ec_groups();
1,250✔
271
   }
272
   return {};
3✔
273
}
274

275
std::vector<Group_Params> Client_Hello::supported_dh_groups() const {
4✔
276
   if(Supported_Groups* groups = m_data->extensions().get<Supported_Groups>()) {
4✔
277
      return groups->dh_groups();
4✔
278
   }
279
   return std::vector<Group_Params>();
×
280
}
281

282
bool Client_Hello_12::prefers_compressed_ec_points() const {
69✔
283
   if(Supported_Point_Formats* ecc_formats = m_data->extensions().get<Supported_Point_Formats>()) {
69✔
284
      return ecc_formats->prefers_compressed();
69✔
285
   }
286
   return false;
287
}
288

289
std::string Client_Hello::sni_hostname() const {
3,900✔
290
   if(Server_Name_Indicator* sni = m_data->extensions().get<Server_Name_Indicator>()) {
3,900✔
291
      return sni->host_name();
3,770✔
292
   }
293
   return "";
130✔
294
}
295

296
bool Client_Hello_12::secure_renegotiation() const { return m_data->extensions().has<Renegotiation_Extension>(); }
4,955✔
297

298
std::vector<uint8_t> Client_Hello_12::renegotiation_info() const {
4,011✔
299
   if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
4,011✔
300
      return reneg->renegotiation_info();
4,011✔
301
   }
302
   return {};
×
303
}
304

305
std::vector<Protocol_Version> Client_Hello::supported_versions() const {
1,291✔
306
   if(Supported_Versions* versions = m_data->extensions().get<Supported_Versions>()) {
1,291✔
307
      return versions->versions();
207✔
308
   }
309
   return {};
1,084✔
310
}
311

312
bool Client_Hello_12::supports_session_ticket() const { return m_data->extensions().has<Session_Ticket_Extension>(); }
1,139✔
313

314
Session_Ticket Client_Hello_12::session_ticket() const {
1,836✔
315
   if(auto* ticket = m_data->extensions().get<Session_Ticket_Extension>()) {
1,836✔
316
      return ticket->contents();
1,696✔
317
   }
318
   return {};
140✔
319
}
320

321
std::optional<Session_Handle> Client_Hello_12::session_handle() const {
921✔
322
   // RFC 5077 3.4
323
   //    If a ticket is presented by the client, the server MUST NOT attempt
324
   //    to use the Session ID in the ClientHello for stateful session
325
   //    resumption.
326
   if(auto ticket = session_ticket(); !ticket.empty()) {
921✔
327
      return ticket;
200✔
328
   } else if(const auto& id = session_id(); !id.empty()) {
721✔
329
      return id;
975✔
330
   } else {
331
      return std::nullopt;
667✔
332
   }
921✔
333
}
334

335
bool Client_Hello::supports_alpn() const { return m_data->extensions().has<Application_Layer_Protocol_Notification>(); }
1,057✔
336

337
bool Client_Hello_12::supports_extended_master_secret() const {
1,141✔
338
   return m_data->extensions().has<Extended_Master_Secret>();
1,141✔
339
}
340

341
bool Client_Hello_12::supports_cert_status_message() const {
1,311✔
342
   return m_data->extensions().has<Certificate_Status_Request>();
1,311✔
343
}
344

345
bool Client_Hello_12::supports_encrypt_then_mac() const { return m_data->extensions().has<Encrypt_then_MAC>(); }
537✔
346

347
bool Client_Hello::sent_signature_algorithms() const { return m_data->extensions().has<Signature_Algorithms>(); }
×
348

349
std::vector<std::string> Client_Hello::next_protocols() const {
142✔
350
   if(auto alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
142✔
351
      return alpn->protocols();
142✔
352
   }
353
   return {};
×
354
}
355

356
std::vector<uint16_t> Client_Hello::srtp_profiles() const {
265✔
357
   if(SRTP_Protection_Profiles* srtp = m_data->extensions().get<SRTP_Protection_Profiles>()) {
265✔
358
      return srtp->profiles();
4✔
359
   }
360
   return {};
261✔
361
}
362

363
const std::vector<uint8_t>& Client_Hello::cookie() const { return m_data->hello_cookie(); }
734✔
364

365
/*
366
* Create a new Hello Request message
367
*/
368
Hello_Request::Hello_Request(Handshake_IO& io) { io.send(*this); }
×
369

370
/*
371
* Deserialize a Hello Request message
372
*/
373
Hello_Request::Hello_Request(const std::vector<uint8_t>& buf) {
42✔
374
   if(!buf.empty()) {
42✔
375
      throw Decoding_Error("Bad Hello_Request, has non-zero size");
2✔
376
   }
377
}
40✔
378

379
/*
380
* Serialize a Hello Request message
381
*/
382
std::vector<uint8_t> Hello_Request::serialize() const { return std::vector<uint8_t>(); }
×
383

384
Client_Hello_12::Client_Hello_12(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
2,233✔
385
   if(offered_suite(static_cast<uint16_t>(TLS_EMPTY_RENEGOTIATION_INFO_SCSV))) {
2,233✔
386
      if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
12✔
387
         if(!reneg->renegotiation_info().empty()) {
×
388
            throw TLS_Exception(Alert::HandshakeFailure, "Client sent renegotiation SCSV and non-empty extension");
×
389
         }
390
      } else {
391
         // add fake extension
392
         m_data->extensions().add(new Renegotiation_Extension());
12✔
393
      }
394
   }
395
}
2,233✔
396

397
// Note: This delegates to the Client_Hello_12 constructor to take advantage
398
//       of the sanity checks there.
399
Client_Hello_12::Client_Hello_12(const std::vector<uint8_t>& buf) :
2,767✔
400
      Client_Hello_12(std::make_unique<Client_Hello_Internal>(buf)) {}
2,767✔
401

402
/*
403
* Create a new Client Hello message
404
*/
405
Client_Hello_12::Client_Hello_12(Handshake_IO& io,
2,426✔
406
                                 Handshake_Hash& hash,
407
                                 const Policy& policy,
408
                                 Callbacks& cb,
409
                                 RandomNumberGenerator& rng,
410
                                 const std::vector<uint8_t>& reneg_info,
411
                                 const Client_Hello_12::Settings& client_settings,
412
                                 const std::vector<std::string>& next_protocols) {
2,426✔
413
   m_data->m_legacy_version = client_settings.protocol_version();
2,426✔
414
   m_data->m_random = make_hello_random(rng, cb, policy);
2,426✔
415
   m_data->m_suites = policy.ciphersuite_list(client_settings.protocol_version());
2,426✔
416

417
   if(!policy.acceptable_protocol_version(m_data->legacy_version())) {
2,426✔
418
      throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
×
419
                           " but our own policy does not accept it");
×
420
   }
421

422
   /*
423
   * Place all empty extensions in front to avoid a bug in some systems
424
   * which reject hellos when the last extension in the list is empty.
425
   */
426

427
   // EMS must always be used with TLS 1.2, regardless of the policy used.
428
   m_data->extensions().add(new Extended_Master_Secret);
2,426✔
429

430
   if(policy.negotiate_encrypt_then_mac()) {
2,426✔
431
      m_data->extensions().add(new Encrypt_then_MAC);
2,413✔
432
   }
433

434
   m_data->extensions().add(new Session_Ticket_Extension());
2,426✔
435

436
   m_data->extensions().add(new Renegotiation_Extension(reneg_info));
2,426✔
437

438
   m_data->extensions().add(new Supported_Versions(m_data->legacy_version(), policy));
2,426✔
439

440
   if(!client_settings.hostname().empty()) {
4,964✔
441
      m_data->extensions().add(new Server_Name_Indicator(client_settings.hostname()));
7,333✔
442
   }
443

444
   if(policy.support_cert_status_message()) {
2,426✔
445
      m_data->extensions().add(new Certificate_Status_Request({}, {}));
2,127✔
446
   }
447

448
   auto supported_groups = std::make_unique<Supported_Groups>(policy.key_exchange_groups());
2,426✔
449
   if(!supported_groups->ec_groups().empty()) {
4,850✔
450
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
2,424✔
451
   }
452
   m_data->extensions().add(supported_groups.release());
2,426✔
453

454
   m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
2,426✔
455
   if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
2,426✔
456
      // RFC 8446 4.2.3
457
      //    TLS 1.2 implementations SHOULD also process this extension.
458
      //    Implementations which have the same policy in both cases MAY omit
459
      //    the "signature_algorithms_cert" extension.
460
      m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
×
461
   }
×
462

463
   if(reneg_info.empty() && !next_protocols.empty()) {
2,426✔
464
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocols));
116✔
465
   }
466

467
   if(m_data->legacy_version().is_datagram_protocol()) {
2,426✔
468
      m_data->extensions().add(new SRTP_Protection_Profiles(policy.srtp_profiles()));
704✔
469
   }
470

471
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
2,426✔
472

473
   hash.update(io.send(*this));
4,852✔
474
}
2,426✔
475

476
/*
477
* Create a new Client Hello message (session resumption case)
478
*/
479
Client_Hello_12::Client_Hello_12(Handshake_IO& io,
212✔
480
                                 Handshake_Hash& hash,
481
                                 const Policy& policy,
482
                                 Callbacks& cb,
483
                                 RandomNumberGenerator& rng,
484
                                 const std::vector<uint8_t>& reneg_info,
485
                                 const Session_with_Handle& session,
486
                                 const std::vector<std::string>& next_protocols) {
212✔
487
   m_data->m_legacy_version = session.session.version();
212✔
488
   m_data->m_random = make_hello_random(rng, cb, policy);
212✔
489

490
   // RFC 5077 3.4
491
   //    When presenting a ticket, the client MAY generate and include a
492
   //    Session ID in the TLS ClientHello. [...] If a ticket is presented by
493
   //    the client, the server MUST NOT attempt to use the Session ID in the
494
   //    ClientHello for stateful session resumption.
495
   m_data->m_session_id = session.handle.id().value_or(Session_ID(make_hello_random(rng, cb, policy)));
458✔
496
   m_data->m_suites = policy.ciphersuite_list(m_data->legacy_version());
212✔
497

498
   if(!policy.acceptable_protocol_version(session.session.version())) {
212✔
499
      throw Internal_Error("Offering " + m_data->legacy_version().to_string() +
×
500
                           " but our own policy does not accept it");
×
501
   }
502

503
   if(!value_exists(m_data->ciphersuites(), session.session.ciphersuite_code())) {
424✔
504
      m_data->m_suites.push_back(session.session.ciphersuite_code());
4✔
505
   }
506

507
   /*
508
   * As EMS must always be used with TLS 1.2, add it even if it wasn't used
509
   * in the original session. If the server understands it and follows the
510
   * RFC it should reject our resume attempt and upgrade us to a new session
511
   * with the EMS protection.
512
   */
513
   m_data->extensions().add(new Extended_Master_Secret);
212✔
514

515
   if(session.session.supports_encrypt_then_mac()) {
212✔
516
      m_data->extensions().add(new Encrypt_then_MAC);
4✔
517
   }
518

519
   if(session.handle.is_ticket()) {
212✔
520
      m_data->extensions().add(new Session_Ticket_Extension(session.handle.ticket().value()));
534✔
521
   }
522

523
   m_data->extensions().add(new Renegotiation_Extension(reneg_info));
212✔
524

525
   m_data->extensions().add(new Server_Name_Indicator(session.session.server_info().hostname()));
636✔
526

527
   if(policy.support_cert_status_message()) {
212✔
528
      m_data->extensions().add(new Certificate_Status_Request({}, {}));
33✔
529
   }
530

531
   auto supported_groups = std::make_unique<Supported_Groups>(policy.key_exchange_groups());
212✔
532

533
   if(!supported_groups->ec_groups().empty()) {
422✔
534
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
210✔
535
   }
536

537
   m_data->extensions().add(supported_groups.release());
212✔
538

539
   m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
212✔
540
   if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
212✔
541
      // RFC 8446 4.2.3
542
      //    TLS 1.2 implementations SHOULD also process this extension.
543
      //    Implementations which have the same policy in both cases MAY omit
544
      //    the "signature_algorithms_cert" extension.
545
      m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
×
546
   }
×
547

548
   if(reneg_info.empty() && !next_protocols.empty()) {
212✔
549
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocols));
18✔
550
   }
551

552
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
212✔
553

554
   hash.update(io.send(*this));
424✔
555
}
212✔
556

557
#if defined(BOTAN_HAS_TLS_13)
558

559
Client_Hello_13::Client_Hello_13(std::unique_ptr<Client_Hello_Internal> data) : Client_Hello(std::move(data)) {
442✔
560
   const auto& exts = m_data->extensions();
442✔
561

562
   // RFC 8446 4.1.2
563
   //    TLS 1.3 ClientHellos are identified as having a legacy_version of
564
   //    0x0303 and a "supported_versions" extension present with 0x0304 as the
565
   //    highest version indicated therein.
566
   //
567
   // Note that we already checked for "supported_versions" before entering this
568
   // c'tor in `Client_Hello_13::parse()`. This is just to be doubly sure.
569
   BOTAN_ASSERT_NOMSG(exts.has<Supported_Versions>());
442✔
570

571
   // RFC 8446 4.2.1
572
   //    Servers MAY abort the handshake upon receiving a ClientHello with
573
   //    legacy_version 0x0304 or later.
574
   if(m_data->legacy_version().is_tls_13_or_later()) {
442✔
575
      throw TLS_Exception(Alert::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version");
1✔
576
   }
577

578
   // RFC 8446 4.1.2
579
   //    For every TLS 1.3 ClientHello, [the compression method] MUST contain
580
   //    exactly one byte, set to zero, [...].  If a TLS 1.3 ClientHello is
581
   //    received with any other value in this field, the server MUST abort the
582
   //    handshake with an "illegal_parameter" alert.
583
   if(m_data->comp_methods().size() != 1 || m_data->comp_methods().front() != 0) {
441✔
584
      throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression");
4✔
585
   }
586

587
   // RFC 8446 4.2.9
588
   //    A client MUST provide a "psk_key_exchange_modes" extension if it
589
   //    offers a "pre_shared_key" extension. If clients offer "pre_shared_key"
590
   //    without a "psk_key_exchange_modes" extension, servers MUST abort
591
   //    the handshake.
592
   if(exts.has<PSK>()) {
437✔
593
      if(!exts.has<PSK_Key_Exchange_Modes>()) {
116✔
594
         throw TLS_Exception(Alert::MissingExtension,
1✔
595
                             "Client Hello offered a PSK without a psk_key_exchange_modes extension");
2✔
596
      }
597

598
      // RFC 8446 4.2.11
599
      //     The "pre_shared_key" extension MUST be the last extension in the
600
      //     ClientHello [...]. Servers MUST check that it is the last extension
601
      //     and otherwise fail the handshake with an "illegal_parameter" alert.
602
      if(exts.all().back()->type() != Extension_Code::PresharedKey) {
115✔
603
         throw TLS_Exception(Alert::IllegalParameter, "PSK extension was not at the very end of the Client Hello");
2✔
604
      }
605
   }
606

607
   // RFC 8446 9.2
608
   //    [A TLS 1.3 ClientHello] message MUST meet the following requirements:
609
   //
610
   //     -  If not containing a "pre_shared_key" extension, it MUST contain
611
   //        both a "signature_algorithms" extension and a "supported_groups"
612
   //        extension.
613
   //
614
   //     -  If containing a "supported_groups" extension, it MUST also contain
615
   //        a "key_share" extension, and vice versa.  An empty
616
   //        KeyShare.client_shares vector is permitted.
617
   //
618
   //    Servers receiving a ClientHello which does not conform to these
619
   //    requirements MUST abort the handshake with a "missing_extension"
620
   //    alert.
621
   if(!exts.has<PSK>()) {
434✔
622
      if(!exts.has<Supported_Groups>() || !exts.has<Signature_Algorithms>()) {
641✔
623
         throw TLS_Exception(
2✔
624
            Alert::MissingExtension,
625
            "Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions");
4✔
626
      }
627
   }
628
   if(exts.has<Supported_Groups>() != exts.has<Key_Share>()) {
432✔
629
      throw TLS_Exception(Alert::MissingExtension,
2✔
630
                          "Client Hello must either contain both key_share and supported_groups extensions or neither");
4✔
631
   }
632

633
   if(exts.has<Key_Share>()) {
430✔
634
      const auto supported_ext = exts.get<Supported_Groups>();
430✔
635
      BOTAN_ASSERT_NONNULL(supported_ext);
430✔
636
      const auto supports = supported_ext->groups();
430✔
637
      const auto offers = exts.get<Key_Share>()->offered_groups();
430✔
638

639
      // RFC 8446 4.2.8
640
      //    Each KeyShareEntry value MUST correspond to a group offered in the
641
      //    "supported_groups" extension and MUST appear in the same order.
642
      //    [...]
643
      //    Clients MUST NOT offer any KeyShareEntry values for groups not
644
      //    listed in the client's "supported_groups" extension.
645
      //
646
      // Note: We can assume that both `offers` and `supports` are unique lists
647
      //       as this is ensured in the parsing code of the extensions.
648
      auto found_in_supported_groups = [&supports, support_offset = -1](auto group) mutable {
1,672✔
649
         const auto i = std::find(supports.begin(), supports.end(), group);
1,672✔
650
         if(i == supports.end()) {
1,672✔
651
            return false;
652
         }
653

654
         const auto found_at = std::distance(supports.begin(), i);
1,672✔
655
         if(found_at <= support_offset) {
1,672✔
656
            return false;  // The order that groups appear in "key_share" and
657
                           // "supported_groups" must be the same
658
         }
659

660
         support_offset = static_cast<decltype(support_offset)>(found_at);
1,672✔
661
         return true;
1,672✔
662
      };
430✔
663

664
      for(const auto offered : offers) {
2,102✔
665
         // RFC 8446 4.2.8
666
         //    Servers MAY check for violations of these rules and abort the
667
         //    handshake with an "illegal_parameter" alert if one is violated.
668
         if(!found_in_supported_groups(offered)) {
1,672✔
669
            throw TLS_Exception(Alert::IllegalParameter,
×
670
                                "Offered key exchange groups do not align with claimed supported groups");
×
671
         }
672
      }
673
   }
860✔
674

675
   // TODO: Reject oid_filters extension if found (which is the only known extension that
676
   //       must not occur in the TLS 1.3 client hello.
677
   // RFC 8446 4.2.5
678
   //    [The oid_filters extension] MUST only be sent in the CertificateRequest message.
679
}
442✔
680

681
/*
682
* Create a new Client Hello message
683
*/
684
Client_Hello_13::Client_Hello_13(const Policy& policy,
950✔
685
                                 Callbacks& cb,
686
                                 RandomNumberGenerator& rng,
687
                                 std::string_view hostname,
688
                                 const std::vector<std::string>& next_protocols,
689
                                 std::optional<Session_with_Handle>& session) {
950✔
690
   // RFC 8446 4.1.2
691
   //    In TLS 1.3, the client indicates its version preferences in the
692
   //    "supported_versions" extension (Section 4.2.1) and the
693
   //    legacy_version field MUST be set to 0x0303, which is the version
694
   //    number for TLS 1.2.
695
   m_data->m_legacy_version = Protocol_Version::TLS_V12;
950✔
696
   m_data->m_random = make_hello_random(rng, cb, policy);
950✔
697
   m_data->m_suites = policy.ciphersuite_list(Protocol_Version::TLS_V13);
950✔
698

699
   if(policy.allow_tls12())  // Note: DTLS 1.3 is NYI, hence dtls_12 is not checked
950✔
700
   {
701
      const auto legacy_suites = policy.ciphersuite_list(Protocol_Version::TLS_V12);
930✔
702
      m_data->m_suites.insert(m_data->m_suites.end(), legacy_suites.cbegin(), legacy_suites.cend());
930✔
703
   }
930✔
704

705
   if(policy.tls_13_middlebox_compatibility_mode()) {
950✔
706
      // RFC 8446 4.1.2
707
      //    In compatibility mode (see Appendix D.4), this field MUST be non-empty,
708
      //    so a client not offering a pre-TLS 1.3 session MUST generate a new
709
      //    32-byte value.
710
      //
711
      // Note: we won't ever offer a TLS 1.2 session. In such a case we would
712
      //       have instantiated a TLS 1.2 client in the first place.
713
      m_data->m_session_id = Session_ID(make_hello_random(rng, cb, policy));
939✔
714
   }
715

716
   if(!hostname.empty()) {
950✔
717
      m_data->extensions().add(new Server_Name_Indicator(hostname));
1,860✔
718
   }
719

720
   m_data->extensions().add(new Supported_Groups(policy.key_exchange_groups()));
950✔
721

722
   m_data->extensions().add(new Key_Share(policy, cb, rng));
950✔
723

724
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13, policy));
950✔
725

726
   m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes()));
950✔
727
   if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) {
950✔
728
      // RFC 8446 4.2.3
729
      //    Implementations which have the same policy in both cases MAY omit
730
      //    the "signature_algorithms_cert" extension.
731
      m_data->extensions().add(new Signature_Algorithms_Cert(std::move(cert_signing_prefs.value())));
×
732
   }
×
733

734
   // TODO: Support for PSK-only mode without a key exchange.
735
   //       This should be configurable in TLS::Policy and should allow no PSK
736
   //       support at all (e.g. to disable support for session resumption).
737
   m_data->extensions().add(new PSK_Key_Exchange_Modes({PSK_Key_Exchange_Mode::PSK_DHE_KE}));
950✔
738

739
   if(policy.support_cert_status_message()) {
950✔
740
      m_data->extensions().add(new Certificate_Status_Request({}, {}));
97✔
741
   }
742

743
   // We currently support "record_size_limit" for TLS 1.3 exclusively. Hence,
744
   // when TLS 1.2 is advertised as a supported protocol, we must not offer this
745
   // extension.
746
   if(policy.record_size_limit().has_value() && !policy.allow_tls12()) {
950✔
747
      m_data->extensions().add(new Record_Size_Limit(policy.record_size_limit().value()));
12✔
748
   }
749

750
   if(!next_protocols.empty()) {
950✔
751
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocols));
11✔
752
   }
753

754
   if(policy.allow_tls12()) {
950✔
755
      m_data->extensions().add(new Renegotiation_Extension());
930✔
756
      m_data->extensions().add(new Session_Ticket_Extension());
930✔
757

758
      // EMS must always be used with TLS 1.2, regardless of the policy
759
      m_data->extensions().add(new Extended_Master_Secret);
930✔
760

761
      if(policy.negotiate_encrypt_then_mac()) {
930✔
762
         m_data->extensions().add(new Encrypt_then_MAC);
930✔
763
      }
764

765
      if(m_data->extensions().has<Supported_Groups>() &&
1,860✔
766
         !m_data->extensions().get<Supported_Groups>()->ec_groups().empty()) {
1,860✔
767
         m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
930✔
768
      }
769
   }
770

771
   if(session.has_value()) {
950✔
772
      m_data->extensions().add(new PSK(session.value(), cb));
82✔
773
   }
774

775
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
950✔
776

777
   if(m_data->extensions().has<PSK>()) {
950✔
778
      // RFC 8446 4.2.11
779
      //    The "pre_shared_key" extension MUST be the last extension in the
780
      //    ClientHello (this facilitates implementation [...]).
781
      if(m_data->extensions().all().back()->type() != Extension_Code::PresharedKey) {
82✔
782
         throw TLS_Exception(Alert::InternalError,
×
783
                             "Application modified extensions of Client Hello, PSK is not last anymore");
×
784
      }
785
      calculate_psk_binders({});
82✔
786
   }
787
}
950✔
788

789
std::variant<Client_Hello_13, Client_Hello_12> Client_Hello_13::parse(const std::vector<uint8_t>& buf) {
947✔
790
   auto data = std::make_unique<Client_Hello_Internal>(buf);
947✔
791
   const auto version = data->version();
921✔
792

793
   if(version.is_pre_tls_13()) {
921✔
794
      return Client_Hello_12(std::move(data));
958✔
795
   } else {
796
      return Client_Hello_13(std::move(data));
872✔
797
   }
798
}
921✔
799

800
void Client_Hello_13::retry(const Hello_Retry_Request& hrr,
34✔
801
                            const Transcript_Hash_State& transcript_hash_state,
802
                            Callbacks& cb,
803
                            RandomNumberGenerator& rng) {
804
   BOTAN_STATE_CHECK(m_data->extensions().has<Supported_Groups>());
34✔
805
   BOTAN_STATE_CHECK(m_data->extensions().has<Key_Share>());
34✔
806

807
   auto hrr_ks = hrr.extensions().get<Key_Share>();
34✔
808
   const auto& supported_groups = m_data->extensions().get<Supported_Groups>()->groups();
34✔
809

810
   if(hrr.extensions().has<Key_Share>()) {
34✔
811
      m_data->extensions().get<Key_Share>()->retry_offer(*hrr_ks, supported_groups, cb, rng);
33✔
812
   }
813

814
   // RFC 8446 4.2.2
815
   //    When sending the new ClientHello, the client MUST copy
816
   //    the contents of the extension received in the HelloRetryRequest into
817
   //    a "cookie" extension in the new ClientHello.
818
   //
819
   // RFC 8446 4.2.2
820
   //    Clients MUST NOT use cookies in their initial ClientHello in subsequent
821
   //    connections.
822
   if(hrr.extensions().has<Cookie>()) {
31✔
823
      BOTAN_STATE_CHECK(!m_data->extensions().has<Cookie>());
3✔
824
      m_data->extensions().add(new Cookie(hrr.extensions().get<Cookie>()->get_cookie()));
3✔
825
   }
826

827
   // Note: the consumer of the TLS implementation won't be able to distinguish
828
   //       invocations to this callback due to the first Client_Hello or the
829
   //       retried Client_Hello after receiving a Hello_Retry_Request. We assume
830
   //       that the user keeps and detects this state themselves.
831
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Client, type());
31✔
832

833
   auto psk = m_data->extensions().get<PSK>();
31✔
834
   if(psk) {
31✔
835
      // Cipher suite should always be a known suite as this is checked upstream
836
      const auto cipher = Ciphersuite::by_id(hrr.ciphersuite());
10✔
837
      BOTAN_ASSERT_NOMSG(cipher.has_value());
10✔
838

839
      // RFC 8446 4.1.4
840
      //    In [...] its updated ClientHello, the client SHOULD NOT offer
841
      //    any pre-shared keys associated with a hash other than that of the
842
      //    selected cipher suite.
843
      psk->filter(cipher.value());
10✔
844

845
      // RFC 8446 4.2.11.2
846
      //    If the server responds with a HelloRetryRequest and the client
847
      //    then sends ClientHello2, its binder will be computed over: [...].
848
      calculate_psk_binders(transcript_hash_state.clone());
10✔
849
   }
850
}
31✔
851

852
void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) {
30✔
853
   // RFC 8446 4.1.2
854
   //    The client will also send a ClientHello when the server has responded
855
   //    to its ClientHello with a HelloRetryRequest. In that case, the client
856
   //    MUST send the same ClientHello without modification, except as follows:
857

858
   if(m_data->session_id() != new_ch.m_data->session_id() || m_data->random() != new_ch.m_data->random() ||
30✔
859
      m_data->ciphersuites() != new_ch.m_data->ciphersuites() ||
60✔
860
      m_data->comp_methods() != new_ch.m_data->comp_methods()) {
30✔
861
      throw TLS_Exception(Alert::IllegalParameter, "Client Hello core values changed after Hello Retry Request");
×
862
   }
863

864
   const auto oldexts = extension_types();
30✔
865
   const auto newexts = new_ch.extension_types();
30✔
866

867
   // Check that extension omissions are justified
868
   for(const auto oldext : oldexts) {
421✔
869
      if(!newexts.contains(oldext)) {
784✔
870
         const auto ext = extensions().get(oldext);
1✔
871

872
         // We don't make any assumptions about unimplemented extensions.
873
         if(!ext->is_implemented()) {
1✔
874
            continue;
×
875
         }
876

877
         // RFC 8446 4.1.2
878
         //    Removing the "early_data" extension (Section 4.2.10) if one was
879
         //    present.  Early data is not permitted after a HelloRetryRequest.
880
         if(oldext == EarlyDataIndication::static_type()) {
1✔
881
            continue;
×
882
         }
883

884
         // RFC 8446 4.1.2
885
         //    Optionally adding, removing, or changing the length of the
886
         //    "padding" extension.
887
         //
888
         // TODO: implement the Padding extension
889
         // if(oldext == Padding::static_type())
890
         //    continue;
891

892
         throw TLS_Exception(Alert::IllegalParameter, "Extension removed in updated Client Hello");
1✔
893
      }
894
   }
895

896
   // Check that extension additions are justified
897
   for(const auto newext : newexts) {
413✔
898
      if(!oldexts.contains(newext)) {
768✔
899
         const auto ext = new_ch.extensions().get(newext);
2✔
900

901
         // We don't make any assumptions about unimplemented extensions.
902
         if(!ext->is_implemented()) {
2✔
903
            continue;
1✔
904
         }
905

906
         // RFC 8446 4.1.2
907
         //    Including a "cookie" extension if one was provided in the
908
         //    HelloRetryRequest.
909
         if(newext == Cookie::static_type()) {
1✔
910
            continue;
1✔
911
         }
912

913
         // RFC 8446 4.1.2
914
         //    Optionally adding, removing, or changing the length of the
915
         //    "padding" extension.
916
         //
917
         // TODO: implement the Padding extension
918
         // if(newext == Padding::static_type())
919
         //    continue;
920

921
         throw TLS_Exception(Alert::UnsupportedExtension, "Added an extension in updated Client Hello");
×
922
      }
923
   }
924

925
   // RFC 8446 4.1.2
926
   //    Removing the "early_data" extension (Section 4.2.10) if one was
927
   //    present.  Early data is not permitted after a HelloRetryRequest.
928
   if(new_ch.extensions().has<EarlyDataIndication>()) {
29✔
929
      throw TLS_Exception(Alert::IllegalParameter, "Updated Client Hello indicates early data");
×
930
   }
931

932
   // TODO: Contents of extensions are not checked for update compatibility, see:
933
   //
934
   // RFC 8446 4.1.2
935
   //    If a "key_share" extension was supplied in the HelloRetryRequest,
936
   //    replacing the list of shares with a list containing a single
937
   //    KeyShareEntry from the indicated group.
938
   //
939
   //    Updating the "pre_shared_key" extension if present by recomputing
940
   //    the "obfuscated_ticket_age" and binder values and (optionally)
941
   //    removing any PSKs which are incompatible with the server's
942
   //    indicated cipher suite.
943
   //
944
   //    Optionally adding, removing, or changing the length of the
945
   //    "padding" extension.
946
}
30✔
947

948
void Client_Hello_13::calculate_psk_binders(Transcript_Hash_State ths) {
92✔
949
   auto psk = m_data->extensions().get<PSK>();
92✔
950
   if(!psk || psk->empty()) {
92✔
951
      return;
1✔
952
   }
953

954
   // RFC 8446 4.2.11.2
955
   //    Each entry in the binders list is computed as an HMAC over a
956
   //    transcript hash (see Section 4.4.1) containing a partial ClientHello
957
   //    [...].
958
   //
959
   // Therefore we marshal the entire message prematurely to obtain the
960
   // (truncated) transcript hash, calculate the PSK binders with it, update
961
   // the Client Hello thus finalizing the message. Down the road, it will be
962
   // re-marshalled with the correct binders and sent over the wire.
963
   Handshake_Layer::prepare_message(*this, ths);
91✔
964
   psk->calculate_binders(ths);
91✔
965
}
966

967
std::optional<Protocol_Version> Client_Hello_13::highest_supported_version(const Policy& policy) const {
384✔
968
   // RFC 8446 4.2.1
969
   //    The "supported_versions" extension is used by the client to indicate
970
   //    which versions of TLS it supports and by the server to indicate which
971
   //    version it is using. The extension contains a list of supported
972
   //    versions in preference order, with the most preferred version first.
973
   const auto supvers = m_data->extensions().get<Supported_Versions>();
384✔
974
   BOTAN_ASSERT_NONNULL(supvers);
384✔
975

976
   std::optional<Protocol_Version> result;
384✔
977

978
   for(const auto& v : supvers->versions()) {
1,873✔
979
      // RFC 8446 4.2.1
980
      //    Servers MUST only select a version of TLS present in that extension
981
      //    and MUST ignore any unknown versions that are present in that
982
      //    extension.
983
      if(!v.known_version() || !policy.acceptable_protocol_version(v)) {
1,489✔
984
         continue;
830✔
985
      }
986

987
      result = (result.has_value()) ? std::optional(std::max(result.value(), v)) : std::optional(v);
934✔
988
   }
989

990
   return result;
384✔
991
}
992

993
#endif  // BOTAN_HAS_TLS_13
994

995
}  // 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

© 2025 Coveralls, Inc