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

randombit / botan / 16251882101

13 Jul 2025 05:54PM UTC coverage: 90.621% (+0.002%) from 90.619%
16251882101

push

github

web-flow
Merge pull request #4982 from randombit/jack/fix-clang-tidy-cert-err58-cpp

Enable and fix clang-tidy warning cert-err58-cpp

99611 of 109920 relevant lines covered (90.62%)

12303698.03 hits per line

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

94.46
/src/lib/tls/msg_server_hello.cpp
1
/*
2
* TLS Server Hello and Server Hello Done
3
* (C) 2004-2011,2015,2016,2019 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/mem_ops.h>
15
#include <botan/tls_callbacks.h>
16
#include <botan/tls_exceptn.h>
17
#include <botan/tls_extensions.h>
18
#include <botan/tls_session_manager.h>
19
#include <botan/internal/ct_utils.h>
20
#include <botan/internal/stl_util.h>
21
#include <botan/internal/tls_handshake_hash.h>
22
#include <botan/internal/tls_handshake_io.h>
23
#include <botan/internal/tls_reader.h>
24
#include <botan/internal/tls_session_key.h>
25
#include <array>
26

27
namespace Botan::TLS {
28

29
namespace {
30

31
const uint64_t DOWNGRADE_TLS11 = 0x444F574E47524400;
32
const uint64_t DOWNGRADE_TLS12 = 0x444F574E47524401;
33

34
// SHA-256("HelloRetryRequest")
35
const std::array<uint8_t, 32> HELLO_RETRY_REQUEST_MARKER = {
36
   0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
37
   0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
38

39
bool random_signals_hello_retry_request(const std::vector<uint8_t>& random) {
3,560✔
40
   return CT::is_equal(random.data(), HELLO_RETRY_REQUEST_MARKER.data(), HELLO_RETRY_REQUEST_MARKER.size()).as_bool();
3,560✔
41
}
42

43
std::vector<uint8_t> make_server_hello_random(RandomNumberGenerator& rng,
1,121✔
44
                                              Protocol_Version offered_version,
45
                                              Callbacks& cb,
46
                                              const Policy& policy) {
47
   BOTAN_UNUSED(offered_version);
1,121✔
48
   auto random = make_hello_random(rng, cb, policy);
1,121✔
49

50
   // RFC 8446 4.1.3
51
   //    TLS 1.3 has a downgrade protection mechanism embedded in the server's
52
   //    random value. TLS 1.3 servers which negotiate TLS 1.2 or below in
53
   //    response to a ClientHello MUST set the last 8 bytes of their Random
54
   //    value specially in their ServerHello.
55
   //
56
   //    If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
57
   //    their Random value to the bytes: [DOWNGRADE_TLS12]
58
   if(offered_version.is_pre_tls_13() && policy.allow_tls13()) {
1,121✔
59
      constexpr size_t downgrade_signal_length = sizeof(DOWNGRADE_TLS12);
482✔
60
      BOTAN_ASSERT_NOMSG(random.size() >= downgrade_signal_length);
482✔
61
      auto* lastbytes = random.data() + random.size() - downgrade_signal_length;
482✔
62
      store_be(DOWNGRADE_TLS12, lastbytes);
482✔
63
   }
64

65
   return random;
1,121✔
66
}
×
67

68
}  // namespace
69

70
/**
71
* Version-agnostic internal server hello data container that allows
72
* parsing Server_Hello messages without prior knowledge of the contained
73
* protocol version.
74
*/
75
class Server_Hello_Internal {
76
   public:
77
      /**
78
       * Deserialize a Server Hello message
79
       */
80
      explicit Server_Hello_Internal(const std::vector<uint8_t>& buf) {
3,566✔
81
         if(buf.size() < 38) {
3,566✔
82
            throw Decoding_Error("Server_Hello: Packet corrupted");
6✔
83
         }
84

85
         TLS_Data_Reader reader("ServerHello", buf);
3,560✔
86

87
         const uint8_t major_version = reader.get_byte();
3,560✔
88
         const uint8_t minor_version = reader.get_byte();
3,560✔
89

90
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,560✔
91

92
         // RFC 8446 4.1.3
93
         //    Upon receiving a message with type server_hello, implementations MUST
94
         //    first examine the Random value and, if it matches this value, process
95
         //    it as described in Section 4.1.4 [Hello Retry Request]).
96
         m_random = reader.get_fixed<uint8_t>(32);
3,560✔
97
         m_is_hello_retry_request = random_signals_hello_retry_request(m_random);
3,560✔
98

99
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,560✔
100
         m_ciphersuite = reader.get_uint16_t();
3,551✔
101
         m_comp_method = reader.get_byte();
3,549✔
102

103
         // Note that this code path might parse a TLS 1.2 (or older) server hello message that
104
         // is nevertheless marked as being a 'hello retry request' (potentially maliciously).
105
         // Extension parsing will however not be affected by the associated flag.
106
         // Only after parsing the extensions will the upstream code be able to decide
107
         // whether we're dealing with TLS 1.3 or older.
108
         m_extensions.deserialize(
3,548✔
109
            reader,
110
            Connection_Side::Server,
111
            m_is_hello_retry_request ? Handshake_Type::HelloRetryRequest : Handshake_Type::ServerHello);
3,548✔
112
      }
3,870✔
113

114
      Server_Hello_Internal(Protocol_Version lv,
1,397✔
115
                            Session_ID sid,
116
                            std::vector<uint8_t> r,
117
                            const uint16_t cs,
118
                            const uint8_t cm,
119
                            bool is_hrr = false) :
1,397✔
120
            m_legacy_version(lv),
1,397✔
121
            m_session_id(std::move(sid)),
1,397✔
122
            m_random(std::move(r)),
1,397✔
123
            m_is_hello_retry_request(is_hrr),
1,397✔
124
            m_ciphersuite(cs),
1,397✔
125
            m_comp_method(cm) {}
1,397✔
126

127
      Protocol_Version version() const {
4,446✔
128
         // RFC 8446 4.2.1
129
         //    A server which negotiates a version of TLS prior to TLS 1.3 MUST set
130
         //    ServerHello.version and MUST NOT send the "supported_versions"
131
         //    extension.  A server which negotiates TLS 1.3 MUST respond by sending
132
         //    a "supported_versions" extension containing the selected version
133
         //    value (0x0304).
134
         //
135
         // Note: Here we just take a message parsing decision, further validation of
136
         //       the extension's contents is done later.
137
         return (extensions().has<Supported_Versions>()) ? Protocol_Version::TLS_V13 : m_legacy_version;
4,446✔
138
      }
139

140
      Protocol_Version legacy_version() const { return m_legacy_version; }
2,132✔
141

142
      const Session_ID& session_id() const { return m_session_id; }
6,901✔
143

144
      const std::vector<uint8_t>& random() const { return m_random; }
2,007✔
145

146
      uint16_t ciphersuite() const { return m_ciphersuite; }
2,229✔
147

148
      uint8_t comp_method() const { return m_comp_method; }
1,394✔
149

150
      bool is_hello_retry_request() const { return m_is_hello_retry_request; }
1,076✔
151

152
      const Extensions& extensions() const { return m_extensions; }
4,446✔
153

154
      Extensions& extensions() { return m_extensions; }
39,484✔
155

156
   private:
157
      Protocol_Version m_legacy_version;
158
      Session_ID m_session_id;
159
      std::vector<uint8_t> m_random;
160
      bool m_is_hello_retry_request;
161
      uint16_t m_ciphersuite;
162
      uint8_t m_comp_method;
163

164
      Extensions m_extensions;
165
};
166

167
Server_Hello::Server_Hello(std::unique_ptr<Server_Hello_Internal> data) : m_data(std::move(data)) {}
4,808✔
168

169
Server_Hello::Server_Hello(Server_Hello&&) noexcept = default;
11,596✔
170
Server_Hello& Server_Hello::operator=(Server_Hello&&) noexcept = default;
1✔
171

172
Server_Hello::~Server_Hello() = default;
16,391✔
173

174
/*
175
* Serialize a Server Hello message
176
*/
177
std::vector<uint8_t> Server_Hello::serialize() const {
1,394✔
178
   std::vector<uint8_t> buf;
1,394✔
179
   buf.reserve(1024);  // working around GCC warning
1,394✔
180

181
   buf.push_back(m_data->legacy_version().major_version());
1,394✔
182
   buf.push_back(m_data->legacy_version().minor_version());
1,394✔
183
   buf += m_data->random();
1,394✔
184

185
   append_tls_length_value(buf, m_data->session_id().get(), 1);
1,394✔
186

187
   buf.push_back(get_byte<0>(m_data->ciphersuite()));
1,394✔
188
   buf.push_back(get_byte<1>(m_data->ciphersuite()));
1,394✔
189

190
   buf.push_back(m_data->comp_method());
1,394✔
191

192
   buf += m_data->extensions().serialize(Connection_Side::Server);
1,394✔
193

194
   return buf;
1,394✔
195
}
×
196

197
Handshake_Type Server_Hello::type() const {
7,373✔
198
   return Handshake_Type::ServerHello;
7,373✔
199
}
200

201
Protocol_Version Server_Hello::legacy_version() const {
13,949✔
202
   return m_data->legacy_version();
13,949✔
203
}
204

205
const std::vector<uint8_t>& Server_Hello::random() const {
3,820✔
206
   return m_data->random();
3,820✔
207
}
208

209
uint8_t Server_Hello::compression_method() const {
6,497✔
210
   return m_data->comp_method();
6,497✔
211
}
212

213
const Session_ID& Server_Hello::session_id() const {
6,901✔
214
   return m_data->session_id();
6,901✔
215
}
216

217
uint16_t Server_Hello::ciphersuite() const {
14,928✔
218
   return m_data->ciphersuite();
14,928✔
219
}
220

221
std::set<Extension_Code> Server_Hello::extension_types() const {
2,316✔
222
   return m_data->extensions().extension_types();
2,316✔
223
}
224

225
const Extensions& Server_Hello::extensions() const {
8,174✔
226
   return m_data->extensions();
8,174✔
227
}
228

229
// New session case
230
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
738✔
231
                                 Handshake_Hash& hash,
232
                                 const Policy& policy,
233
                                 Callbacks& cb,
234
                                 RandomNumberGenerator& rng,
235
                                 const std::vector<uint8_t>& reneg_info,
236
                                 const Client_Hello_12& client_hello,
237
                                 const Server_Hello_12::Settings& server_settings,
238
                                 std::string_view next_protocol) :
738✔
239
      Server_Hello(std::make_unique<Server_Hello_Internal>(
738✔
240
         server_settings.protocol_version(),
1,476✔
241
         server_settings.session_id(),
738✔
242
         make_server_hello_random(rng, server_settings.protocol_version(), cb, policy),
738✔
243
         server_settings.ciphersuite(),
738✔
244
         uint8_t(0))) {
1,476✔
245
   // NOLINTBEGIN(*-owning-memory)
246
   if(client_hello.supports_extended_master_secret()) {
738✔
247
      m_data->extensions().add(new Extended_Master_Secret);
733✔
248
   }
249

250
   // Sending the extension back does not commit us to sending a stapled response
251
   if(client_hello.supports_cert_status_message() && policy.support_cert_status_message()) {
738✔
252
      m_data->extensions().add(new Certificate_Status_Request);
204✔
253
   }
254

255
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
738✔
256
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
124✔
257
   }
258

259
   const auto c = Ciphersuite::by_id(m_data->ciphersuite());
738✔
260

261
   if(c && c->cbc_ciphersuite() && client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
738✔
262
      m_data->extensions().add(new Encrypt_then_MAC);
15✔
263
   }
264

265
   if(c && c->ecc_ciphersuite() && client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
2,112✔
266
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
635✔
267
   }
268

269
   if(client_hello.secure_renegotiation()) {
738✔
270
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
735✔
271
   }
272

273
   if(client_hello.supports_session_ticket() && server_settings.offer_session_ticket()) {
738✔
274
      m_data->extensions().add(new Session_Ticket_Extension());
543✔
275
   }
276

277
   if(m_data->legacy_version().is_datagram_protocol()) {
738✔
278
      const std::vector<uint16_t> server_srtp = policy.srtp_profiles();
293✔
279
      const std::vector<uint16_t> client_srtp = client_hello.srtp_profiles();
293✔
280

281
      if(!server_srtp.empty() && !client_srtp.empty()) {
293✔
282
         uint16_t shared = 0;
283
         // always using server preferences for now
284
         for(auto s_srtp : server_srtp) {
6✔
285
            for(auto c_srtp : client_srtp) {
16✔
286
               if(shared == 0 && s_srtp == c_srtp) {
12✔
287
                  shared = s_srtp;
1✔
288
               }
289
            }
290
         }
291

292
         if(shared != 0) {
2✔
293
            m_data->extensions().add(new SRTP_Protection_Profiles(shared));
1✔
294
         }
295
      }
296
   }
295✔
297
   // NOLINTEND(*-owning-memory)
298

299
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
738✔
300

301
   hash.update(io.send(*this));
1,476✔
302
}
738✔
303

304
// Resuming
305
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
227✔
306
                                 Handshake_Hash& hash,
307
                                 const Policy& policy,
308
                                 Callbacks& cb,
309
                                 RandomNumberGenerator& rng,
310
                                 const std::vector<uint8_t>& reneg_info,
311
                                 const Client_Hello_12& client_hello,
312
                                 const Session& resumed_session,
313
                                 bool offer_session_ticket,
314
                                 std::string_view next_protocol) :
227✔
315
      Server_Hello(std::make_unique<Server_Hello_Internal>(resumed_session.version(),
454✔
316
                                                           client_hello.session_id(),
227✔
317
                                                           make_hello_random(rng, cb, policy),
227✔
318
                                                           resumed_session.ciphersuite_code(),
454✔
319
                                                           uint8_t(0))) {
454✔
320
   // NOLINTBEGIN(*-owning-memory)
321
   if(client_hello.supports_extended_master_secret()) {
227✔
322
      m_data->extensions().add(new Extended_Master_Secret);
226✔
323
   }
324

325
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
227✔
326
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
12✔
327
   }
328

329
   if(client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
227✔
330
      Ciphersuite c = resumed_session.ciphersuite();
1✔
331
      if(c.cbc_ciphersuite()) {
1✔
332
         m_data->extensions().add(new Encrypt_then_MAC);
1✔
333
      }
334
   }
335

336
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
227✔
337
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
643✔
338
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
208✔
339
   }
340

341
   if(client_hello.secure_renegotiation()) {
227✔
342
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
227✔
343
   }
344

345
   if(client_hello.supports_session_ticket() && offer_session_ticket) {
227✔
346
      m_data->extensions().add(new Session_Ticket_Extension());
1✔
347
   }
348
   // NOLINTEND(*-owning-memory)
349

350
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
227✔
351

352
   hash.update(io.send(*this));
454✔
353
}
227✔
354

355
Server_Hello_12::Server_Hello_12(const std::vector<uint8_t>& buf) :
2,519✔
356
      Server_Hello_12(std::make_unique<Server_Hello_Internal>(buf)) {}
2,519✔
357

358
Server_Hello_12::Server_Hello_12(std::unique_ptr<Server_Hello_Internal> data) : Server_Hello(std::move(data)) {
2,873✔
359
   if(!m_data->version().is_pre_tls_13()) {
5,746✔
360
      throw TLS_Exception(Alert::ProtocolVersion, "Expected server hello of (D)TLS 1.2 or lower");
×
361
   }
362
}
2,873✔
363

364
Protocol_Version Server_Hello_12::selected_version() const {
490✔
365
   return legacy_version();
490✔
366
}
367

368
bool Server_Hello_12::secure_renegotiation() const {
3,200✔
369
   return m_data->extensions().has<Renegotiation_Extension>();
3,200✔
370
}
371

372
std::vector<uint8_t> Server_Hello_12::renegotiation_info() const {
3,107✔
373
   if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
3,107✔
374
      return reneg->renegotiation_info();
3,107✔
375
   }
376
   return std::vector<uint8_t>();
×
377
}
378

379
bool Server_Hello_12::supports_extended_master_secret() const {
3,939✔
380
   return m_data->extensions().has<Extended_Master_Secret>();
3,939✔
381
}
382

383
bool Server_Hello_12::supports_encrypt_then_mac() const {
6,871✔
384
   return m_data->extensions().has<Encrypt_then_MAC>();
6,871✔
385
}
386

387
bool Server_Hello_12::supports_certificate_status_message() const {
1,929✔
388
   return m_data->extensions().has<Certificate_Status_Request>();
1,929✔
389
}
390

391
bool Server_Hello_12::supports_session_ticket() const {
2,617✔
392
   return m_data->extensions().has<Session_Ticket_Extension>();
2,617✔
393
}
394

395
uint16_t Server_Hello_12::srtp_profile() const {
3,713✔
396
   if(auto* srtp = m_data->extensions().get<SRTP_Protection_Profiles>()) {
3,713✔
397
      auto prof = srtp->profiles();
4✔
398
      if(prof.size() != 1 || prof[0] == 0) {
4✔
399
         throw Decoding_Error("Server sent malformed DTLS-SRTP extension");
×
400
      }
401
      return prof[0];
4✔
402
   }
4✔
403

404
   return 0;
405
}
406

407
std::string Server_Hello_12::next_protocol() const {
2,160✔
408
   if(auto* alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
2,160✔
409
      return alpn->single_protocol();
137✔
410
   }
411
   return "";
2,023✔
412
}
413

414
bool Server_Hello_12::prefers_compressed_ec_points() const {
13✔
415
   if(auto* ecc_formats = m_data->extensions().get<Supported_Point_Formats>()) {
13✔
416
      return ecc_formats->prefers_compressed();
10✔
417
   }
418
   return false;
419
}
420

421
std::optional<Protocol_Version> Server_Hello_12::random_signals_downgrade() const {
613✔
422
   const uint64_t last8 = load_be<uint64_t>(m_data->random().data(), 3);
613✔
423
   if(last8 == DOWNGRADE_TLS11) {
613✔
424
      return Protocol_Version::TLS_V11;
×
425
   }
426
   if(last8 == DOWNGRADE_TLS12) {
613✔
427
      return Protocol_Version::TLS_V12;
1✔
428
   }
429

430
   return std::nullopt;
612✔
431
}
432

433
/*
434
* Create a new Server Hello Done message
435
*/
436
Server_Hello_Done::Server_Hello_Done(Handshake_IO& io, Handshake_Hash& hash) {
713✔
437
   hash.update(io.send(*this));
1,426✔
438
}
713✔
439

440
/*
441
* Deserialize a Server Hello Done message
442
*/
443
Server_Hello_Done::Server_Hello_Done(const std::vector<uint8_t>& buf) {
859✔
444
   if(!buf.empty()) {
859✔
445
      throw Decoding_Error("Server_Hello_Done: Must be empty, and is not");
2✔
446
   }
447
}
857✔
448

449
/*
450
* Serialize a Server Hello Done message
451
*/
452
std::vector<uint8_t> Server_Hello_Done::serialize() const {
713✔
453
   return std::vector<uint8_t>();
713✔
454
}
455

456
#if defined(BOTAN_HAS_TLS_13)
457

458
const Server_Hello_13::Server_Hello_Tag Server_Hello_13::as_server_hello;
459
const Server_Hello_13::Hello_Retry_Request_Tag Server_Hello_13::as_hello_retry_request;
460
const Server_Hello_13::Hello_Retry_Request_Creation_Tag Server_Hello_13::as_new_hello_retry_request;
461

462
std::variant<Hello_Retry_Request, Server_Hello_13> Server_Hello_13::create(const Client_Hello_13& ch,
432✔
463
                                                                           bool hello_retry_request_allowed,
464
                                                                           Session_Manager& session_mgr,
465
                                                                           Credentials_Manager& credentials_mgr,
466
                                                                           RandomNumberGenerator& rng,
467
                                                                           const Policy& policy,
468
                                                                           Callbacks& cb) {
469
   const auto& exts = ch.extensions();
432✔
470

471
   // RFC 8446 4.2.9
472
   //    [With PSK with (EC)DHE key establishment], the client and server MUST
473
   //    supply "key_share" values [...].
474
   //
475
   // Note: We currently do not support PSK without (EC)DHE, hence, we can
476
   //       assume that those extensions are available.
477
   BOTAN_ASSERT_NOMSG(exts.has<Supported_Groups>() && exts.has<Key_Share>());
864✔
478
   const auto& supported_by_client = exts.get<Supported_Groups>()->groups();
432✔
479
   const auto& offered_by_client = exts.get<Key_Share>()->offered_groups();
432✔
480
   const auto selected_group = policy.choose_key_exchange_group(supported_by_client, offered_by_client);
432✔
481

482
   // RFC 8446 4.1.1
483
   //    If there is no overlap between the received "supported_groups" and the
484
   //    groups supported by the server, then the server MUST abort the
485
   //    handshake with a "handshake_failure" or an "insufficient_security" alert.
486
   if(selected_group == Named_Group::NONE) {
432✔
487
      throw TLS_Exception(Alert::HandshakeFailure, "Client did not offer any acceptable group");
×
488
   }
489

490
   // RFC 8446 4.2.8:
491
   //    Servers MUST NOT send a KeyShareEntry for any group not indicated in the
492
   //    client's "supported_groups" extension [...]
493
   if(!value_exists(supported_by_client, selected_group)) {
432✔
494
      throw TLS_Exception(Alert::InternalError, "Application selected a group that is not supported by the client");
×
495
   }
496

497
   // RFC 8446 4.1.4
498
   //    The server will send this message in response to a ClientHello
499
   //    message if it is able to find an acceptable set of parameters but the
500
   //    ClientHello does not contain sufficient information to proceed with
501
   //    the handshake.
502
   //
503
   // In this case, the Client Hello did not contain a key share offer for
504
   // the group selected by the application.
505
   if(!value_exists(offered_by_client, selected_group)) {
432✔
506
      // RFC 8446 4.1.4
507
      //    If a client receives a second HelloRetryRequest in the same
508
      //    connection (i.e., where the ClientHello was itself in response to a
509
      //    HelloRetryRequest), it MUST abort the handshake with an
510
      //    "unexpected_message" alert.
511
      BOTAN_STATE_CHECK(hello_retry_request_allowed);
49✔
512
      return Hello_Retry_Request(ch, selected_group, policy, cb);
98✔
513
   } else {
514
      return Server_Hello_13(ch, selected_group, session_mgr, credentials_mgr, rng, cb, policy);
750✔
515
   }
516
}
416✔
517

518
std::variant<Hello_Retry_Request, Server_Hello_13, Server_Hello_12> Server_Hello_13::parse(
1,047✔
519
   const std::vector<uint8_t>& buf) {
520
   auto data = std::make_unique<Server_Hello_Internal>(buf);
1,047✔
521
   const auto version = data->version();
1,035✔
522

523
   // server hello that appears to be pre-TLS 1.3, takes precedence over...
524
   if(version.is_pre_tls_13()) {
1,035✔
525
      return Server_Hello_12(std::move(data));
994✔
526
   }
527

528
   // ... the TLS 1.3 "special case" aka. Hello_Retry_Request
529
   if(version == Protocol_Version::TLS_V13) {
538✔
530
      if(data->is_hello_retry_request()) {
538✔
531
         return Hello_Retry_Request(std::move(data));
135✔
532
      }
533

534
      return Server_Hello_13(std::move(data));
930✔
535
   }
536

537
   throw TLS_Exception(Alert::ProtocolVersion, "unexpected server hello version: " + version.to_string());
×
538
}
1,035✔
539

540
/**
541
 * Validation that applies to both Server Hello and Hello Retry Request
542
 */
543
void Server_Hello_13::basic_validation() const {
538✔
544
   BOTAN_ASSERT_NOMSG(m_data->version() == Protocol_Version::TLS_V13);
1,076✔
545

546
   // Note: checks that cannot be performed without contextual information
547
   //       are done in the specific TLS client implementation.
548
   // Note: The Supported_Version extension makes sure internally that
549
   //       exactly one entry is provided.
550

551
   // Note: Hello Retry Request basic validation is equivalent with the
552
   //       basic validations required for Server Hello
553
   //
554
   // RFC 8446 4.1.4
555
   //    Upon receipt of a HelloRetryRequest, the client MUST check the
556
   //    legacy_version, [...], and legacy_compression_method as specified in
557
   //    Section 4.1.3 and then process the extensions, starting with determining
558
   //    the version using "supported_versions".
559

560
   // RFC 8446 4.1.3
561
   //    In TLS 1.3, [...] the legacy_version field MUST be set to 0x0303
562
   if(legacy_version() != Protocol_Version::TLS_V12) {
538✔
563
      throw TLS_Exception(Alert::ProtocolVersion,
2✔
564
                          "legacy_version '" + legacy_version().to_string() + "' is not allowed");
6✔
565
   }
566

567
   // RFC 8446 4.1.3
568
   //    legacy_compression_method:  A single byte which MUST have the value 0.
569
   if(compression_method() != 0x00) {
536✔
570
      throw TLS_Exception(Alert::DecodeError, "compression is not supported in TLS 1.3");
2✔
571
   }
572

573
   // RFC 8446 4.1.3
574
   //    All TLS 1.3 ServerHello messages MUST contain the "supported_versions" extension.
575
   if(!extensions().has<Supported_Versions>()) {
534✔
576
      throw TLS_Exception(Alert::MissingExtension, "server hello did not contain 'supported version' extension");
×
577
   }
578

579
   // RFC 8446 4.2.1
580
   //    A server which negotiates TLS 1.3 MUST respond by sending
581
   //    a "supported_versions" extension containing the selected version
582
   //    value (0x0304).
583
   if(selected_version() != Protocol_Version::TLS_V13) {
534✔
584
      throw TLS_Exception(Alert::IllegalParameter, "TLS 1.3 Server Hello selected a different version");
1✔
585
   }
586
}
533✔
587

588
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Server_Hello_13::Server_Hello_Tag) :
469✔
589
      Server_Hello(std::move(data)) {
469✔
590
   BOTAN_ASSERT_NOMSG(!m_data->is_hello_retry_request());
469✔
591
   basic_validation();
469✔
592

593
   const auto& exts = extensions();
465✔
594

595
   // RFC 8446 4.1.3
596
   //    The ServerHello MUST only include extensions which are required to
597
   //    establish the cryptographic context and negotiate the protocol version.
598
   //    [...]
599
   //    Other extensions (see Section 4.2) are sent separately in the
600
   //    EncryptedExtensions message.
601
   //
602
   // Note that further validation dependent on the client hello is done in the
603
   // TLS client implementation.
604
   const std::set<Extension_Code> allowed = {
465✔
605
      Extension_Code::KeyShare,
606
      Extension_Code::SupportedVersions,
607
      Extension_Code::PresharedKey,
608
   };
465✔
609

610
   // As the ServerHello shall only contain essential extensions, we don't give
611
   // any slack for extensions not implemented by Botan here.
612
   if(exts.contains_other_than(allowed)) {
465✔
613
      throw TLS_Exception(Alert::UnsupportedExtension, "Server Hello contained an extension that is not allowed");
2✔
614
   }
615

616
   // RFC 8446 4.1.3
617
   //    Current ServerHello messages additionally contain
618
   //    either the "pre_shared_key" extension or the "key_share"
619
   //    extension, or both [...].
620
   if(!exts.has<Key_Share>() && !exts.has<PSK_Key_Exchange_Modes>()) {
465✔
621
      throw TLS_Exception(Alert::MissingExtension, "server hello must contain key exchange information");
2✔
622
   }
623
}
469✔
624

625
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
69✔
626
                                 Server_Hello_13::Hello_Retry_Request_Tag) :
69✔
627
      Server_Hello(std::move(data)) {
69✔
628
   BOTAN_ASSERT_NOMSG(m_data->is_hello_retry_request());
69✔
629
   basic_validation();
69✔
630

631
   const auto& exts = extensions();
68✔
632

633
   // RFC 8446 4.1.4
634
   //     The HelloRetryRequest extensions defined in this specification are:
635
   //     -  supported_versions (see Section 4.2.1)
636
   //     -  cookie (see Section 4.2.2)
637
   //     -  key_share (see Section 4.2.8)
638
   const std::set<Extension_Code> allowed = {
68✔
639
      Extension_Code::Cookie,
640
      Extension_Code::SupportedVersions,
641
      Extension_Code::KeyShare,
642
   };
68✔
643

644
   // As the Hello Retry Request shall only contain essential extensions, we
645
   // don't give any slack for extensions not implemented by Botan here.
646
   if(exts.contains_other_than(allowed)) {
68✔
647
      throw TLS_Exception(Alert::UnsupportedExtension,
1✔
648
                          "Hello Retry Request contained an extension that is not allowed");
1✔
649
   }
650

651
   // RFC 8446 4.1.4
652
   //    Clients MUST abort the handshake with an "illegal_parameter" alert if
653
   //    the HelloRetryRequest would not result in any change in the ClientHello.
654
   if(!exts.has<Key_Share>() && !exts.has<Cookie>()) {
69✔
655
      throw TLS_Exception(Alert::IllegalParameter, "Hello Retry Request does not request any changes to Client Hello");
1✔
656
   }
657
}
69✔
658

659
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Hello_Retry_Request_Creation_Tag) :
49✔
660
      Server_Hello(std::move(data)) {}
49✔
661

662
namespace {
663

664
uint16_t choose_ciphersuite(const Client_Hello_13& ch, const Policy& policy) {
432✔
665
   auto pref_list = ch.ciphersuites();
432✔
666
   // TODO: DTLS might need to make this version dynamic
667
   auto other_list = policy.ciphersuite_list(Protocol_Version::TLS_V13);
432✔
668

669
   if(policy.server_uses_own_ciphersuite_preferences()) {
432✔
670
      std::swap(pref_list, other_list);
432✔
671
   }
672

673
   for(auto suite_id : pref_list) {
1,263✔
674
      // TODO: take potentially available PSKs into account to select a
675
      //       compatible ciphersuite.
676
      //
677
      // Assuming the client sent one or more PSKs, we would first need to find
678
      // the hash functions they are associated to. For session tickets, that
679
      // would mean decrypting the ticket and comparing the cipher suite used in
680
      // those tickets. For (currently not yet supported) pre-assigned PSKs, the
681
      // hash function needs to be specified along with them.
682
      //
683
      // Then we could refine the ciphersuite selection using the required hash
684
      // function for the PSK(s) we are wishing to use down the road.
685
      //
686
      // For now, we just negotiate the cipher suite blindly and hope for the
687
      // best. As long as PSKs are used for session resumption only, this has a
688
      // high chance of success. Previous handshakes with this client have very
689
      // likely selected the same ciphersuite anyway.
690
      //
691
      // See also RFC 8446 4.2.11
692
      //    When session resumption is the primary use case of PSKs, the most
693
      //    straightforward way to implement the PSK/cipher suite matching
694
      //    requirements is to negotiate the cipher suite first [...].
695
      if(value_exists(other_list, suite_id)) {
2,526✔
696
         return suite_id;
432✔
697
      }
698
   }
699

700
   // RFC 8446 4.1.1
701
   //     If the server is unable to negotiate a supported set of parameters
702
   //     [...], it MUST abort the handshake with either a "handshake_failure"
703
   //     or "insufficient_security" fatal alert [...].
704
   throw TLS_Exception(Alert::HandshakeFailure, "Can't agree on a ciphersuite with client");
×
705
}
864✔
706
}  // namespace
707

708
Server_Hello_13::Server_Hello_13(const Client_Hello_13& ch,
383✔
709
                                 std::optional<Named_Group> key_exchange_group,
710
                                 Session_Manager& session_mgr,
711
                                 Credentials_Manager& credentials_mgr,
712
                                 RandomNumberGenerator& rng,
713
                                 Callbacks& cb,
714
                                 const Policy& policy) :
383✔
715
      Server_Hello(std::make_unique<Server_Hello_Internal>(
766✔
716
         Protocol_Version::TLS_V12,
717
         ch.session_id(),
383✔
718
         make_server_hello_random(rng, Protocol_Version::TLS_V13, cb, policy),
383✔
719
         choose_ciphersuite(ch, policy),
383✔
720
         uint8_t(0) /* compression method */
766✔
721
         )) {
766✔
722
   // RFC 8446 4.2.1
723
   //    A server which negotiates TLS 1.3 MUST respond by sending a
724
   //    "supported_versions" extension containing the selected version
725
   //    value (0x0304). It MUST set the ServerHello.legacy_version field to
726
   //     0x0303 (TLS 1.2).
727
   //
728
   // Note that the legacy version (TLS 1.2) is set in this constructor's
729
   // initializer list, accordingly.
730
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13));  // NOLINT(*-owning-memory)
383✔
731

732
   if(key_exchange_group.has_value()) {
383✔
733
      BOTAN_ASSERT_NOMSG(ch.extensions().has<Key_Share>());
383✔
734
      m_data->extensions().add(Key_Share::create_as_encapsulation(
1,133✔
735
         key_exchange_group.value(), *ch.extensions().get<Key_Share>(), policy, cb, rng));
383✔
736
   }
737

738
   const auto& ch_exts = ch.extensions();
367✔
739

740
   if(ch_exts.has<PSK>()) {
367✔
741
      const auto cs = Ciphersuite::by_id(m_data->ciphersuite());
97✔
742
      BOTAN_ASSERT_NOMSG(cs);
97✔
743

744
      // RFC 8446 4.2.9
745
      //    A client MUST provide a "psk_key_exchange_modes" extension if it
746
      //    offers a "pre_shared_key" extension.
747
      //
748
      // Note: Client_Hello_13 constructor already performed a graceful check.
749
      auto* const psk_modes = ch_exts.get<PSK_Key_Exchange_Modes>();
97✔
750
      BOTAN_ASSERT_NONNULL(psk_modes);
97✔
751

752
      // TODO: also support PSK_Key_Exchange_Mode::PSK_KE
753
      //       (PSK-based handshake without an additional ephemeral key exchange)
754
      if(value_exists(psk_modes->modes(), PSK_Key_Exchange_Mode::PSK_DHE_KE)) {
97✔
755
         if(auto server_psk = ch_exts.get<PSK>()->select_offered_psk(
96✔
756
               ch.sni_hostname(), cs.value(), session_mgr, credentials_mgr, cb, policy)) {
192✔
757
            // RFC 8446 4.2.11
758
            //    In order to accept PSK key establishment, the server sends a
759
            //    "pre_shared_key" extension indicating the selected identity.
760
            m_data->extensions().add(std::move(server_psk));
188✔
761
         }
96✔
762
      }
763
   }
764

765
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
367✔
766
}
383✔
767

768
std::optional<Protocol_Version> Server_Hello_13::random_signals_downgrade() const {
×
769
   const uint64_t last8 = load_be<uint64_t>(m_data->random().data(), 3);
×
770
   if(last8 == DOWNGRADE_TLS11) {
×
771
      return Protocol_Version::TLS_V11;
×
772
   }
773
   if(last8 == DOWNGRADE_TLS12) {
×
774
      return Protocol_Version::TLS_V12;
×
775
   }
776

777
   return std::nullopt;
×
778
}
779

780
Protocol_Version Server_Hello_13::selected_version() const {
2,604✔
781
   auto* const versions_ext = m_data->extensions().get<Supported_Versions>();
2,604✔
782
   BOTAN_ASSERT_NOMSG(versions_ext);
2,604✔
783
   const auto& versions = versions_ext->versions();
2,604✔
784
   BOTAN_ASSERT_NOMSG(versions.size() == 1);
2,604✔
785
   return versions.front();
2,604✔
786
}
787

788
Hello_Retry_Request::Hello_Retry_Request(std::unique_ptr<Server_Hello_Internal> data) :
69✔
789
      Server_Hello_13(std::move(data), Server_Hello_13::as_hello_retry_request) {}
69✔
790

791
Hello_Retry_Request::Hello_Retry_Request(const Client_Hello_13& ch,
49✔
792
                                         Named_Group selected_group,
793
                                         const Policy& policy,
794
                                         Callbacks& cb) :
49✔
795
      Server_Hello_13(std::make_unique<Server_Hello_Internal>(
98✔
796
                         Protocol_Version::TLS_V12 /* legacy_version */,
797
                         ch.session_id(),
49✔
798
                         std::vector<uint8_t>(HELLO_RETRY_REQUEST_MARKER.begin(), HELLO_RETRY_REQUEST_MARKER.end()),
49✔
799
                         choose_ciphersuite(ch, policy),
49✔
800
                         uint8_t(0) /* compression method */,
98✔
801
                         true /* is Hello Retry Request */
98✔
802
                         ),
803
                      as_new_hello_retry_request) {
98✔
804
   // RFC 8446 4.1.4
805
   //     As with the ServerHello, a HelloRetryRequest MUST NOT contain any
806
   //     extensions that were not first offered by the client in its
807
   //     ClientHello, with the exception of optionally the "cookie" [...]
808
   //     extension.
809
   BOTAN_STATE_CHECK(ch.extensions().has<Supported_Groups>());
49✔
810
   BOTAN_STATE_CHECK(ch.extensions().has<Key_Share>());
49✔
811

812
   BOTAN_STATE_CHECK(!value_exists(ch.extensions().get<Key_Share>()->offered_groups(), selected_group));
114✔
813

814
   // RFC 8446 4.1.4
815
   //    The server's extensions MUST contain "supported_versions".
816
   //
817
   // RFC 8446 4.2.1
818
   //    A server which negotiates TLS 1.3 MUST respond by sending a
819
   //    "supported_versions" extension containing the selected version
820
   //    value (0x0304). It MUST set the ServerHello.legacy_version field to
821
   //    0x0303 (TLS 1.2).
822
   //
823
   // Note that the legacy version (TLS 1.2) is set in this constructor's
824
   // initializer list, accordingly.
825
   // NOLINTBEGIN(*-owning-memory)
826
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13));
49✔
827

828
   m_data->extensions().add(new Key_Share(selected_group));
49✔
829
   // NOLINTEND(*-owning-memory)
830

831
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
49✔
832
}
49✔
833

834
#endif  // BOTAN_HAS_TLS_13
835

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