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

randombit / botan / 20579846577

29 Dec 2025 06:24PM UTC coverage: 90.415% (+0.2%) from 90.243%
20579846577

push

github

web-flow
Merge pull request #5167 from randombit/jack/src-size-reductions

Changes to reduce unnecessary inclusions

101523 of 112285 relevant lines covered (90.42%)

12817276.56 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_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
#include <array>
25

26
namespace Botan::TLS {
27

28
namespace {
29

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

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

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

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

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

64
   return random;
1,123✔
65
}
×
66

67
}  // namespace
68

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

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

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

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

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

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

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

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

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

139
      Protocol_Version legacy_version() const { return m_legacy_version; }
2,137✔
140

141
      const Session_ID& session_id() const { return m_session_id; }
6,918✔
142

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

145
      uint16_t ciphersuite() const { return m_ciphersuite; }
2,234✔
146

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

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

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

153
      Extensions& extensions() { return m_extensions; }
39,587✔
154

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

163
      Extensions m_extensions;
164
};
165

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

268
   if(client_hello.secure_renegotiation()) {
740✔
269
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
737✔
270
   }
271

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

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

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

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

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

300
   hash.update(io.send(*this));
1,480✔
301
}
740✔
302

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

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

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

335
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
228✔
336
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
646✔
337
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
209✔
338
   }
339

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

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

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

351
   hash.update(io.send(*this));
456✔
352
}
228✔
353

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

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

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

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

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

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

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

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

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

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

403
   return 0;
404
}
405

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

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

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

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

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

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

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

455
#if defined(BOTAN_HAS_TLS_13)
456

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

587
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
469✔
588
                                 Server_Hello_13::Server_Hello_Tag /*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 /*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,
49✔
660
                                 Hello_Retry_Request_Creation_Tag /*tag*/) :
49✔
661
      Server_Hello(std::move(data)) {}
49✔
662

663
namespace {
664

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

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

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

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

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

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

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

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

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

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

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

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

778
   return std::nullopt;
×
779
}
780

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

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

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

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

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

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

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

835
#endif  // BOTAN_HAS_TLS_13
836

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