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

randombit / botan / 15426630667

03 Jun 2025 07:58PM CUT coverage: 90.963% (-0.005%) from 90.968%
15426630667

Pull #4898

github

web-flow
Merge 76843e0e3 into 9ad273be6
Pull Request #4898: MARVIN test utility improvements

98235 of 107995 relevant lines covered (90.96%)

12467633.66 hits per line

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

97.83
/src/lib/tls/tls_session.h
1
/*
2
* TLS Session
3
* (C) 2011-2012,2015 Jack Lloyd
4
* (C) 2022 René Meusel - Rohde & Schwarz Cybersecurity
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#ifndef BOTAN_TLS_SESSION_STATE_H_
10
#define BOTAN_TLS_SESSION_STATE_H_
11

12
#include <botan/secmem.h>
13
#include <botan/strong_type.h>
14
#include <botan/symkey.h>
15
#include <botan/tls_ciphersuite.h>
16
#include <botan/tls_magic.h>
17
#include <botan/tls_server_info.h>
18
#include <botan/tls_version.h>
19
#include <botan/x509cert.h>
20

21
#include <chrono>
22
#include <span>
23
#include <variant>
24

25
namespace Botan::TLS {
26

27
// Different flavors of session handles are used, depending on the usage
28
// scenario and the TLS protocol version.
29

30
/// @brief holds a TLS 1.2 session ID for stateful resumption
31
using Session_ID = Strong<std::vector<uint8_t>, struct Session_ID_>;
32

33
/// @brief holds a TLS 1.2 session ticket for stateless resumption
34
using Session_Ticket = Strong<std::vector<uint8_t>, struct Session_Ticket_>;
35

36
/// @brief holds an opaque session handle as used in TLS 1.3 that could be
37
///        either a ticket for stateless resumption or a database handle.
38
using Opaque_Session_Handle = Strong<std::vector<uint8_t>, struct Opaque_Session_Handle_>;
39

40
inline auto operator<(const Session_ID& id1, const Session_ID& id2) {
2,012✔
41
   // TODO: C++20 better use std::lexicographical_compare_three_way
42
   //       that was not available on all target platforms at the time
43
   //       of this writing.
44
   return std::lexicographical_compare(id1.begin(), id1.end(), id2.begin(), id2.end());
1,995✔
45
}
46

47
/**
48
 * @brief Helper class to embody a session handle in all protocol versions
49
 *
50
 * Sessions in TLS 1.2 are identified by an arbitrary and unique ID of up to
51
 * 32 bytes or by a self-contained arbitrary-length ticket (RFC 5077).
52
 *
53
 * TLS 1.3 does not distinct between the two and handles both as tickets. Also
54
 * a TLS 1.3 server can issue multiple tickets in one connection and the
55
 * resumption mechanism is compatible with the PSK establishment.
56
 *
57
 * Concrete implementations of Session_Manager use this helper to distinguish
58
 * the different states and manage sessions for TLS 1.2 and 1.3 connections.
59
 *
60
 * Note that all information stored in a Session_Handle might be transmitted in
61
 * unprotected form. Hence, it should not contain any confidential information.
62
 */
63
class BOTAN_PUBLIC_API(3, 0) Session_Handle {
16,429✔
64
   public:
65
      /**
66
       * Constructs a Session_Handle from a session ID which is an
67
       * arbitrary byte vector that must be 32 bytes long at most.
68
       */
69
      Session_Handle(Session_ID id) : m_handle(std::move(id)) { validate_constraints(); }
693✔
70

71
      /**
72
       * Constructs a Session_Handle from a session ticket which is a
73
       * non-empty byte vector that must be 64kB long at most.
74
       * Typically, tickets facilitate stateless server implementations
75
       * and contain all relevant context in encrypted/authenticated form.
76
       *
77
       * Note that (for technical reasons) we enforce that tickets are
78
       * longer than 32 bytes.
79
       */
80
      Session_Handle(Session_Ticket ticket) : m_handle(std::move(ticket)) { validate_constraints(); }
2,167✔
81

82
      /**
83
       * Constructs a Session_Handle from an Opaque_Handle such as TLS 1.3
84
       * uses them in its resumption mechanism. This could be either a
85
       * Session_ID or a Session_Ticket and it is up to the Session_Manager
86
       * to figure out what it actually is.
87
       */
88
      Session_Handle(Opaque_Session_Handle ticket) : m_handle(std::move(ticket)) { validate_constraints(); }
689✔
89

90
      bool is_id() const { return std::holds_alternative<Session_ID>(m_handle); }
2,845✔
91

92
      bool is_ticket() const { return std::holds_alternative<Session_Ticket>(m_handle); }
3,866✔
93

94
      bool is_opaque_handle() const { return std::holds_alternative<Opaque_Session_Handle>(m_handle); }
2,385✔
95

96
      /**
97
       * Returns the Session_Handle as an opaque handle. If the object was not
98
       * constructed as an Opaque_Session_Handle, the contained value is
99
       * converted.
100
       */
101
      Opaque_Session_Handle opaque_handle() const;
102

103
      /**
104
       * If the Session_Handle was constructed with a Session_ID or an
105
       * Opaque_Session_Handle that can be converted to a Session_ID (up to
106
       * 32 bytes long), this returns the handle as a Session_ID. Otherwise,
107
       * std::nullopt is returned.
108
       */
109
      std::optional<Session_ID> id() const;
110

111
      /**
112
       * If the Session_Handle was constructed with a Session_Ticket or an
113
       * Opaque_Session_Handle this returns the handle as a Session_ID.
114
       * Otherwise, std::nullopt is returned.
115
       */
116
      std::optional<Session_Ticket> ticket() const;
117

118
      decltype(auto) get() const { return m_handle; }
574✔
119

120
   private:
121
      void validate_constraints() const;
122

123
   private:
124
      std::variant<Session_ID, Session_Ticket, Opaque_Session_Handle> m_handle;
125
};
126

127
class Client_Hello_13;
128
class Server_Hello_13;
129
class Callbacks;
130

131
/**
132
 * Represents basic information about a session that can be both
133
 * persisted for resumption and presented to the application as
134
 * a summary of a specific just-established TLS session.
135
 */
136
class BOTAN_PUBLIC_API(3, 0) Session_Base {
137
   public:
138
      Session_Base(std::chrono::system_clock::time_point start_time,
3,133✔
139
                   Protocol_Version version,
140
                   uint16_t ciphersuite,
141
                   Connection_Side connection_side,
142
                   uint16_t srtp_profile,
143
                   bool extended_master_secret,
144
                   bool encrypt_then_mac,
145
                   std::vector<X509_Certificate> peer_certs,
146
                   std::shared_ptr<const Public_Key> peer_raw_public_key,
147
                   Server_Information server_info) :
3,133✔
148
            m_start_time(start_time),
3,133✔
149
            m_version(version),
3,133✔
150
            m_ciphersuite(ciphersuite),
3,133✔
151
            m_connection_side(connection_side),
3,133✔
152
            m_srtp_profile(srtp_profile),
3,133✔
153
            m_extended_master_secret(extended_master_secret),
3,133✔
154
            m_encrypt_then_mac(encrypt_then_mac),
3,133✔
155
            m_peer_certs(std::move(peer_certs)),
3,133✔
156
            m_peer_raw_public_key(std::move(peer_raw_public_key)),
3,133✔
157
            m_server_info(std::move(server_info)) {}
3,133✔
158

159
   protected:
160
      Session_Base() = default;
451✔
161

162
   public:
163
      /**
164
       * Get the wall clock time this session began
165
       */
166
      std::chrono::system_clock::time_point start_time() const { return m_start_time; }
1,570✔
167

168
      /**
169
       * Get the negotiated protocol version of the TLS session
170
       */
171
      Protocol_Version version() const { return m_version; }
8,081✔
172

173
      /**
174
       * Get the ciphersuite code of the negotiated TLS session
175
       */
176
      uint16_t ciphersuite_code() const { return m_ciphersuite; }
687✔
177

178
      /**
179
       * Get the ciphersuite info of the negotiated TLS session
180
       */
181
      Ciphersuite ciphersuite() const;
182

183
      /**
184
       * Get which side of the connection we are/were acting as.
185
       */
186
      Connection_Side side() const { return m_connection_side; }
1,152✔
187

188
      /**
189
       * Get the negotiated DTLS-SRTP algorithm (RFC 5764)
190
       */
191
      uint16_t dtls_srtp_profile() const { return m_srtp_profile; }
192

193
      /**
194
       * Returns true if a TLS 1.2 session negotiated "encrypt then MAC";
195
       * TLS 1.3 sessions will always return false as they always use an AEAD.
196
       */
197
      bool supports_encrypt_then_mac() const { return m_encrypt_then_mac; }
441✔
198

199
      /**
200
       * Returns true if a TLS 1.2 session negotiated "extended master secret";
201
       * TLS 1.3 sessions will always return true (see RFC 8446 Appendix D).
202
       */
203
      bool supports_extended_master_secret() const { return m_extended_master_secret; }
2,472✔
204

205
      /**
206
       * Return the certificate chain of the peer (possibly empty)
207
       */
208
      const std::vector<X509_Certificate>& peer_certs() const { return m_peer_certs; }
808✔
209

210
      /**
211
       * Return the raw public key of the peer (possibly empty)
212
       */
213
      std::shared_ptr<const Public_Key> peer_raw_public_key() const { return m_peer_raw_public_key; }
379✔
214

215
      /**
216
       * Get information about the TLS server
217
       *
218
       * Returns information that identifies the server side of the connection.
219
       * This is useful for the client in that it identifies what was originally
220
       * passed to the constructor. For the server, it includes the name the
221
       * client specified in the server name indicator extension.
222
       */
223
      const Server_Information& server_info() const { return m_server_info; }
1,915✔
224

225
   protected:
226
      std::chrono::system_clock::time_point m_start_time;
227

228
      Protocol_Version m_version;
229
      uint16_t m_ciphersuite;
230
      Connection_Side m_connection_side;
231
      uint16_t m_srtp_profile;
232

233
      bool m_extended_master_secret;
234
      bool m_encrypt_then_mac;
235

236
      std::vector<X509_Certificate> m_peer_certs;
237
      std::shared_ptr<const Public_Key> m_peer_raw_public_key;
238
      Server_Information m_server_info;
239
};
240

241
/**
242
 * Summarizes the negotiated features after a TLS handshake. Applications may
243
 * query those in Callbacks::tls_session_established().
244
 */
245
class BOTAN_PUBLIC_API(3, 0) Session_Summary : public Session_Base {
246
   public:
247
      /**
248
       * The Session_ID negotiated during the handshake.
249
       * Note that this does not carry any meaning in TLS 1.3 and might even
250
       * be empty.
251
       */
252
      const Session_ID& session_id() const { return m_session_id; }
22✔
253

254
      /**
255
       * The session ticket a TLS 1.2 server issued for this session.
256
       * Note that this may be set in TLS 1.2 clients only. It is _not_ the
257
       * ticket used to establish this session.
258
       */
259
      const std::optional<Session_Ticket>& session_ticket() const { return m_session_ticket; }
18✔
260

261
      /**
262
       * The negotiated identity of an externally provided preshared key used to
263
       * establish this session. For TLS 1.3 this may be any of the externally
264
       * provided PSKs offered by the client. PSK identities used as session
265
       * tickets for TLS 1.3 session resumption won't be shown here.
266
       */
267
      const std::optional<std::string>& external_psk_identity() const { return m_external_psk_identity; }
20✔
268

269
      /**
270
       * Indicates that the session was established using an externally provided
271
       * PSK. Session resumptions in TLS 1.3 (while technically implemented
272
       * using a PSK) are not considered here. @sa was_resumption()
273
       *
274
       * @note Botan 3.0 and 3.1 did incorrectly report true for session resumption.
275
       *
276
       * @returns true if the session was established using an externally
277
       *          provided PSK.
278
       */
279
      bool psk_used() const { return m_external_psk_identity.has_value(); }
1,232✔
280

281
      /**
282
       * Indicates that the session was resumed from a previous handshake state.
283
       *
284
       * @returns true if this session is a resumption, otherwise false
285
       */
286
      bool was_resumption() const { return m_was_resumption; }
1,212✔
287

288
      std::string kex_algo() const { return m_kex_algo; }
289

290
      std::optional<std::string> kex_parameters() const { return m_kex_parameters; }
9✔
291

292
      std::string cipher_algo() const { return ciphersuite().cipher_algo(); }
293

294
      std::string mac_algo() const { return ciphersuite().mac_algo(); }
295

296
      std::string prf_algo() const { return ciphersuite().prf_algo(); }
297

298
   private:
299
      friend class Server_Impl_12;
300
      friend class Server_Impl_13;
301
      friend class Client_Impl_12;
302
      friend class Client_Impl_13;
303

304
      Session_Summary(const Session_Base& base, bool was_resumption, std::optional<std::string> psk_identity);
305

306
#if defined(BOTAN_HAS_TLS_13)
307
      Session_Summary(const Server_Hello_13& server_hello,
308
                      Connection_Side side,
309
                      std::vector<X509_Certificate> peer_certs,
310
                      std::shared_ptr<const Public_Key> peer_raw_public_key,
311
                      std::optional<std::string> psk_identity,
312
                      bool session_was_resumed,
313
                      Server_Information server_info,
314
                      std::chrono::system_clock::time_point current_timestamp);
315
#endif
316

317
      void set_session_id(Session_ID id) { m_session_id = std::move(id); }
2,389✔
318

319
      void set_session_ticket(Session_Ticket ticket) { m_session_ticket = std::move(ticket); }
800✔
320

321
   private:
322
      Session_ID m_session_id;
323
      std::optional<Session_Ticket> m_session_ticket;
324
      std::optional<std::string> m_external_psk_identity;
325

326
      bool m_was_resumption;
327
      std::string m_kex_algo;
328
      std::optional<std::string> m_kex_parameters;
329
};
330

331
/**
332
 * Represents a session's negotiated features along with all resumption
333
 * information to re-establish a TLS connection later on.
334
 */
335
class BOTAN_PUBLIC_API(3, 0) Session final : public Session_Base {
336
   public:
337
      /**
338
      * New TLS 1.2 session (sets session start time)
339
      */
340
      Session(const secure_vector<uint8_t>& master_secret,
341
              Protocol_Version version,
342
              uint16_t ciphersuite,
343
              Connection_Side side,
344
              bool supports_extended_master_secret,
345
              bool supports_encrypt_then_mac,
346
              const std::vector<X509_Certificate>& peer_certs,
347
              const Server_Information& server_info,
348
              uint16_t srtp_profile,
349
              std::chrono::system_clock::time_point current_timestamp,
350
              std::chrono::seconds lifetime_hint = std::chrono::seconds::max());
351

352
#if defined(BOTAN_HAS_TLS_13)
353

354
      /**
355
      * New TLS 1.3 session (sets session start time)
356
      */
357
      Session(const secure_vector<uint8_t>& session_psk,
358
              const std::optional<uint32_t>& max_early_data_bytes,
359
              uint32_t ticket_age_add,
360
              std::chrono::seconds lifetime_hint,
361
              Protocol_Version version,
362
              uint16_t ciphersuite,
363
              Connection_Side side,
364
              const std::vector<X509_Certificate>& peer_certs,
365
              std::shared_ptr<const Public_Key> peer_raw_public_key,
366
              const Server_Information& server_info,
367
              std::chrono::system_clock::time_point current_timestamp);
368

369
      /**
370
       * Create a new TLS 1.3 session object from server data structures
371
       * after a successful handshake with a TLS 1.3 client
372
       */
373
      Session(secure_vector<uint8_t>&& session_psk,
374
              const std::optional<uint32_t>& max_early_data_bytes,
375
              std::chrono::seconds lifetime_hint,
376
              const std::vector<X509_Certificate>& peer_certs,
377
              std::shared_ptr<const Public_Key> peer_raw_public_key,
378
              const Client_Hello_13& client_hello,
379
              const Server_Hello_13& server_hello,
380
              Callbacks& callbacks,
381
              RandomNumberGenerator& rng);
382

383
#endif
384

385
      /**
386
      * Load a session from DER representation (created by DER_encode)
387
      * @param ber_data DER representation buffer
388
      */
389
      Session(std::span<const uint8_t> ber_data);
390

391
      /**
392
      * Load a session from PEM representation (created by PEM_encode)
393
      * @param pem PEM representation
394
      */
395
      explicit Session(std::string_view pem);
396

397
      /**
398
      * Encode this session data for storage
399
      * @warning if the master secret is compromised so is the
400
      * session traffic
401
      */
402
      secure_vector<uint8_t> DER_encode() const;
403

404
      /**
405
      * Encrypt a session (useful for serialization or session tickets)
406
      */
407
      std::vector<uint8_t> encrypt(const SymmetricKey& key, RandomNumberGenerator& rng) const;
408

409
      /**
410
      * Decrypt a session created by encrypt
411
      * @param ctext the ciphertext returned by encrypt
412
      * @param ctext_size the size of ctext in bytes
413
      * @param key the same key used by the encrypting side
414
      */
415
      static inline Session decrypt(const uint8_t ctext[], size_t ctext_size, const SymmetricKey& key) {
129✔
416
         return Session::decrypt(std::span(ctext, ctext_size), key);
129✔
417
      }
418

419
      /**
420
      * Decrypt a session created by encrypt
421
      * @param ctext the ciphertext returned by encrypt
422
      * @param key the same key used by the encrypting side
423
      */
424
      static Session decrypt(std::span<const uint8_t> ctext, const SymmetricKey& key);
425

426
      /**
427
      * Encode this session data for storage
428
      * @warning if the master secret is compromised so is the
429
      * session traffic
430
      */
431
      std::string PEM_encode() const;
432

433
      /**
434
      * Get a reference to the contained master secret
435
      */
436
      const secure_vector<uint8_t>& master_secret() const { return m_master_secret; }
434✔
437

438
      /**
439
      * Get the contained master secret as a moved-out object
440
      */
441
      secure_vector<uint8_t> extract_master_secret();
442

443
      /**
444
       * Get whether the saved session supports sending/receiving of early data
445
       */
446
      bool supports_early_data() const { return m_early_data_allowed; }
447

448
      /**
449
      * Return the ticket obfuscation adder
450
      */
451
      uint32_t session_age_add() const { return m_ticket_age_add; }
354✔
452

453
      /**
454
      * Return the number of bytes allowed for 0-RTT early data
455
      */
456
      uint32_t max_early_data_bytes() const { return m_max_early_data_bytes; }
457

458
      /**
459
      * @return the lifetime of the ticket as defined by the TLS server
460
      */
461
      std::chrono::seconds lifetime_hint() const { return m_lifetime_hint; }
3,739✔
462

463
   private:
464
      // Struct Version history
465
      //
466
      // 20160812 - Pre TLS 1.3
467
      // 20220505 - Introduction of TLS 1.3 sessions
468
      //            - added fields:
469
      //              - m_early_data_allowed
470
      //              - m_max_early_data_bytes
471
      //              - m_ticket_age_add
472
      //              - m_lifetime_hint
473
      // 20230112 - Remove Session_ID and Session_Ticket from this object
474
      //            (association is now in the hands of the Session_Manager)
475
      //          - Peer certificates are now stored as a SEQUENCE
476
      // 20230222 - Remove deprecated and unused fields
477
      //            - compression method (always 0)
478
      //            - fragment size (always 0)
479
      //            - SRP identifier (always "")
480
      // 20231031 - Allow storage of peer's raw public key
481
      enum { TLS_SESSION_PARAM_STRUCT_VERSION = 20231031 };
482

483
      secure_vector<uint8_t> m_master_secret;
484

485
      bool m_early_data_allowed;
486
      uint32_t m_max_early_data_bytes;
487
      uint32_t m_ticket_age_add;
488
      std::chrono::seconds m_lifetime_hint;
489
};
490

491
/**
492
 * Helper struct to conveniently pass a Session and its Session_Handle around
493
 */
494
struct BOTAN_PUBLIC_API(3, 0) Session_with_Handle {
×
495
      Session session;
496
      Session_Handle handle;
497
};
498

499
}  // namespace Botan::TLS
500

501
#endif
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