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

randombit / botan / 11385316852

17 Oct 2024 12:51PM UTC coverage: 91.14% (+0.02%) from 91.125%
11385316852

push

github

web-flow
Merge pull request #4389 from Rohde-Schwarz/tls/bogo_update

TLS: BoGo tests update

91037 of 99887 relevant lines covered (91.14%)

9381295.27 hits per line

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

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

12
#include <botan/tls_messages.h>
13

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

26
#include <array>
27

28
namespace Botan::TLS {
29

30
namespace {
31

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

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

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

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

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

66
   return random;
1,111✔
67
}
×
68

69
}  // namespace
70

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

86
         TLS_Data_Reader reader("ServerHello", buf);
3,539✔
87

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

91
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,539✔
92

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

100
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,539✔
101
         m_ciphersuite = reader.get_uint16_t();
3,530✔
102
         m_comp_method = reader.get_byte();
3,528✔
103

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

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

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

141
      Protocol_Version legacy_version() const { return m_legacy_version; }
2,105✔
142

143
      const Session_ID& session_id() const { return m_session_id; }
5,803✔
144

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

147
      uint16_t ciphersuite() const { return m_ciphersuite; }
2,202✔
148

149
      uint8_t comp_method() const { return m_comp_method; }
1,376✔
150

151
      bool is_hello_retry_request() const { return m_is_hello_retry_request; }
1,048✔
152

153
      const Extensions& extensions() const { return m_extensions; }
4,410✔
154

155
      Extensions& extensions() { return m_extensions; }
33,113✔
156

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

165
      Extensions m_extensions;
166
};
167

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

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

173
Server_Hello::~Server_Hello() = default;
16,138✔
174

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

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

186
   append_tls_length_value(buf, m_data->session_id().get(), 1);
1,376✔
187

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

191
   buf.push_back(m_data->comp_method());
1,376✔
192

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

195
   return buf;
1,376✔
196
}
×
197

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

202
Protocol_Version Server_Hello::legacy_version() const {
9,649✔
203
   return m_data->legacy_version();
9,649✔
204
}
205

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

210
uint8_t Server_Hello::compression_method() const {
5,288✔
211
   return m_data->comp_method();
5,288✔
212
}
213

214
const Session_ID& Server_Hello::session_id() const {
5,803✔
215
   return m_data->session_id();
5,803✔
216
}
217

218
uint16_t Server_Hello::ciphersuite() const {
12,537✔
219
   return m_data->ciphersuite();
12,537✔
220
}
221

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

226
const Extensions& Server_Hello::extensions() const {
7,072✔
227
   return m_data->extensions();
7,072✔
228
}
229

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

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

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

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

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

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

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

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

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

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

292
         if(shared) {
2✔
293
            m_data->extensions().add(new SRTP_Protection_Profiles(shared));
1✔
294
         }
295
      }
296
   }
290✔
297

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

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

303
// Resuming
304
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
231✔
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) :
231✔
314
      Server_Hello(std::make_unique<Server_Hello_Internal>(resumed_session.version(),
462✔
315
                                                           client_hello.session_id(),
231✔
316
                                                           make_hello_random(rng, cb, policy),
231✔
317
                                                           resumed_session.ciphersuite_code(),
462✔
318
                                                           uint8_t(0))) {
462✔
319
   if(client_hello.supports_extended_master_secret()) {
231✔
320
      m_data->extensions().add(new Extended_Master_Secret);
230✔
321
   }
322

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

327
   if(client_hello.supports_encrypt_then_mac() && policy.negotiate_encrypt_then_mac()) {
231✔
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() &&
231✔
335
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
649✔
336
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
209✔
337
   }
338

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

343
   if(client_hello.supports_session_ticket() && offer_session_ticket) {
231✔
344
      m_data->extensions().add(new Session_Ticket_Extension());
1✔
345
   }
346

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

349
   hash.update(io.send(*this));
462✔
350
}
231✔
351

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

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

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

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

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

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

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

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

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

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

401
   return 0;
402
}
403

404
std::string Server_Hello_12::next_protocol() const {
1,172✔
405
   if(auto alpn = m_data->extensions().get<Application_Layer_Protocol_Notification>()) {
1,172✔
406
      return alpn->single_protocol();
133✔
407
   }
408
   return "";
1,039✔
409
}
410

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

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

427
   return std::nullopt;
490✔
428
}
429

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

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

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

453
#if defined(BOTAN_HAS_TLS_13)
454

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

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

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

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

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

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

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

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

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

531
      return Server_Hello_13(std::move(data));
928✔
532
   }
533

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

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

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

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

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

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

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

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

585
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Server_Hello_13::Server_Hello_Tag) :
468✔
586
      Server_Hello(std::move(data)) {
468✔
587
   BOTAN_ASSERT_NOMSG(!m_data->is_hello_retry_request());
468✔
588
   basic_validation();
468✔
589

590
   const auto& exts = extensions();
464✔
591

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

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

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

622
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data,
56✔
623
                                 Server_Hello_13::Hello_Retry_Request_Tag) :
56✔
624
      Server_Hello(std::move(data)) {
56✔
625
   BOTAN_ASSERT_NOMSG(m_data->is_hello_retry_request());
56✔
626
   basic_validation();
56✔
627

628
   const auto& exts = extensions();
55✔
629

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

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

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

656
Server_Hello_13::Server_Hello_13(std::unique_ptr<Server_Hello_Internal> data, Hello_Retry_Request_Creation_Tag) :
36✔
657
      Server_Hello(std::move(data)) {}
36✔
658

659
namespace {
660

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

666
   if(policy.server_uses_own_ciphersuite_preferences()) {
418✔
667
      std::swap(pref_list, other_list);
418✔
668
   }
669

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

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

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

729
   if(key_exchange_group.has_value()) {
382✔
730
      BOTAN_ASSERT_NOMSG(ch.extensions().has<Key_Share>());
382✔
731
      m_data->extensions().add(Key_Share::create_as_encapsulation(
1,131✔
732
         key_exchange_group.value(), *ch.extensions().get<Key_Share>(), policy, cb, rng));
382✔
733
   }
734

735
   auto& ch_exts = ch.extensions();
367✔
736

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

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

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

762
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
367✔
763
}
382✔
764

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

774
   return std::nullopt;
×
775
}
776

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

785
Hello_Retry_Request::Hello_Retry_Request(std::unique_ptr<Server_Hello_Internal> data) :
56✔
786
      Server_Hello_13(std::move(data), Server_Hello_13::as_hello_retry_request) {}
56✔
787

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

808
   BOTAN_STATE_CHECK(!value_exists(ch.extensions().get<Key_Share>()->offered_groups(), selected_group));
75✔
809

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

823
   m_data->extensions().add(new Key_Share(selected_group));
36✔
824

825
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
36✔
826
}
36✔
827

828
#endif  // BOTAN_HAS_TLS_13
829

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

© 2025 Coveralls, Inc