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

randombit / botan / 19012754211

02 Nov 2025 01:10PM UTC coverage: 90.677% (+0.006%) from 90.671%
19012754211

push

github

web-flow
Merge pull request #5137 from randombit/jack/clang-tidy-includes

Remove various unused includes flagged by clang-tidy misc-include-cleaner

100457 of 110786 relevant lines covered (90.68%)

12189873.8 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.h>
13

14
#include <botan/tls_callbacks.h>
15
#include <botan/tls_exceptn.h>
16
#include <botan/tls_extensions.h>
17
#include <botan/tls_session_manager.h>
18
#include <botan/internal/ct_utils.h>
19
#include <botan/internal/stl_util.h>
20
#include <botan/internal/tls_handshake_hash.h>
21
#include <botan/internal/tls_handshake_io.h>
22
#include <botan/internal/tls_reader.h>
23
#include <array>
24

25
namespace Botan::TLS {
26

27
namespace {
28

29
const uint64_t DOWNGRADE_TLS11 = 0x444F574E47524400;
30
const uint64_t DOWNGRADE_TLS12 = 0x444F574E47524401;
31

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

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

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

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

63
   return random;
1,118✔
64
}
×
65

66
}  // namespace
67

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

83
         TLS_Data_Reader reader("ServerHello", buf);
3,563✔
84

85
         const uint8_t major_version = reader.get_byte();
3,563✔
86
         const uint8_t minor_version = reader.get_byte();
3,563✔
87

88
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,563✔
89

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

97
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,563✔
98
         m_ciphersuite = reader.get_uint16_t();
3,554✔
99
         m_comp_method = reader.get_byte();
3,552✔
100

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

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

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

138
      Protocol_Version legacy_version() const { return m_legacy_version; }
2,132✔
139

140
      const Session_ID& session_id() const { return m_session_id; }
6,913✔
141

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

144
      uint16_t ciphersuite() const { return m_ciphersuite; }
2,229✔
145

146
      uint8_t comp_method() const { return m_comp_method; }
1,397✔
147

148
      bool is_hello_retry_request() const { return m_is_hello_retry_request; }
1,076✔
149

150
      const Extensions& extensions() const { return m_extensions; }
4,449✔
151

152
      Extensions& extensions() { return m_extensions; }
39,559✔
153

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

162
      Extensions m_extensions;
163
};
164

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

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

170
Server_Hello::~Server_Hello() = default;
16,397✔
171

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

179
   buf.push_back(m_data->legacy_version().major_version());
1,397✔
180
   buf.push_back(m_data->legacy_version().minor_version());
1,397✔
181
   buf += m_data->random();
1,397✔
182

183
   append_tls_length_value(buf, m_data->session_id().get(), 1);
1,397✔
184

185
   buf.push_back(get_byte<0>(m_data->ciphersuite()));
1,397✔
186
   buf.push_back(get_byte<1>(m_data->ciphersuite()));
1,397✔
187

188
   buf.push_back(m_data->comp_method());
1,397✔
189

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

192
   return buf;
1,397✔
193
}
×
194

195
Handshake_Type Server_Hello::type() const {
7,382✔
196
   return Handshake_Type::ServerHello;
7,382✔
197
}
198

199
Protocol_Version Server_Hello::legacy_version() const {
13,964✔
200
   return m_data->legacy_version();
13,964✔
201
}
202

203
const std::vector<uint8_t>& Server_Hello::random() const {
3,830✔
204
   return m_data->random();
3,830✔
205
}
206

207
uint8_t Server_Hello::compression_method() const {
6,512✔
208
   return m_data->comp_method();
6,512✔
209
}
210

211
const Session_ID& Server_Hello::session_id() const {
6,913✔
212
   return m_data->session_id();
6,913✔
213
}
214

215
uint16_t Server_Hello::ciphersuite() const {
14,943✔
216
   return m_data->ciphersuite();
14,943✔
217
}
218

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

223
const Extensions& Server_Hello::extensions() const {
8,177✔
224
   return m_data->extensions();
8,177✔
225
}
226

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

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

253
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
735✔
254
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
121✔
255
   }
256

257
   const auto c = Ciphersuite::by_id(m_data->ciphersuite());
735✔
258

259
   if(c && c->cbc_ciphersuite() && client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
735✔
260
      m_data->extensions().add(new Encrypt_then_MAC);
14✔
261
   }
262

263
   if(c && c->ecc_ciphersuite() && client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
2,105✔
264
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
634✔
265
   }
266

267
   if(client_hello.secure_renegotiation()) {
735✔
268
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
732✔
269
   }
270

271
   if(client_hello.supports_session_ticket() && server_settings.offer_session_ticket()) {
735✔
272
      m_data->extensions().add(new Session_Ticket_Extension());
543✔
273
   }
274

275
   if(m_data->legacy_version().is_datagram_protocol()) {
735✔
276
      const std::vector<uint16_t> server_srtp = policy.srtp_profiles();
292✔
277
      const std::vector<uint16_t> client_srtp = client_hello.srtp_profiles();
292✔
278

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

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

297
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
735✔
298

299
   hash.update(io.send(*this));
1,470✔
300
}
735✔
301

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

323
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
233✔
324
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
18✔
325
   }
326

327
   if(client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
233✔
328
      Ciphersuite c = resumed_session.ciphersuite();
2✔
329
      if(c.cbc_ciphersuite()) {
2✔
330
         m_data->extensions().add(new Encrypt_then_MAC);
2✔
331
      }
332
   }
333

334
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
233✔
335
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
649✔
336
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
208✔
337
   }
338

339
   if(client_hello.secure_renegotiation()) {
233✔
340
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
233✔
341
   }
342

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

348
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
233✔
349

350
   hash.update(io.send(*this));
466✔
351
}
233✔
352

353
Server_Hello_12::Server_Hello_12(const std::vector<uint8_t>& buf) :
2,522✔
354
      Server_Hello_12(std::make_unique<Server_Hello_Internal>(buf)) {}
2,522✔
355

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

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

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

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

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

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

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

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

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

402
   return 0;
403
}
404

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

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

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

428
   return std::nullopt;
612✔
429
}
430

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

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

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

454
#if defined(BOTAN_HAS_TLS_13)
455

456
const Server_Hello_13::Server_Hello_Tag Server_Hello_13::as_server_hello;
457
const Server_Hello_13::Hello_Retry_Request_Tag Server_Hello_13::as_hello_retry_request;
458
const Server_Hello_13::Hello_Retry_Request_Creation_Tag Server_Hello_13::as_new_hello_retry_request;
459

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

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

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

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

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

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

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

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

532
      return Server_Hello_13(std::move(data));
930✔
533
   }
534

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

658
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
49✔
659
                                 Hello_Retry_Request_Creation_Tag /*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