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

randombit / botan / 21742894084

06 Feb 2026 07:47AM UTC coverage: 90.073% (+0.003%) from 90.07%
21742894084

push

github

web-flow
Merge pull request #5288 from Rohde-Schwarz/feature/disentangle_tls12_from_tls13

Refactor: Organize most TLS handshake messages into TLS 1.2 and TLS 1.3 modules

102234 of 113501 relevant lines covered (90.07%)

11492577.14 hits per line

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

94.8
/src/lib/tls/tls_session.cpp
1
/*
2
* TLS Session State
3
* (C) 2011-2012,2015,2019 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include <botan/tls_session.h>
9

10
#include <botan/aead.h>
11
#include <botan/asn1_obj.h>
12
#include <botan/ber_dec.h>
13
#include <botan/der_enc.h>
14
#include <botan/mac.h>
15
#include <botan/pem.h>
16
#include <botan/rng.h>
17
#include <botan/tls_callbacks.h>
18
#include <botan/x509_key.h>
19
#include <botan/internal/ct_utils.h>
20
#include <botan/internal/loadstor.h>
21
#include <botan/internal/stl_util.h>
22

23
#if defined(BOTAN_HAS_TLS_13)
24
   #include <botan/tls_messages_13.h>
25
#endif
26

27
#include <utility>
28

29
namespace Botan::TLS {
30

31
void Session_Handle::validate_constraints() const {
3,551✔
32
   std::visit(overloaded{
7,102✔
33
                 [](const Session_ID& id) {
695✔
34
                    // RFC 5246 7.4.1.2
35
                    //    opaque SessionID<0..32>;
36
                    BOTAN_ARG_CHECK(!id.empty(), "Session ID must not be empty");
695✔
37
                    BOTAN_ARG_CHECK(id.size() <= 32, "Session ID cannot be longer than 32 bytes");
695✔
38
                 },
695✔
39
                 [](const Session_Ticket& ticket) {
2,167✔
40
                    BOTAN_ARG_CHECK(!ticket.empty(), "Ticket most not be empty");
2,167✔
41
                    BOTAN_ARG_CHECK(ticket.size() <= std::numeric_limits<uint16_t>::max(),
2,167✔
42
                                    "Ticket cannot be longer than 64kB");
43
                 },
2,167✔
44
                 [](const Opaque_Session_Handle& handle) {
689✔
45
                    // RFC 8446 4.6.1
46
                    //    opaque ticket<1..2^16-1>;
47
                    BOTAN_ARG_CHECK(!handle.empty(), "Opaque session handle must not be empty");
689✔
48
                    BOTAN_ARG_CHECK(handle.size() <= std::numeric_limits<uint16_t>::max(),
689✔
49
                                    "Opaque session handle cannot be longer than 64kB");
50
                 },
689✔
51
              },
52
              m_handle);
3,551✔
53
}
3,551✔
54

55
Opaque_Session_Handle Session_Handle::opaque_handle() const {
367✔
56
   // both a Session_ID and a Session_Ticket could be an Opaque_Session_Handle
57
   return Opaque_Session_Handle(std::visit([](const auto& handle) { return handle.get(); }, m_handle));
734✔
58
}
59

60
std::optional<Session_ID> Session_Handle::id() const {
2,466✔
61
   if(is_id()) {
2,466✔
62
      return std::get<Session_ID>(m_handle);
632✔
63
   }
64

65
   // Opaque handles can mimic as a Session_ID if they are short enough
66
   if(is_opaque_handle()) {
1,834✔
67
      const auto& handle = std::get<Opaque_Session_Handle>(m_handle);
680✔
68
      if(handle.size() <= 32) {
680✔
69
         return Session_ID(handle.get());
27✔
70
      }
71
   }
72

73
   return std::nullopt;
1,807✔
74
}
75

76
std::optional<Session_Ticket> Session_Handle::ticket() const {
1,769✔
77
   if(is_ticket()) {
1,769✔
78
      return std::get<Session_Ticket>(m_handle);
1,220✔
79
   }
80

81
   // Opaque handles can mimic 'normal' Session_Tickets at any time
82
   if(is_opaque_handle()) {
549✔
83
      return Session_Ticket(std::get<Opaque_Session_Handle>(m_handle).get());
210✔
84
   }
85

86
   return std::nullopt;
339✔
87
}
88

89
Ciphersuite Session_Base::ciphersuite() const {
4,908✔
90
   auto suite = Ciphersuite::by_id(m_ciphersuite);
4,908✔
91
   if(!suite.has_value()) {
4,908✔
92
      throw Decoding_Error("Failed to find cipher suite for ID " + std::to_string(m_ciphersuite));
×
93
   }
94
   return suite.value();
4,908✔
95
}
96

97
Session_Summary::Session_Summary(const Session_Base& base,
1,785✔
98
                                 bool was_resumption,
99
                                 std::optional<std::string> psk_identity) :
1,785✔
100
      Session_Base(base), m_external_psk_identity(std::move(psk_identity)), m_was_resumption(was_resumption) {
1,906✔
101
   BOTAN_ARG_CHECK(version().is_pre_tls_13(), "Instantiated a TLS 1.2 session summary with an newer TLS version");
1,785✔
102

103
   const auto cs = ciphersuite();
1,785✔
104
   m_kex_algo = cs.kex_algo();
1,785✔
105
}
1,785✔
106

107
#if defined(BOTAN_HAS_TLS_13)
108

109
namespace {
110

111
std::string tls13_kex_to_string(bool psk, std::optional<Named_Group> group) {
610✔
112
   if(psk && group) {
610✔
113
      if(group->is_dh_named_group()) {
159✔
114
         return kex_method_to_string(Kex_Algo::DHE_PSK);
×
115
      } else if(group->is_ecdh_named_curve() || group->is_x25519() || group->is_x448()) {
159✔
116
         return kex_method_to_string(Kex_Algo::ECDHE_PSK);
157✔
117
      } else if(group->is_pure_ml_kem() || group->is_pure_frodokem()) {
2✔
118
         return kex_method_to_string(Kex_Algo::KEM_PSK);
×
119
      } else if(group->is_pqc_hybrid()) {
2✔
120
         return kex_method_to_string(Kex_Algo::HYBRID_PSK);
2✔
121
      } else if(auto s = group->to_string()) {
×
122
         return *s;
×
123
      }
×
124
   } else if(psk) {
451✔
125
      return kex_method_to_string(Kex_Algo::PSK);
×
126
   } else {
127
      BOTAN_ASSERT_NOMSG(group.has_value());
451✔
128
      if(group->is_dh_named_group()) {
451✔
129
         return kex_method_to_string(Kex_Algo::DH);
×
130
      } else if(group->is_ecdh_named_curve() || group->is_x25519() || group->is_x448()) {
451✔
131
         return kex_method_to_string(Kex_Algo::ECDH);
419✔
132
      } else if(group->is_pure_ml_kem() || group->is_pure_frodokem()) {
32✔
133
         return kex_method_to_string(Kex_Algo::KEM);
2✔
134
      } else if(group->is_pqc_hybrid()) {
30✔
135
         return kex_method_to_string(Kex_Algo::HYBRID);
30✔
136
      } else if(auto s = group->to_string()) {
×
137
         return *s;
×
138
      }
×
139
   }
140

141
   return kex_method_to_string(Kex_Algo::UNDEFINED);
×
142
}
143

144
}  // namespace
145

146
Session_Summary::Session_Summary(const Server_Hello_13& server_hello,
610✔
147
                                 Connection_Side side,
148
                                 std::vector<X509_Certificate> peer_certs,
149
                                 std::shared_ptr<const Public_Key> peer_raw_public_key,
150
                                 std::optional<std::string> psk_identity,
151
                                 bool session_was_resumed,
152
                                 Server_Information server_info,
153
                                 std::chrono::system_clock::time_point current_timestamp) :
610✔
154
      Session_Base(current_timestamp,
155
                   server_hello.selected_version(),
156
                   server_hello.ciphersuite(),
610✔
157
                   side,
158

159
                   // TODO: SRTP might become necessary when DTLS 1.3 is being implemented
160
                   0,
161

162
                   // RFC 8446 Appendix D
163
                   //    Because TLS 1.3 always hashes in the transcript up to the server
164
                   //    Finished, implementations which support both TLS 1.3 and earlier
165
                   //    versions SHOULD indicate the use of the Extended Master Secret
166
                   //    extension in their APIs whenever TLS 1.3 is used.
167
                   true,
168

169
                   // TLS 1.3 uses AEADs, so technically encrypt-then-MAC is not applicable.
170
                   false,
171
                   std::move(peer_certs),
172
                   std::move(peer_raw_public_key),
173
                   std::move(server_info)),
174
      m_external_psk_identity(std::move(psk_identity)),
610✔
175
      m_was_resumption(session_was_resumed) {
1,834✔
176
   BOTAN_ARG_CHECK(version().is_tls_13_or_later(), "Instantiated a TLS 1.3 session summary with an older TLS version");
610✔
177
   set_session_id(server_hello.session_id());
1,220✔
178

179
   // In TLS 1.3 the key exchange algorithm is not negotiated in the ciphersuite
180
   // anymore. This provides a compatible identifier for applications to use.
181

182
   std::optional<Named_Group> group = [&]() -> std::optional<Named_Group> {
1,830✔
183
      if(psk_used() || was_resumption()) {
610✔
184
         if(auto* const keyshare = server_hello.extensions().get<Key_Share>()) {
159✔
185
            return keyshare->selected_group();
159✔
186
         } else {
187
            return {};
×
188
         }
189
      } else {
190
         auto* const keyshare = server_hello.extensions().get<Key_Share>();
451✔
191
         BOTAN_ASSERT_NONNULL(keyshare);
451✔
192
         return keyshare->selected_group();
451✔
193
      }
194
   }();
610✔
195

196
   if(group.has_value()) {
610✔
197
      m_kex_parameters = group->to_string();
1,220✔
198
   }
199

200
   m_kex_algo = tls13_kex_to_string(psk_used() || was_resumption(), group);
610✔
201
}
610✔
202

203
#endif
204

205
Session::Session(const secure_vector<uint8_t>& master_secret,
1,668✔
206
                 Protocol_Version version,
207
                 uint16_t ciphersuite,
208
                 Connection_Side side,
209
                 bool extended_master_secret,
210
                 bool encrypt_then_mac,
211
                 const std::vector<X509_Certificate>& certs,
212
                 const Server_Information& server_info,
213
                 uint16_t srtp_profile,
214
                 std::chrono::system_clock::time_point current_timestamp,
215
                 std::chrono::seconds lifetime_hint) :
1,668✔
216
      Session_Base(current_timestamp,
217
                   version,
218
                   ciphersuite,
219
                   side,
220
                   srtp_profile,
221
                   extended_master_secret,
222
                   encrypt_then_mac,
223
                   certs,
224
                   nullptr,  // RFC 7250 (raw public keys) is NYI for TLS 1.2
225
                   server_info),
226
      m_master_secret(master_secret),
1,668✔
227
      m_early_data_allowed(false),
1,668✔
228
      m_max_early_data_bytes(0),
1,668✔
229
      m_ticket_age_add(0),
1,668✔
230
      m_lifetime_hint(lifetime_hint) {
3,336✔
231
   BOTAN_ARG_CHECK(version.is_pre_tls_13(), "Instantiated a TLS 1.2 session object with a TLS version newer than 1.2");
1,668✔
232
}
1,668✔
233

234
#if defined(BOTAN_HAS_TLS_13)
235

236
Session::Session(const secure_vector<uint8_t>& session_psk,
578✔
237
                 const std::optional<uint32_t>& max_early_data_bytes,
238
                 uint32_t ticket_age_add,
239
                 std::chrono::seconds lifetime_hint,
240
                 Protocol_Version version,
241
                 uint16_t ciphersuite,
242
                 Connection_Side side,
243
                 const std::vector<X509_Certificate>& peer_certs,
244
                 std::shared_ptr<const Public_Key> peer_raw_public_key,
245
                 const Server_Information& server_info,
246
                 std::chrono::system_clock::time_point current_timestamp) :
578✔
247
      Session_Base(current_timestamp,
248
                   version,
249
                   ciphersuite,
250
                   side,
251

252
                   // TODO: SRTP might become necessary when DTLS 1.3 is being implemented
253
                   0,
254

255
                   // RFC 8446 Appendix D
256
                   //    Because TLS 1.3 always hashes in the transcript up to the server
257
                   //    Finished, implementations which support both TLS 1.3 and earlier
258
                   //    versions SHOULD indicate the use of the Extended Master Secret
259
                   //    extension in their APIs whenever TLS 1.3 is used.
260
                   true,
261

262
                   // TLS 1.3 uses AEADs, so technically encrypt-then-MAC is not applicable.
263
                   false,
264
                   peer_certs,
265
                   std::move(peer_raw_public_key),
266
                   server_info),
267
      m_master_secret(session_psk),
578✔
268
      m_early_data_allowed(max_early_data_bytes.has_value()),
578✔
269
      m_max_early_data_bytes(max_early_data_bytes.value_or(0)),
578✔
270
      m_ticket_age_add(ticket_age_add),
578✔
271
      m_lifetime_hint(lifetime_hint) {
1,156✔
272
   BOTAN_ARG_CHECK(!version.is_pre_tls_13(), "Instantiated a TLS 1.3 session object with a TLS version older than 1.3");
578✔
273
}
578✔
274

275
Session::Session(secure_vector<uint8_t>&& session_psk,
284✔
276
                 const std::optional<uint32_t>& max_early_data_bytes,
277
                 std::chrono::seconds lifetime_hint,
278
                 const std::vector<X509_Certificate>& peer_certs,
279
                 std::shared_ptr<const Public_Key> peer_raw_public_key,
280
                 const Client_Hello_13& client_hello,
281
                 const Server_Hello_13& server_hello,
282
                 Callbacks& callbacks,
283
                 RandomNumberGenerator& rng) :
284✔
284
      Session_Base(callbacks.tls_current_timestamp(),
284✔
285
                   server_hello.selected_version(),
286
                   server_hello.ciphersuite(),
284✔
287
                   Connection_Side::Server,
288
                   0,
289
                   true,
290
                   false,  // see constructor above for rationales
291
                   peer_certs,
292
                   std::move(peer_raw_public_key),
293
                   Server_Information(client_hello.sni_hostname())),
568✔
294
      m_master_secret(std::move(session_psk)),
284✔
295
      m_early_data_allowed(max_early_data_bytes.has_value()),
284✔
296
      m_max_early_data_bytes(max_early_data_bytes.value_or(0)),
284✔
297
      m_ticket_age_add(load_be<uint32_t>(rng.random_vec(4).data(), 0)),
284✔
298
      m_lifetime_hint(lifetime_hint) {
852✔
299
   BOTAN_ARG_CHECK(!m_version.is_pre_tls_13(),
284✔
300
                   "Instantiated a TLS 1.3 session object with a TLS version older than 1.3");
301
}
284✔
302

303
#endif
304

305
Session::Session(std::string_view pem) : Session(PEM_Code::decode_check_label(pem, "TLS SESSION")) {}
3✔
306

307
Session::Session(std::span<const uint8_t> ber_data) /* NOLINT(*-member-init) */ {
452✔
308
   uint8_t side_code = 0;
452✔
309

310
   std::vector<uint8_t> raw_pubkey_or_empty;
452✔
311

312
   ASN1_String server_hostname;
452✔
313
   ASN1_String server_service;
453✔
314
   size_t server_port = 0;
452✔
315

316
   uint8_t major_version = 0;
452✔
317
   uint8_t minor_version = 0;
452✔
318

319
   size_t start_time = 0;
452✔
320
   size_t srtp_profile = 0;
452✔
321
   uint16_t ciphersuite_code = 0;
452✔
322
   uint64_t lifetime_hint = 0;
452✔
323

324
   BER_Decoder(ber_data.data(), ber_data.size())
904✔
325
      .start_sequence()
452✔
326
      .decode_and_check(TLS_SESSION_PARAM_STRUCT_VERSION, "Unknown version in serialized TLS session")
904✔
327
      .decode_integer_type(start_time)
452✔
328
      .decode_integer_type(major_version)
452✔
329
      .decode_integer_type(minor_version)
452✔
330
      .decode_integer_type(ciphersuite_code)
452✔
331
      .decode_integer_type(side_code)
452✔
332
      .decode(m_extended_master_secret)
452✔
333
      .decode(m_encrypt_then_mac)
452✔
334
      .decode(m_master_secret, ASN1_Type::OctetString)
452✔
335
      .decode_list<X509_Certificate>(m_peer_certs)
452✔
336
      .decode(raw_pubkey_or_empty, ASN1_Type::OctetString)
452✔
337
      .decode(server_hostname)
452✔
338
      .decode(server_service)
452✔
339
      .decode(server_port)
452✔
340
      .decode(srtp_profile)
452✔
341
      .decode(m_early_data_allowed)
452✔
342
      .decode_integer_type(m_max_early_data_bytes)
452✔
343
      .decode_integer_type(m_ticket_age_add)
452✔
344
      .decode_integer_type(lifetime_hint)
452✔
345
      .end_cons()
452✔
346
      .verify_end();
452✔
347

348
   if(!Ciphersuite::by_id(ciphersuite_code)) {
452✔
349
      throw Decoding_Error(
1✔
350
         "Serialized TLS session contains unknown cipher suite "
351
         "(" +
2✔
352
         std::to_string(ciphersuite_code) + ")");
4✔
353
   }
354

355
   m_ciphersuite = ciphersuite_code;
451✔
356
   m_version = Protocol_Version(major_version, minor_version);
451✔
357
   m_start_time = std::chrono::system_clock::from_time_t(start_time);
451✔
358
   m_connection_side = static_cast<Connection_Side>(side_code);
451✔
359
   m_srtp_profile = static_cast<uint16_t>(srtp_profile);
451✔
360

361
   m_server_info =
451✔
362
      Server_Information(server_hostname.value(), server_service.value(), static_cast<uint16_t>(server_port));
902✔
363

364
   if(!raw_pubkey_or_empty.empty()) {
451✔
365
      m_peer_raw_public_key = X509::load_key(raw_pubkey_or_empty);
1✔
366
   }
367

368
   m_lifetime_hint = std::chrono::seconds(lifetime_hint);
451✔
369
}
906✔
370

371
secure_vector<uint8_t> Session::DER_encode() const {
1,156✔
372
   const auto raw_pubkey_or_empty =
1,156✔
373
      m_peer_raw_public_key ? m_peer_raw_public_key->subject_public_key() : std::vector<uint8_t>{};
1,156✔
374

375
   return DER_Encoder()
1,156✔
376
      .start_sequence()
1,156✔
377
      .encode(TLS_SESSION_PARAM_STRUCT_VERSION)
1,156✔
378
      .encode(static_cast<size_t>(std::chrono::system_clock::to_time_t(m_start_time)))
1,156✔
379
      .encode(static_cast<size_t>(m_version.major_version()))
1,156✔
380
      .encode(static_cast<size_t>(m_version.minor_version()))
1,156✔
381
      .encode(static_cast<size_t>(m_ciphersuite))
1,156✔
382
      .encode(static_cast<size_t>(m_connection_side))
1,156✔
383
      .encode(m_extended_master_secret)
1,156✔
384
      .encode(m_encrypt_then_mac)
1,156✔
385
      .encode(m_master_secret, ASN1_Type::OctetString)
1,156✔
386
      .start_sequence()
1,576✔
387
      .encode_list(m_peer_certs)
1,156✔
388
      .end_cons()
1,156✔
389
      .encode(raw_pubkey_or_empty, ASN1_Type::OctetString)
1,156✔
390
      .encode(ASN1_String(m_server_info.hostname(), ASN1_Type::Utf8String))
3,468✔
391
      .encode(ASN1_String(m_server_info.service(), ASN1_Type::Utf8String))
3,468✔
392
      .encode(static_cast<size_t>(m_server_info.port()))
1,156✔
393
      .encode(static_cast<size_t>(m_srtp_profile))
1,156✔
394

395
      // the fields below were introduced for TLS 1.3 session tickets
396
      .encode(m_early_data_allowed)
1,156✔
397
      .encode(static_cast<size_t>(m_max_early_data_bytes))
1,156✔
398
      .encode(static_cast<size_t>(m_ticket_age_add))
1,156✔
399
      .encode(static_cast<size_t>(m_lifetime_hint.count()))
1,156✔
400
      .end_cons()
1,156✔
401
      .get_contents();
2,312✔
402
}
1,156✔
403

404
std::string Session::PEM_encode() const {
2✔
405
   return PEM_Code::encode(this->DER_encode(), "TLS SESSION");
6✔
406
}
407

408
secure_vector<uint8_t> Session::extract_master_secret() {
171✔
409
   BOTAN_STATE_CHECK(!m_master_secret.empty());
171✔
410
   return std::exchange(m_master_secret, {});
171✔
411
}
412

413
namespace {
414

415
// The output length of the HMAC must be a valid keylength for the AEAD
416
const char* const TLS_SESSION_CRYPT_HMAC = "HMAC(SHA-512-256)";
417
// SIV would be better, but we can't assume it is available
418
const char* const TLS_SESSION_CRYPT_AEAD = "AES-256/GCM";
419
const char* const TLS_SESSION_CRYPT_KEY_NAME = "BOTAN TLS SESSION KEY NAME";
420
const uint64_t TLS_SESSION_CRYPT_MAGIC = 0x068B5A9D396C0000;
421
const size_t TLS_SESSION_CRYPT_MAGIC_LEN = 8;
422
const size_t TLS_SESSION_CRYPT_KEY_NAME_LEN = 4;
423
const size_t TLS_SESSION_CRYPT_AEAD_NONCE_LEN = 12;
424
const size_t TLS_SESSION_CRYPT_AEAD_KEY_SEED_LEN = 16;
425
const size_t TLS_SESSION_CRYPT_AEAD_TAG_SIZE = 16;
426

427
const size_t TLS_SESSION_CRYPT_HDR_LEN = TLS_SESSION_CRYPT_MAGIC_LEN + TLS_SESSION_CRYPT_KEY_NAME_LEN +
428
                                         TLS_SESSION_CRYPT_AEAD_NONCE_LEN + TLS_SESSION_CRYPT_AEAD_KEY_SEED_LEN;
429

430
const size_t TLS_SESSION_CRYPT_OVERHEAD = TLS_SESSION_CRYPT_HDR_LEN + TLS_SESSION_CRYPT_AEAD_TAG_SIZE;
431

432
}  // namespace
433

434
std::vector<uint8_t> Session::encrypt(const SymmetricKey& key, RandomNumberGenerator& rng) const {
1,148✔
435
   auto hmac = MessageAuthenticationCode::create_or_throw(TLS_SESSION_CRYPT_HMAC);
1,148✔
436
   hmac->set_key(key);
1,148✔
437

438
   // First derive the "key name"
439
   std::vector<uint8_t> key_name(hmac->output_length());
1,148✔
440
   hmac->update(TLS_SESSION_CRYPT_KEY_NAME);
1,148✔
441
   hmac->final(key_name.data());
1,148✔
442
   key_name.resize(TLS_SESSION_CRYPT_KEY_NAME_LEN);
1,148✔
443

444
   std::vector<uint8_t> aead_nonce;
1,148✔
445
   std::vector<uint8_t> key_seed;
1,148✔
446

447
   rng.random_vec(aead_nonce, TLS_SESSION_CRYPT_AEAD_NONCE_LEN);
1,148✔
448
   rng.random_vec(key_seed, TLS_SESSION_CRYPT_AEAD_KEY_SEED_LEN);
1,148✔
449

450
   hmac->update(key_seed);
1,148✔
451
   const secure_vector<uint8_t> aead_key = hmac->final();
1,148✔
452

453
   secure_vector<uint8_t> bits = this->DER_encode();
1,148✔
454

455
   // create the header
456
   std::vector<uint8_t> buf;
1,148✔
457
   buf.reserve(TLS_SESSION_CRYPT_OVERHEAD + bits.size());
1,148✔
458
   buf.resize(TLS_SESSION_CRYPT_MAGIC_LEN);
1,148✔
459
   store_be(TLS_SESSION_CRYPT_MAGIC, &buf[0]);  // NOLINT(*container-data-pointer)
1,148✔
460
   buf += key_name;
1,148✔
461
   buf += key_seed;
1,148✔
462
   buf += aead_nonce;
1,148✔
463

464
   auto aead = AEAD_Mode::create_or_throw(TLS_SESSION_CRYPT_AEAD, Cipher_Dir::Encryption);
1,148✔
465
   BOTAN_ASSERT_NOMSG(aead->valid_nonce_length(TLS_SESSION_CRYPT_AEAD_NONCE_LEN));
1,148✔
466
   BOTAN_ASSERT_NOMSG(aead->tag_size() == TLS_SESSION_CRYPT_AEAD_TAG_SIZE);
1,148✔
467
   aead->set_key(aead_key);
1,148✔
468
   aead->set_associated_data(buf);
1,148✔
469
   aead->start(aead_nonce);
1,148✔
470
   aead->finish(bits, 0);
1,148✔
471

472
   // append the ciphertext
473
   buf += bits;
1,148✔
474
   return buf;
1,148✔
475
}
4,592✔
476

477
Session Session::decrypt(std::span<const uint8_t> in, const SymmetricKey& key) {
453✔
478
   try {
453✔
479
      const size_t min_session_size = 48 + 4;  // serious under-estimate
453✔
480
      if(in.size() < TLS_SESSION_CRYPT_OVERHEAD + min_session_size) {
453✔
481
         throw Decoding_Error("Encrypted session too short to be valid");
3✔
482
      }
483

484
      BufferSlicer sub(in);
450✔
485
      const auto* const magic = sub.take(TLS_SESSION_CRYPT_MAGIC_LEN).data();
450✔
486
      const auto* const key_name = sub.take(TLS_SESSION_CRYPT_KEY_NAME_LEN).data();
450✔
487
      const auto* const key_seed = sub.take(TLS_SESSION_CRYPT_AEAD_KEY_SEED_LEN).data();
450✔
488
      const auto* const aead_nonce = sub.take(TLS_SESSION_CRYPT_AEAD_NONCE_LEN).data();
450✔
489
      auto ctext = sub.copy_as_secure_vector(sub.remaining());
450✔
490

491
      if(load_be<uint64_t>(magic, 0) != TLS_SESSION_CRYPT_MAGIC) {
450✔
492
         throw Decoding_Error("Missing expected magic numbers");
×
493
      }
494

495
      auto hmac = MessageAuthenticationCode::create_or_throw(TLS_SESSION_CRYPT_HMAC);
454✔
496
      hmac->set_key(key);
450✔
497

498
      // First derive and check the "key name"
499
      std::vector<uint8_t> cmp_key_name(hmac->output_length());
454✔
500
      hmac->update(TLS_SESSION_CRYPT_KEY_NAME);
450✔
501
      hmac->final(cmp_key_name.data());
450✔
502

503
      if(CT::is_equal(cmp_key_name.data(), key_name, TLS_SESSION_CRYPT_KEY_NAME_LEN).as_bool() == false) {
450✔
504
         throw Decoding_Error("Wrong key name for encrypted session");
1✔
505
      }
506

507
      hmac->update(key_seed, TLS_SESSION_CRYPT_AEAD_KEY_SEED_LEN);
449✔
508
      const secure_vector<uint8_t> aead_key = hmac->final();
449✔
509

510
      auto aead = AEAD_Mode::create_or_throw(TLS_SESSION_CRYPT_AEAD, Cipher_Dir::Decryption);
452✔
511
      aead->set_key(aead_key);
449✔
512
      aead->set_associated_data(in.data(), TLS_SESSION_CRYPT_HDR_LEN);
449✔
513
      aead->start(aead_nonce, TLS_SESSION_CRYPT_AEAD_NONCE_LEN);
449✔
514
      aead->finish(ctext, 0);
449✔
515
      return Session(ctext);
449✔
516
   } catch(std::exception& e) {
1,802✔
517
      throw Decoding_Error("Failed to decrypt serialized TLS session: " + std::string(e.what()));
21✔
518
   }
7✔
519
}
520

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

© 2026 Coveralls, Inc