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

randombit / botan / 21746428601

06 Feb 2026 07:47AM UTC coverage: 90.074% (+0.002%) from 90.072%
21746428601

push

github

web-flow
Merge pull request #5288 from Rohde-Schwarz/feature/disentangle_tls12_from_tls13

Refactor: Organize most TLS handshake messages into TLS 1.2 and TLS 1.3 modules

102235 of 113501 relevant lines covered (90.07%)

11561717.77 hits per line

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

94.5
/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_12.h>
13

14
#include <botan/tls_callbacks.h>
15
#include <botan/tls_exceptn.h>
16
#include <botan/tls_extensions.h>
17
#include <botan/tls_policy.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

25
#ifdef BOTAN_HAS_TLS_13
26
   #include <botan/tls_messages_13.h>
27
#endif
28

29
#include <array>
30

31
namespace Botan::TLS {
32

33
namespace {
34

35
const uint64_t DOWNGRADE_TLS11 = 0x444F574E47524400;
36
const uint64_t DOWNGRADE_TLS12 = 0x444F574E47524401;
37

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

43
bool random_signals_hello_retry_request(const std::vector<uint8_t>& random) {
3,563✔
44
   return CT::is_equal(random.data(), HELLO_RETRY_REQUEST_MARKER.data(), HELLO_RETRY_REQUEST_MARKER.size()).as_bool();
3,563✔
45
}
46

47
std::vector<uint8_t> make_server_hello_random(RandomNumberGenerator& rng,
1,125✔
48
                                              Protocol_Version offered_version,
49
                                              Callbacks& cb,
50
                                              const Policy& policy) {
51
   BOTAN_UNUSED(offered_version);
1,125✔
52
   auto random = make_hello_random(rng, cb, policy);
1,125✔
53

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

69
   return random;
1,125✔
70
}
×
71

72
}  // namespace
73

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

89
         TLS_Data_Reader reader("ServerHello", buf);
3,563✔
90

91
         const uint8_t major_version = reader.get_byte();
3,563✔
92
         const uint8_t minor_version = reader.get_byte();
3,563✔
93

94
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,563✔
95

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

103
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,563✔
104
         m_ciphersuite = reader.get_uint16_t();
3,554✔
105
         m_comp_method = reader.get_byte();
3,552✔
106

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

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

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

144
      Protocol_Version legacy_version() const { return m_legacy_version; }
2,139✔
145

146
      const Session_ID& session_id() const { return m_session_id; }
6,920✔
147

148
      const std::vector<uint8_t>& random() const { return m_random; }
2,010✔
149

150
      uint16_t ciphersuite() const { return m_ciphersuite; }
2,236✔
151

152
      uint8_t comp_method() const { return m_comp_method; }
1,397✔
153

154
      bool is_hello_retry_request() const { return m_is_hello_retry_request; }
1,076✔
155

156
      const Extensions& extensions() const { return m_extensions; }
4,449✔
157

158
      Extensions& extensions() { return m_extensions; }
39,599✔
159

160
   private:
161
      Protocol_Version m_legacy_version;
162
      Session_ID m_session_id;
163
      std::vector<uint8_t> m_random;
164
      bool m_is_hello_retry_request;
165
      uint16_t m_ciphersuite;
166
      uint8_t m_comp_method;
167

168
      Extensions m_extensions;
169
};
170

171
Server_Hello::Server_Hello(std::unique_ptr<Server_Hello_Internal> data) : m_data(std::move(data)) {}
4,814✔
172

173
Server_Hello::Server_Hello(Server_Hello&&) noexcept = default;
11,596✔
174
Server_Hello& Server_Hello::operator=(Server_Hello&&) noexcept = default;
1✔
175

176
Server_Hello::~Server_Hello() = default;
16,397✔
177

178
/*
179
* Serialize a Server Hello message
180
*/
181
std::vector<uint8_t> Server_Hello::serialize() const {
1,397✔
182
   std::vector<uint8_t> buf;
1,397✔
183
   buf.reserve(1024);  // working around GCC warning
1,397✔
184

185
   buf.push_back(m_data->legacy_version().major_version());
1,397✔
186
   buf.push_back(m_data->legacy_version().minor_version());
1,397✔
187
   buf += m_data->random();
1,397✔
188

189
   append_tls_length_value(buf, m_data->session_id().get(), 1);
1,397✔
190

191
   buf.push_back(get_byte<0>(m_data->ciphersuite()));
1,397✔
192
   buf.push_back(get_byte<1>(m_data->ciphersuite()));
1,397✔
193

194
   buf.push_back(m_data->comp_method());
1,397✔
195

196
   buf += m_data->extensions().serialize(Connection_Side::Server);
1,397✔
197

198
   return buf;
1,397✔
199
}
×
200

201
Handshake_Type Server_Hello::type() const {
7,382✔
202
   return Handshake_Type::ServerHello;
7,382✔
203
}
204

205
Protocol_Version Server_Hello::legacy_version() const {
13,971✔
206
   return m_data->legacy_version();
13,971✔
207
}
208

209
const std::vector<uint8_t>& Server_Hello::random() const {
3,838✔
210
   return m_data->random();
3,838✔
211
}
212

213
uint8_t Server_Hello::compression_method() const {
6,512✔
214
   return m_data->comp_method();
6,512✔
215
}
216

217
const Session_ID& Server_Hello::session_id() const {
6,920✔
218
   return m_data->session_id();
6,920✔
219
}
220

221
uint16_t Server_Hello::ciphersuite() const {
14,950✔
222
   return m_data->ciphersuite();
14,950✔
223
}
224

225
std::set<Extension_Code> Server_Hello::extension_types() const {
2,319✔
226
   return m_data->extensions().extension_types();
2,319✔
227
}
228

229
const Extensions& Server_Hello::extensions() const {
8,177✔
230
   return m_data->extensions();
8,177✔
231
}
232

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

254
   // Sending the extension back does not commit us to sending a stapled response
255
   if(client_hello.supports_cert_status_message() && policy.support_cert_status_message()) {
742✔
256
      m_data->extensions().add(new Certificate_Status_Request);
208✔
257
   }
258

259
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
742✔
260
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
128✔
261
   }
262

263
   const auto c = Ciphersuite::by_id(m_data->ciphersuite());
742✔
264

265
   if(c && c->cbc_ciphersuite() && client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
742✔
266
      m_data->extensions().add(new Encrypt_then_MAC);
15✔
267
   }
268

269
   if(c && c->ecc_ciphersuite() && client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
2,124✔
270
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
639✔
271
   }
272

273
   if(client_hello.secure_renegotiation()) {
742✔
274
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
739✔
275
   }
276

277
   if(client_hello.supports_session_ticket() && server_settings.offer_session_ticket()) {
742✔
278
      m_data->extensions().add(new Session_Ticket_Extension());
543✔
279
   }
280

281
   if(m_data->legacy_version().is_datagram_protocol()) {
742✔
282
      const std::vector<uint16_t> server_srtp = policy.srtp_profiles();
294✔
283
      const std::vector<uint16_t> client_srtp = client_hello.srtp_profiles();
294✔
284

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

296
         if(shared != 0) {
2✔
297
            m_data->extensions().add(new SRTP_Protection_Profiles(shared));
1✔
298
         }
299
      }
300
   }
296✔
301
   // NOLINTEND(*-owning-memory)
302

303
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
742✔
304

305
   hash.update(io.send(*this));
1,484✔
306
}
742✔
307

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

329
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
226✔
330
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
11✔
331
   }
332

333
   if(client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
226✔
334
      const Ciphersuite c = resumed_session.ciphersuite();
1✔
335
      if(c.cbc_ciphersuite()) {
1✔
336
         m_data->extensions().add(new Encrypt_then_MAC);
1✔
337
      }
338
   }
339

340
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
226✔
341
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
640✔
342
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
207✔
343
   }
344

345
   if(client_hello.secure_renegotiation()) {
226✔
346
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
226✔
347
   }
348

349
   if(client_hello.supports_session_ticket() && offer_session_ticket) {
226✔
350
      m_data->extensions().add(new Session_Ticket_Extension());
1✔
351
   }
352
   // NOLINTEND(*-owning-memory)
353

354
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
226✔
355

356
   hash.update(io.send(*this));
452✔
357
}
226✔
358

359
Server_Hello_12::Server_Hello_12(const std::vector<uint8_t>& buf) :
2,522✔
360
      Server_Hello_12(std::make_unique<Server_Hello_Internal>(buf)) {}
2,522✔
361

362
Server_Hello_12::Server_Hello_12(std::unique_ptr<Server_Hello_Internal> data) : Server_Hello(std::move(data)) {
2,876✔
363
   if(!m_data->version().is_pre_tls_13()) {
5,752✔
364
      throw TLS_Exception(Alert::ProtocolVersion, "Expected server hello of (D)TLS 1.2 or lower");
×
365
   }
366
}
2,876✔
367

368
Protocol_Version Server_Hello_12::selected_version() const {
490✔
369
   return legacy_version();
490✔
370
}
371

372
bool Server_Hello_12::secure_renegotiation() const {
3,206✔
373
   return m_data->extensions().has<Renegotiation_Extension>();
3,206✔
374
}
375

376
std::vector<uint8_t> Server_Hello_12::renegotiation_info() const {
3,113✔
377
   if(const Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
3,113✔
378
      return reneg->renegotiation_info();
3,113✔
379
   }
380
   return std::vector<uint8_t>();
×
381
}
382

383
bool Server_Hello_12::supports_extended_master_secret() const {
3,950✔
384
   return m_data->extensions().has<Extended_Master_Secret>();
3,950✔
385
}
386

387
bool Server_Hello_12::supports_encrypt_then_mac() const {
6,893✔
388
   return m_data->extensions().has<Encrypt_then_MAC>();
6,893✔
389
}
390

391
bool Server_Hello_12::supports_certificate_status_message() const {
1,935✔
392
   return m_data->extensions().has<Certificate_Status_Request>();
1,935✔
393
}
394

395
bool Server_Hello_12::supports_session_ticket() const {
2,631✔
396
   return m_data->extensions().has<Session_Ticket_Extension>();
2,631✔
397
}
398

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

408
   return 0;
409
}
410

411
std::string Server_Hello_12::next_protocol() const {
2,163✔
412
   if(auto* alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
2,163✔
413
      return alpn->single_protocol();
140✔
414
   }
415
   return "";
2,023✔
416
}
417

418
bool Server_Hello_12::prefers_compressed_ec_points() const {
25✔
419
   if(auto* ecc_formats = m_data->extensions().get<Supported_Point_Formats>()) {
25✔
420
      return ecc_formats->prefers_compressed();
13✔
421
   }
422
   return false;
423
}
424

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

434
   return std::nullopt;
612✔
435
}
436

437
/*
438
* Create a new Server Hello Done message
439
*/
440
Server_Hello_Done::Server_Hello_Done(Handshake_IO& io, Handshake_Hash& hash) {
717✔
441
   hash.update(io.send(*this));
1,434✔
442
}
717✔
443

444
/*
445
* Deserialize a Server Hello Done message
446
*/
447
Server_Hello_Done::Server_Hello_Done(const std::vector<uint8_t>& buf) {
863✔
448
   if(!buf.empty()) {
863✔
449
      throw Decoding_Error("Server_Hello_Done: Must be empty, and is not");
2✔
450
   }
451
}
861✔
452

453
/*
454
* Serialize a Server Hello Done message
455
*/
456
std::vector<uint8_t> Server_Hello_Done::serialize() const {
717✔
457
   return std::vector<uint8_t>();
717✔
458
}
459

460
#if defined(BOTAN_HAS_TLS_13)
461

462
const Server_Hello_13::Server_Hello_Tag Server_Hello_13::as_server_hello;
463
const Server_Hello_13::Hello_Retry_Request_Tag Server_Hello_13::as_hello_retry_request;
464
const Server_Hello_13::Hello_Retry_Request_Creation_Tag Server_Hello_13::as_new_hello_retry_request;
465

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

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

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

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

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

522
std::variant<Hello_Retry_Request, Server_Hello_13, Server_Hello_12> Server_Hello_13::parse(
1,047✔
523
   const std::vector<uint8_t>& buf) {
524
   auto data = std::make_unique<Server_Hello_Internal>(buf);
1,047✔
525
   const auto version = data->version();
1,035✔
526

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

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

538
      return Server_Hello_13(std::move(data));
930✔
539
   }
540

541
   throw TLS_Exception(Alert::ProtocolVersion, "unexpected server hello version: " + version.to_string());
×
542
}
1,035✔
543

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

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

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

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

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

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

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

592
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
469✔
593
                                 Server_Hello_13::Server_Hello_Tag /*tag*/) :
469✔
594
      Server_Hello(std::move(data)) {
469✔
595
   BOTAN_ASSERT_NOMSG(!m_data->is_hello_retry_request());
469✔
596
   basic_validation();
469✔
597

598
   const auto& exts = extensions();
465✔
599

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

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

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

630
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
69✔
631
                                 Server_Hello_13::Hello_Retry_Request_Tag /*tag*/) :
69✔
632
      Server_Hello(std::move(data)) {
69✔
633
   BOTAN_ASSERT_NOMSG(m_data->is_hello_retry_request());
69✔
634
   basic_validation();
69✔
635

636
   const auto& exts = extensions();
68✔
637

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

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

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

664
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
49✔
665
                                 Hello_Retry_Request_Creation_Tag /*tag*/) :
49✔
666
      Server_Hello(std::move(data)) {}
49✔
667

668
namespace {
669

670
uint16_t choose_ciphersuite(const Client_Hello_13& ch, const Policy& policy) {
432✔
671
   auto pref_list = ch.ciphersuites();
432✔
672
   // TODO: DTLS might need to make this version dynamic
673
   auto other_list = policy.ciphersuite_list(Protocol_Version::TLS_V13);
432✔
674

675
   if(policy.server_uses_own_ciphersuite_preferences()) {
432✔
676
      std::swap(pref_list, other_list);
432✔
677
   }
678

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

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

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

738
   if(key_exchange_group.has_value()) {
383✔
739
      BOTAN_ASSERT_NOMSG(ch.extensions().has<Key_Share>());
383✔
740
      m_data->extensions().add(Key_Share::create_as_encapsulation(
1,133✔
741
         key_exchange_group.value(), *ch.extensions().get<Key_Share>(), policy, cb, rng));
383✔
742
   }
743

744
   const auto& ch_exts = ch.extensions();
367✔
745

746
   if(ch_exts.has<PSK>()) {
367✔
747
      const auto cs = Ciphersuite::by_id(m_data->ciphersuite());
97✔
748
      BOTAN_ASSERT_NOMSG(cs);
97✔
749

750
      // RFC 8446 4.2.9
751
      //    A client MUST provide a "psk_key_exchange_modes" extension if it
752
      //    offers a "pre_shared_key" extension.
753
      //
754
      // Note: Client_Hello_13 constructor already performed a graceful check.
755
      auto* const psk_modes = ch_exts.get<PSK_Key_Exchange_Modes>();
97✔
756
      BOTAN_ASSERT_NONNULL(psk_modes);
97✔
757

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

771
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
367✔
772
}
383✔
773

774
std::optional<Protocol_Version> Server_Hello_13::random_signals_downgrade() const {
×
775
   const uint64_t last8 = load_be<uint64_t>(m_data->random().data(), 3);
×
776
   if(last8 == DOWNGRADE_TLS11) {
×
777
      return Protocol_Version::TLS_V11;
×
778
   }
779
   if(last8 == DOWNGRADE_TLS12) {
×
780
      return Protocol_Version::TLS_V12;
×
781
   }
782

783
   return std::nullopt;
×
784
}
785

786
Protocol_Version Server_Hello_13::selected_version() const {
2,604✔
787
   auto* const versions_ext = m_data->extensions().get<Supported_Versions>();
2,604✔
788
   BOTAN_ASSERT_NOMSG(versions_ext);
2,604✔
789
   const auto& versions = versions_ext->versions();
2,604✔
790
   BOTAN_ASSERT_NOMSG(versions.size() == 1);
2,604✔
791
   return versions.front();
2,604✔
792
}
793

794
Hello_Retry_Request::Hello_Retry_Request(std::unique_ptr<Server_Hello_Internal> data) :
69✔
795
      Server_Hello_13(std::move(data), Server_Hello_13::as_hello_retry_request) {}
69✔
796

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

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

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

834
   m_data->extensions().add(new Key_Share(selected_group));
49✔
835
   // NOLINTEND(*-owning-memory)
836

837
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
49✔
838
}
49✔
839

840
#endif  // BOTAN_HAS_TLS_13
841

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