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

randombit / botan / 21749304465

06 Feb 2026 11:41AM UTC coverage: 90.073% (-1.6%) from 91.639%
21749304465

push

github

web-flow
Merge pull request #5287 from randombit/jack/buffer-slicer-h

Split out BufferSlicer and BufferStuffer to their own headers

102238 of 113506 relevant lines covered (90.07%)

11559538.43 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/buffer_slicer.h>
20
#include <botan/internal/ct_utils.h>
21
#include <botan/internal/loadstor.h>
22
#include <botan/internal/stl_util.h>
23

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

28
#include <utility>
29

30
namespace Botan::TLS {
31

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

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

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

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

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

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

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

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

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

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

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

108
#if defined(BOTAN_HAS_TLS_13)
109

110
namespace {
111

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

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

145
}  // namespace
146

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

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

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

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

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

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

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

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

204
#endif
205

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

235
#if defined(BOTAN_HAS_TLS_13)
236

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

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

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

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

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

304
#endif
305

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

414
namespace {
415

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

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

431
const size_t TLS_SESSION_CRYPT_OVERHEAD = TLS_SESSION_CRYPT_HDR_LEN + TLS_SESSION_CRYPT_AEAD_TAG_SIZE;
432

433
}  // namespace
434

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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