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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

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

94.74
/src/lib/tls/msg_server_hello.cpp
1
/*
2
* TLS Server Hello and Server Hello Done
3
* (C) 2004-2011,2015,2016,2019 Jack Lloyd
4
*     2016 Matthias Gierlings
5
*     2017 Harry Reimann, Rohde & Schwarz Cybersecurity
6
*     2021 Elektrobit Automotive GmbH
7
*     2022 René Meusel, Hannes Rantzsch - neXenio GmbH
8
*
9
* Botan is released under the Simplified BSD License (see license.txt)
10
*/
11

12
#include <botan/tls_messages.h>
13

14
#include <botan/mem_ops.h>
15
#include <botan/tls_callbacks.h>
16
#include <botan/tls_exceptn.h>
17
#include <botan/tls_extensions.h>
18
#include <botan/tls_session_manager.h>
19
#include <botan/internal/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 <botan/internal/tls_session_key.h>
24

25
#include <array>
26

27
namespace Botan::TLS {
28

29
namespace {
30

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

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

39
bool random_signals_hello_retry_request(const std::vector<uint8_t>& random) {
3,420✔
40
   return constant_time_compare(random.data(), HELLO_RETRY_REQUEST_MARKER.data(), HELLO_RETRY_REQUEST_MARKER.size());
6,840✔
41
}
42

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

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

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

68
}
69

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

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

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

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

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

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

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

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

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

140
      Protocol_Version legacy_version() const { return m_legacy_version; }
1,984✔
141

142
      const Session_ID& session_id() const { return m_session_id; }
5,608✔
143

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

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

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

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

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

154
      Extensions& extensions() { return m_extensions; }
32,018✔
155

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

164
      Extensions m_extensions;
165
};
166

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

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

172
Server_Hello::~Server_Hello() = default;
15,460✔
173

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

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

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

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

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

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

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

197
Handshake_Type Server_Hello::type() const { return Handshake_Type::ServerHello; }
6,921✔
198

199
Protocol_Version Server_Hello::legacy_version() const { return m_data->legacy_version(); }
9,196✔
200

201
const std::vector<uint8_t>& Server_Hello::random() const { return m_data->random(); }
3,484✔
202

203
uint8_t Server_Hello::compression_method() const { return m_data->comp_method(); }
5,120✔
204

205
const Session_ID& Server_Hello::session_id() const { return m_data->session_id(); }
5,608✔
206

207
uint16_t Server_Hello::ciphersuite() const { return m_data->ciphersuite(); }
12,041✔
208

209
std::set<Extension_Code> Server_Hello::extension_types() const { return m_data->extensions().extension_types(); }
1,107✔
210

211
const Extensions& Server_Hello::extensions() const { return m_data->extensions(); }
7,351✔
212

213
// New session case
214
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
675✔
215
                                 Handshake_Hash& hash,
216
                                 const Policy& policy,
217
                                 Callbacks& cb,
218
                                 RandomNumberGenerator& rng,
219
                                 const std::vector<uint8_t>& reneg_info,
220
                                 const Client_Hello_12& client_hello,
221
                                 const Server_Hello_12::Settings& server_settings,
222
                                 std::string_view next_protocol) :
675✔
223
      Server_Hello(std::make_unique<Server_Hello_Internal>(
675✔
224
         server_settings.protocol_version(),
1,350✔
225
         server_settings.session_id(),
675✔
226
         make_server_hello_random(rng, server_settings.protocol_version(), cb, policy),
675✔
227
         server_settings.ciphersuite(),
675✔
228
         uint8_t(0))) {
1,350✔
229
   if(client_hello.supports_extended_master_secret()) {
675✔
230
      m_data->extensions().add(new Extended_Master_Secret);
670✔
231
   }
232

233
   // Sending the extension back does not commit us to sending a stapled response
234
   if(client_hello.supports_cert_status_message() && policy.support_cert_status_message()) {
675✔
235
      m_data->extensions().add(new Certificate_Status_Request);
187✔
236
   }
237

238
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
675✔
239
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
116✔
240
   }
241

242
   const auto c = Ciphersuite::by_id(m_data->ciphersuite());
675✔
243

244
   if(c && c->cbc_ciphersuite() && client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
675✔
245
      m_data->extensions().add(new Encrypt_then_MAC);
13✔
246
   }
247

248
   if(c && c->ecc_ciphersuite() && client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
1,833✔
249
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
578✔
250
   }
251

252
   if(client_hello.secure_renegotiation()) {
675✔
253
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
672✔
254
   }
255

256
   if(client_hello.supports_session_ticket() && server_settings.offer_session_ticket()) {
675✔
257
      m_data->extensions().add(new Session_Ticket_Extension());
489✔
258
   }
259

260
   if(m_data->legacy_version().is_datagram_protocol()) {
675✔
261
      const std::vector<uint16_t> server_srtp = policy.srtp_profiles();
260✔
262
      const std::vector<uint16_t> client_srtp = client_hello.srtp_profiles();
260✔
263

264
      if(!server_srtp.empty() && !client_srtp.empty()) {
260✔
265
         uint16_t shared = 0;
266
         // always using server preferences for now
267
         for(auto s_srtp : server_srtp)
6✔
268
            for(auto c_srtp : client_srtp) {
16✔
269
               if(shared == 0 && s_srtp == c_srtp) {
12✔
270
                  shared = s_srtp;
1✔
271
               }
272
            }
273

274
         if(shared) {
2✔
275
            m_data->extensions().add(new SRTP_Protection_Profiles(shared));
1✔
276
         }
277
      }
278
   }
262✔
279

280
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
675✔
281

282
   hash.update(io.send(*this));
1,350✔
283
}
675✔
284

285
// Resuming
286
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
233✔
287
                                 Handshake_Hash& hash,
288
                                 const Policy& policy,
289
                                 Callbacks& cb,
290
                                 RandomNumberGenerator& rng,
291
                                 const std::vector<uint8_t>& reneg_info,
292
                                 const Client_Hello_12& client_hello,
293
                                 const Session& resumed_session,
294
                                 bool offer_session_ticket,
295
                                 std::string_view next_protocol) :
233✔
296
      Server_Hello(std::make_unique<Server_Hello_Internal>(resumed_session.version(),
466✔
297
                                                           client_hello.session_id(),
233✔
298
                                                           make_hello_random(rng, cb, policy),
233✔
299
                                                           resumed_session.ciphersuite_code(),
466✔
300
                                                           uint8_t(0))) {
466✔
301
   if(client_hello.supports_extended_master_secret()) {
233✔
302
      m_data->extensions().add(new Extended_Master_Secret);
232✔
303
   }
304

305
   if(!next_protocol.empty() && client_hello.supports_alpn()) {
233✔
306
      m_data->extensions().add(new Application_Layer_Protocol_Notification(next_protocol));
20✔
307
   }
308

309
   if(client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
233✔
310
      Ciphersuite c = resumed_session.ciphersuite();
5✔
311
      if(c.cbc_ciphersuite()) {
5✔
312
         m_data->extensions().add(new Encrypt_then_MAC);
5✔
313
      }
314
   }
315

316
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
233✔
317
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
653✔
318
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
210✔
319
   }
320

321
   if(client_hello.secure_renegotiation()) {
233✔
322
      m_data->extensions().add(new Renegotiation_Extension(reneg_info));
233✔
323
   }
324

325
   if(client_hello.supports_session_ticket() && offer_session_ticket) {
233✔
326
      m_data->extensions().add(new Session_Ticket_Extension());
1✔
327
   }
328

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

331
   hash.update(io.send(*this));
466✔
332
}
233✔
333

334
Server_Hello_12::Server_Hello_12(const std::vector<uint8_t>& buf) :
2,440✔
335
      Server_Hello_12(std::make_unique<Server_Hello_Internal>(buf)) {}
2,440✔
336

337
Server_Hello_12::Server_Hello_12(std::unique_ptr<Server_Hello_Internal> data) : Server_Hello(std::move(data)) {
2,762✔
338
   if(!m_data->version().is_pre_tls_13()) {
5,524✔
339
      throw TLS_Exception(Alert::ProtocolVersion, "Expected server hello of (D)TLS 1.2 or lower");
×
340
   }
341
}
2,762✔
342

343
Protocol_Version Server_Hello_12::selected_version() const { return legacy_version(); }
458✔
344

345
bool Server_Hello_12::secure_renegotiation() const { return m_data->extensions().has<Renegotiation_Extension>(); }
2,082✔
346

347
std::vector<uint8_t> Server_Hello_12::renegotiation_info() const {
1,998✔
348
   if(Renegotiation_Extension* reneg = m_data->extensions().get<Renegotiation_Extension>()) {
1,998✔
349
      return reneg->renegotiation_info();
1,998✔
350
   }
351
   return std::vector<uint8_t>();
×
352
}
353

354
bool Server_Hello_12::supports_extended_master_secret() const {
3,798✔
355
   return m_data->extensions().has<Extended_Master_Secret>();
3,798✔
356
}
357

358
bool Server_Hello_12::supports_encrypt_then_mac() const { return m_data->extensions().has<Encrypt_then_MAC>(); }
5,956✔
359

360
bool Server_Hello_12::supports_certificate_status_message() const {
1,502✔
361
   return m_data->extensions().has<Certificate_Status_Request>();
1,502✔
362
}
363

364
bool Server_Hello_12::supports_session_ticket() const { return m_data->extensions().has<Session_Ticket_Extension>(); }
2,505✔
365

366
uint16_t Server_Hello_12::srtp_profile() const {
2,596✔
367
   if(auto srtp = m_data->extensions().get<SRTP_Protection_Profiles>()) {
2,596✔
368
      auto prof = srtp->profiles();
4✔
369
      if(prof.size() != 1 || prof[0] == 0) {
4✔
370
         throw Decoding_Error("Server sent malformed DTLS-SRTP extension");
×
371
      }
372
      return prof[0];
4✔
373
   }
4✔
374

375
   return 0;
376
}
377

378
std::string Server_Hello_12::next_protocol() const {
1,099✔
379
   if(auto alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
1,099✔
380
      return alpn->single_protocol();
137✔
381
   }
382
   return "";
962✔
383
}
384

385
bool Server_Hello_12::prefers_compressed_ec_points() const {
12✔
386
   if(auto ecc_formats = m_data->extensions().get<Supported_Point_Formats>()) {
12✔
387
      return ecc_formats->prefers_compressed();
9✔
388
   }
389
   return false;
390
}
391

392
std::optional<Protocol_Version> Server_Hello_12::random_signals_downgrade() const {
460✔
393
   const uint64_t last8 = load_be<uint64_t>(m_data->random().data(), 3);
460✔
394
   if(last8 == DOWNGRADE_TLS11) {
460✔
395
      return Protocol_Version::TLS_V11;
×
396
   }
397
   if(last8 == DOWNGRADE_TLS12) {
460✔
398
      return Protocol_Version::TLS_V12;
1✔
399
   }
400

401
   return std::nullopt;
459✔
402
}
403

404
/*
405
* Create a new Server Hello Done message
406
*/
407
Server_Hello_Done::Server_Hello_Done(Handshake_IO& io, Handshake_Hash& hash) { hash.update(io.send(*this)); }
1,974✔
408

409
/*
410
* Deserialize a Server Hello Done message
411
*/
412
Server_Hello_Done::Server_Hello_Done(const std::vector<uint8_t>& buf) {
773✔
413
   if(!buf.empty()) {
773✔
414
      throw Decoding_Error("Server_Hello_Done: Must be empty, and is not");
2✔
415
   }
416
}
771✔
417

418
/*
419
* Serialize a Server Hello Done message
420
*/
421
std::vector<uint8_t> Server_Hello_Done::serialize() const { return std::vector<uint8_t>(); }
658✔
422

423
#if defined(BOTAN_HAS_TLS_13)
424

425
Server_Hello_13::Server_Hello_Tag Server_Hello_13::as_server_hello;
426
Server_Hello_13::Hello_Retry_Request_Tag Server_Hello_13::as_hello_retry_request;
427
Server_Hello_13::Hello_Retry_Request_Creation_Tag Server_Hello_13::as_new_hello_retry_request;
428

429
std::variant<Hello_Retry_Request, Server_Hello_13> Server_Hello_13::create(const Client_Hello_13& ch,
412✔
430
                                                                           bool hello_retry_request_allowed,
431
                                                                           Session_Manager& session_mgr,
432
                                                                           RandomNumberGenerator& rng,
433
                                                                           const Policy& policy,
434
                                                                           Callbacks& cb) {
435
   const auto& exts = ch.extensions();
412✔
436

437
   // RFC 8446 4.2.9
438
   //    [With PSK with (EC)DHE key establishment], the client and server MUST
439
   //    supply "key_share" values [...].
440
   //
441
   // Note: We currently do not support PSK without (EC)DHE, hence, we can
442
   //       assume that those extensions are available.
443
   BOTAN_ASSERT_NOMSG(exts.has<Supported_Groups>() && exts.has<Key_Share>());
824✔
444
   const auto& supported_by_client = exts.get<Supported_Groups>()->groups();
412✔
445
   const auto& offered_by_client = exts.get<Key_Share>()->offered_groups();
412✔
446
   const auto selected_group = policy.choose_key_exchange_group(supported_by_client, offered_by_client);
412✔
447

448
   // RFC 8446 4.1.1
449
   //    If there is no overlap between the received "supported_groups" and the
450
   //    groups supported by the server, then the server MUST abort the
451
   //    handshake with a "handshake_failure" or an "insufficient_security" alert.
452
   if(selected_group == Named_Group::NONE) {
412✔
453
      throw TLS_Exception(Alert::HandshakeFailure, "Client did not offer any acceptable group");
×
454
   }
455

456
   if(!value_exists(offered_by_client, selected_group)) {
412✔
457
      // RFC 8446 4.1.4
458
      //    If a client receives a second HelloRetryRequest in the same
459
      //    connection (i.e., where the ClientHello was itself in response to a
460
      //    HelloRetryRequest), it MUST abort the handshake with an
461
      //    "unexpected_message" alert.
462
      BOTAN_STATE_CHECK(hello_retry_request_allowed);
35✔
463
      return Hello_Retry_Request(ch, selected_group, policy, cb);
70✔
464
   } else {
465
      return Server_Hello_13(ch, selected_group, session_mgr, rng, cb, policy);
734✔
466
   }
467
}
392✔
468

469
std::variant<Hello_Retry_Request, Server_Hello_13, Server_Hello_12> Server_Hello_13::parse(
986✔
470
   const std::vector<uint8_t>& buf) {
471
   auto data = std::make_unique<Server_Hello_Internal>(buf);
986✔
472
   const auto version = data->version();
974✔
473

474
   // server hello that appears to be pre-TLS 1.3, takes precedence over...
475
   if(version.is_pre_tls_13()) {
974✔
476
      return Server_Hello_12(std::move(data));
930✔
477
   }
478

479
   // ... the TLS 1.3 "special case" aka. Hello_Retry_Request
480
   if(version == Protocol_Version::TLS_V13) {
509✔
481
      if(data->is_hello_retry_request()) {
509✔
482
         return Hello_Retry_Request(std::move(data));
81✔
483
      }
484

485
      return Server_Hello_13(std::move(data));
926✔
486
   }
487

488
   throw TLS_Exception(Alert::ProtocolVersion, "unexpected server hello version: " + version.to_string());
×
489
}
974✔
490

491
/**
492
 * Validation that applies to both Server Hello and Hello Retry Request
493
 */
494
void Server_Hello_13::basic_validation() const {
509✔
495
   BOTAN_ASSERT_NOMSG(m_data->version() == Protocol_Version::TLS_V13);
1,018✔
496

497
   // Note: checks that cannot be performed without contextual information
498
   //       are done in the specific TLS client implementation.
499
   // Note: The Supported_Version extension makes sure internally that
500
   //       exactly one entry is provided.
501

502
   // Note: Hello Retry Request basic validation is equivalent with the
503
   //       basic validations required for Server Hello
504
   //
505
   // RFC 8446 4.1.4
506
   //    Upon receipt of a HelloRetryRequest, the client MUST check the
507
   //    legacy_version, [...], and legacy_compression_method as specified in
508
   //    Section 4.1.3 and then process the extensions, starting with determining
509
   //    the version using "supported_versions".
510

511
   // RFC 8446 4.1.3
512
   //    In TLS 1.3, [...] the legacy_version field MUST be set to 0x0303
513
   if(legacy_version() != Protocol_Version::TLS_V12) {
509✔
514
      throw TLS_Exception(Alert::ProtocolVersion,
2✔
515
                          "legacy_version '" + legacy_version().to_string() + "' is not allowed");
4✔
516
   }
517

518
   // RFC 8446 4.1.3
519
   //    legacy_compression_method:  A single byte which MUST have the value 0.
520
   if(compression_method() != 0x00) {
507✔
521
      throw TLS_Exception(Alert::DecodeError, "compression is not supported in TLS 1.3");
2✔
522
   }
523

524
   // RFC 8446 4.1.3
525
   //    All TLS 1.3 ServerHello messages MUST contain the "supported_versions" extension.
526
   if(!extensions().has<Supported_Versions>()) {
505✔
527
      throw TLS_Exception(Alert::MissingExtension, "server hello did not contain 'supported version' extension");
×
528
   }
529

530
   // RFC 8446 4.2.1
531
   //    A server which negotiates TLS 1.3 MUST respond by sending
532
   //    a "supported_versions" extension containing the selected version
533
   //    value (0x0304).
534
   if(selected_version() != Protocol_Version::TLS_V13) {
505✔
535
      throw TLS_Exception(Alert::IllegalParameter, "TLS 1.3 Server Hello selected a different version");
1✔
536
   }
537
}
504✔
538

539
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Server_Hello_13::Server_Hello_Tag) :
467✔
540
      Server_Hello(std::move(data)) {
467✔
541
   BOTAN_ASSERT_NOMSG(!m_data->is_hello_retry_request());
467✔
542
   basic_validation();
467✔
543

544
   const auto& exts = extensions();
463✔
545

546
   // RFC 8446 4.1.3
547
   //    The ServerHello MUST only include extensions which are required to
548
   //    establish the cryptographic context and negotiate the protocol version.
549
   //    [...]
550
   //    Other extensions (see Section 4.2) are sent separately in the
551
   //    EncryptedExtensions message.
552
   //
553
   // Note that further validation dependent on the client hello is done in the
554
   // TLS client implementation.
555
   const std::set<Extension_Code> allowed = {
463✔
556
      Extension_Code::KeyShare,
557
      Extension_Code::SupportedVersions,
558
      Extension_Code::PresharedKey,
559
   };
463✔
560

561
   // As the ServerHello shall only contain essential extensions, we don't give
562
   // any slack for extensions not implemented by Botan here.
563
   if(exts.contains_other_than(allowed)) {
463✔
564
      throw TLS_Exception(Alert::UnsupportedExtension, "Server Hello contained an extension that is not allowed");
2✔
565
   }
566

567
   // RFC 8446 4.1.3
568
   //    Current ServerHello messages additionally contain
569
   //    either the "pre_shared_key" extension or the "key_share"
570
   //    extension, or both [...].
571
   if(!exts.has<Key_Share>() && !exts.has<PSK_Key_Exchange_Modes>()) {
463✔
572
      throw TLS_Exception(Alert::MissingExtension, "server hello must contain key exchange information");
2✔
573
   }
574
}
467✔
575

576
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
42✔
577
                                 Server_Hello_13::Hello_Retry_Request_Tag) :
42✔
578
      Server_Hello(std::move(data)) {
42✔
579
   BOTAN_ASSERT_NOMSG(m_data->is_hello_retry_request());
42✔
580
   basic_validation();
42✔
581

582
   const auto& exts = extensions();
41✔
583

584
   // RFC 8446 4.1.4
585
   //     The HelloRetryRequest extensions defined in this specification are:
586
   //     -  supported_versions (see Section 4.2.1)
587
   //     -  cookie (see Section 4.2.2)
588
   //     -  key_share (see Section 4.2.8)
589
   const std::set<Extension_Code> allowed = {
41✔
590
      Extension_Code::Cookie,
591
      Extension_Code::SupportedVersions,
592
      Extension_Code::KeyShare,
593
   };
41✔
594

595
   // As the Hello Retry Request shall only contain essential extensions, we
596
   // don't give any slack for extensions not implemented by Botan here.
597
   if(exts.contains_other_than(allowed)) {
41✔
598
      throw TLS_Exception(Alert::UnsupportedExtension,
1✔
599
                          "Hello Retry Request contained an extension that is not allowed");
2✔
600
   }
601

602
   // RFC 8446 4.1.4
603
   //    Clients MUST abort the handshake with an "illegal_parameter" alert if
604
   //    the HelloRetryRequest would not result in any change in the ClientHello.
605
   if(!exts.has<Key_Share>() && !exts.has<Cookie>()) {
42✔
606
      throw TLS_Exception(Alert::IllegalParameter, "Hello Retry Request does not request any changes to Client Hello");
1✔
607
   }
608
}
42✔
609

610
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Hello_Retry_Request_Creation_Tag) :
35✔
611
      Server_Hello(std::move(data)) {}
35✔
612

613
namespace {
614

615
uint16_t choose_ciphersuite(const Client_Hello_13& ch, const Policy& policy) {
412✔
616
   auto pref_list = ch.ciphersuites();
412✔
617
   // TODO: DTLS might need to make this version dynamic
618
   auto other_list = policy.ciphersuite_list(Protocol_Version::TLS_V13);
432✔
619

620
   if(policy.server_uses_own_ciphersuite_preferences()) {
412✔
621
      std::swap(pref_list, other_list);
412✔
622
   }
623

624
   for(auto suite_id : pref_list) {
1,282✔
625
      // TODO: take potentially available PSKs into account to select a
626
      //       compatible ciphersuite.
627
      //
628
      // Assuming the client sent one or more PSKs, we would first need to find
629
      // the hash functions they are associated to. For session tickets, that
630
      // would mean decrypting the ticket and comparing the cipher suite used in
631
      // those tickets. For (currently not yet supported) pre-assigned PSKs, the
632
      // hash function needs to be specified along with them.
633
      //
634
      // Then we could refine the ciphersuite selection using the required hash
635
      // function for the PSK(s) we are wishing to use down the road.
636
      //
637
      // For now, we just negotiate the cipher suite blindly and hope for the
638
      // best. As long as PSKs are used for session resumption only, this has a
639
      // high chance of success. Previous handshakes with this client have very
640
      // likely selected the same ciphersuite anyway.
641
      //
642
      // See also RFC 8446 4.2.11
643
      //    When session resumption is the primary use case of PSKs, the most
644
      //    straightforward way to implement the PSK/cipher suite matching
645
      //    requirements is to negotiate the cipher suite first [...].
646
      if(value_exists(other_list, suite_id)) {
2,524✔
647
         return suite_id;
392✔
648
      }
649
   }
650

651
   // RFC 8446 4.1.1
652
   //     If the server is unable to negotiate a supported set of parameters
653
   //     [...], it MUST abort the handshake with either a "handshake_failure"
654
   //     or "insufficient_security" fatal alert [...].
655
   throw TLS_Exception(Alert::HandshakeFailure, "Can't agree on a ciphersuite with client");
20✔
656
}
804✔
657
}
658

659
Server_Hello_13::Server_Hello_13(const Client_Hello_13& ch,
377✔
660
                                 std::optional<Named_Group> key_exchange_group,
661
                                 Session_Manager& session_mgr,
662
                                 RandomNumberGenerator& rng,
663
                                 Callbacks& cb,
664
                                 const Policy& policy) :
377✔
665
      Server_Hello(std::make_unique<Server_Hello_Internal>(
714✔
666
         Protocol_Version::TLS_V12,
667
         ch.session_id(),
357✔
668
         make_server_hello_random(rng, Protocol_Version::TLS_V13, cb, policy),
357✔
669
         choose_ciphersuite(ch, policy),
357✔
670
         uint8_t(0) /* compression method */
734✔
671
         )) {
734✔
672
   // RFC 8446 4.2.1
673
   //    A server which negotiates TLS 1.3 MUST respond by sending a
674
   //    "supported_versions" extension containing the selected version
675
   //    value (0x0304). It MUST set the ServerHello.legacy_version field to
676
   //     0x0303 (TLS 1.2).
677
   //
678
   // Note that the legacy version (TLS 1.2) is set in this constructor's
679
   // initializer list, accordingly.
680
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13));
357✔
681

682
   if(key_exchange_group.has_value()) {
357✔
683
      m_data->extensions().add(new Key_Share(key_exchange_group.value(), cb, rng));
357✔
684
   }
685

686
   auto& ch_exts = ch.extensions();
357✔
687

688
   if(ch_exts.has<PSK>()) {
357✔
689
      const auto cs = Ciphersuite::by_id(m_data->ciphersuite());
98✔
690
      BOTAN_ASSERT_NOMSG(cs);
98✔
691

692
      // RFC 8446 4.2.9
693
      //    A client MUST provide a "psk_key_exchange_modes" extension if it
694
      //    offers a "pre_shared_key" extension.
695
      //
696
      // Note: Client_Hello_13 constructor already performed a graceful check.
697
      const auto psk_modes = ch_exts.get<PSK_Key_Exchange_Modes>();
98✔
698
      BOTAN_ASSERT_NONNULL(psk_modes);
98✔
699

700
      // TODO: also support PSK_Key_Exchange_Mode::PSK_KE
701
      //       (PSK-based handshake without an additional ephemeral key exchange)
702
      if(value_exists(psk_modes->modes(), PSK_Key_Exchange_Mode::PSK_DHE_KE)) {
98✔
703
         if(auto server_psk = ch_exts.get<PSK>()->select_offered_psk(cs.value(), session_mgr, cb, policy)) {
97✔
704
            // RFC 8446 4.2.11
705
            //    In order to accept PSK key establishment, the server sends a
706
            //    "pre_shared_key" extension indicating the selected identity.
707
            m_data->extensions().add(std::move(server_psk));
190✔
708
         }
97✔
709
      }
710
   }
711

712
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
357✔
713
}
357✔
714

715
std::optional<Protocol_Version> Server_Hello_13::random_signals_downgrade() const {
×
716
   const uint64_t last8 = load_be<uint64_t>(m_data->random().data(), 3);
×
717
   if(last8 == DOWNGRADE_TLS11) {
×
718
      return Protocol_Version::TLS_V11;
×
719
   }
720
   if(last8 == DOWNGRADE_TLS12) {
×
721
      return Protocol_Version::TLS_V12;
×
722
   }
723

724
   return std::nullopt;
×
725
}
726

727
Protocol_Version Server_Hello_13::selected_version() const {
2,448✔
728
   const auto versions_ext = m_data->extensions().get<Supported_Versions>();
2,448✔
729
   BOTAN_ASSERT_NOMSG(versions_ext);
2,448✔
730
   const auto& versions = versions_ext->versions();
2,448✔
731
   BOTAN_ASSERT_NOMSG(versions.size() == 1);
2,448✔
732
   return versions.front();
2,448✔
733
}
734

735
Hello_Retry_Request::Hello_Retry_Request(std::unique_ptr<Server_Hello_Internal> data) :
42✔
736
      Server_Hello_13(std::move(data), Server_Hello_13::as_hello_retry_request) {}
42✔
737

738
Hello_Retry_Request::Hello_Retry_Request(const Client_Hello_13& ch,
35✔
739
                                         Named_Group selected_group,
740
                                         const Policy& policy,
741
                                         Callbacks& cb) :
35✔
742
      Server_Hello_13(std::make_unique<Server_Hello_Internal>(Protocol_Version::TLS_V12 /* legacy_version */,
70✔
743
                                                              ch.session_id(),
35✔
744
                                                              HELLO_RETRY_REQUEST_MARKER,
745
                                                              choose_ciphersuite(ch, policy),
35✔
746
                                                              uint8_t(0) /* compression method */,
70✔
747
                                                              true /* is Hello Retry Request */
70✔
748
                                                              ),
749
                      as_new_hello_retry_request) {
70✔
750
   // RFC 8446 4.1.4
751
   //     As with the ServerHello, a HelloRetryRequest MUST NOT contain any
752
   //     extensions that were not first offered by the client in its
753
   //     ClientHello, with the exception of optionally the "cookie" [...]
754
   //     extension.
755
   BOTAN_STATE_CHECK(ch.extensions().has<Supported_Groups>());
35✔
756
   BOTAN_STATE_CHECK(ch.extensions().has<Key_Share>());
35✔
757

758
   BOTAN_STATE_CHECK(!value_exists(ch.extensions().get<Key_Share>()->offered_groups(), selected_group));
72✔
759

760
   // RFC 8446 4.1.4
761
   //    The server's extensions MUST contain "supported_versions".
762
   //
763
   // RFC 8446 4.2.1
764
   //    A server which negotiates TLS 1.3 MUST respond by sending a
765
   //    "supported_versions" extension containing the selected version
766
   //    value (0x0304). It MUST set the ServerHello.legacy_version field to
767
   //    0x0303 (TLS 1.2).
768
   //
769
   // Note that the legacy version (TLS 1.2) is set in this constructor's
770
   // initializer list, accordingly.
771
   m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13));
35✔
772

773
   m_data->extensions().add(new Key_Share(selected_group));
35✔
774

775
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
35✔
776
}
35✔
777

778
#endif  // BOTAN_HAS_TLS_13
779

780
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc