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

randombit / botan / 5587580523

18 Jul 2023 12:45PM UTC coverage: 91.72% (+0.03%) from 91.691%
5587580523

Pull #3618

github

web-flow
Merge b6d23d19e into 65b754862
Pull Request #3618: [TLS 1.3] PSK Support

78438 of 85519 relevant lines covered (91.72%)

12184016.91 hits per line

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

94.75
/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,432✔
40
   return constant_time_compare(random.data(), HELLO_RETRY_REQUEST_MARKER.data(), HELLO_RETRY_REQUEST_MARKER.size());
6,864✔
41
}
42

43
std::vector<uint8_t> make_server_hello_random(RandomNumberGenerator& rng,
1,034✔
44
                                              Protocol_Version offered_version,
45
                                              Callbacks& cb,
46
                                              const Policy& policy) {
47
   BOTAN_UNUSED(offered_version);
1,034✔
48
   auto random = make_hello_random(rng, cb, policy);
1,034✔
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,034✔
59
      constexpr size_t downgrade_signal_length = sizeof(DOWNGRADE_TLS12);
447✔
60
      BOTAN_ASSERT_NOMSG(random.size() >= downgrade_signal_length);
447✔
61
      auto lastbytes = random.data() + random.size() - downgrade_signal_length;
447✔
62
      store_be(DOWNGRADE_TLS12, lastbytes);
447✔
63
   }
64

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

68
}  // namespace
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,438✔
81
         if(buf.size() < 38) {
3,438✔
82
            throw Decoding_Error("Server_Hello: Packet corrupted");
6✔
83
         }
84

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

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

90
         m_legacy_version = Protocol_Version(major_version, minor_version);
3,432✔
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,432✔
97
         m_is_hello_retry_request = random_signals_hello_retry_request(m_random);
3,432✔
98

99
         m_session_id = Session_ID(reader.get_range<uint8_t>(1, 0, 32));
3,432✔
100
         m_ciphersuite = reader.get_uint16_t();
3,423✔
101
         m_comp_method = reader.get_byte();
3,421✔
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,420✔
109
            reader,
110
            Connection_Side::Server,
111
            m_is_hello_retry_request ? Handshake_Type::HelloRetryRequest : Handshake_Type::ServerHello);
3,420✔
112
      }
3,587✔
113

114
      Server_Hello_Internal(Protocol_Version lv,
1,305✔
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,305✔
120
            m_legacy_version(lv),
1,305✔
121
            m_session_id(std::move(sid)),
1,305✔
122
            m_random(std::move(r)),
1,305✔
123
            m_is_hello_retry_request(is_hrr),
1,305✔
124
            m_ciphersuite(cs),
1,305✔
125
            m_comp_method(cm) {}
1,305✔
126

127
      Protocol_Version version() const {
4,261✔
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,261✔
138
      }
139

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

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

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

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

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

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

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

154
      Extensions& extensions() { return m_extensions; }
31,833✔
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,588✔
168

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

225
const Extensions& Server_Hello::extensions() const {
6,782✔
226
   return m_data->extensions();
6,782✔
227
}
228

229
// New session case
230
Server_Hello_12::Server_Hello_12(Handshake_IO& io,
676✔
231
                                 Handshake_Hash& hash,
232
                                 const Policy& policy,
233
                                 Callbacks& cb,
234
                                 RandomNumberGenerator& rng,
235
                                 const std::vector<uint8_t>& reneg_info,
236
                                 const Client_Hello_12& client_hello,
237
                                 const Server_Hello_12::Settings& server_settings,
238
                                 std::string_view next_protocol) :
676✔
239
      Server_Hello(std::make_unique<Server_Hello_Internal>(
676✔
240
         server_settings.protocol_version(),
1,352✔
241
         server_settings.session_id(),
676✔
242
         make_server_hello_random(rng, server_settings.protocol_version(), cb, policy),
676✔
243
         server_settings.ciphersuite(),
676✔
244
         uint8_t(0))) {
1,352✔
245
   if(client_hello.supports_extended_master_secret()) {
676✔
246
      m_data->extensions().add(new Extended_Master_Secret);
671✔
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()) {
676✔
251
      m_data->extensions().add(new Certificate_Status_Request);
186✔
252
   }
253

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

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

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

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

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

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

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

280
      if(!server_srtp.empty() && !client_srtp.empty()) {
267✔
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) {
2✔
292
            m_data->extensions().add(new SRTP_Protection_Profiles(shared));
1✔
293
         }
294
      }
295
   }
269✔
296

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

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

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

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

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

333
   if(resumed_session.ciphersuite().ecc_ciphersuite() &&
236✔
334
      client_hello.extension_types().contains(Extension_Code::EcPointFormats)) {
662✔
335
      m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression()));
211✔
336
   }
337

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

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

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

348
   hash.update(io.send(*this));
472✔
349
}
236✔
350

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

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

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

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

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

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

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

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

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

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

400
   return 0;
401
}
402

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

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

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

426
   return std::nullopt;
462✔
427
}
428

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

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

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

452
#if defined(BOTAN_HAS_TLS_13)
453

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

627
   const auto& exts = extensions();
41✔
628

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

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

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

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

658
namespace {
659

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

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

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

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

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

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

734
   auto& ch_exts = ch.extensions();
357✔
735

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

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

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

761
   cb.tls_modify_extensions(m_data->extensions(), Connection_Side::Server, type());
357✔
762
}
358✔
763

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

773
   return std::nullopt;
×
774
}
775

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

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

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

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

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

822
   m_data->extensions().add(new Key_Share(selected_group));
35✔
823

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

827
#endif  // BOTAN_HAS_TLS_13
828

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