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

randombit / botan / 21848380424

10 Feb 2026 01:47AM UTC coverage: 91.634% (+1.6%) from 90.069%
21848380424

push

github

web-flow
Merge pull request #5296 from randombit/jack/tls-header-patrol

Various changes to reduce header dependencies in TLS

104002 of 113497 relevant lines covered (91.63%)

11230277.53 hits per line

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

98.53
/src/lib/tls/tls_session_manager.cpp
1
/**
2
 * TLS Session Manger base class implementations
3
 * (C) 2011-2023 Jack Lloyd
4
 *     2022-2023 René Meusel - Rohde & Schwarz Cybersecurity
5
 *
6
 * Botan is released under the Simplified BSD License (see license.txt)
7
 */
8

9
#include <botan/tls_session_manager.h>
10

11
#include <botan/assert.h>
12
#include <botan/rng.h>
13
#include <botan/tls_callbacks.h>
14
#include <botan/tls_policy.h>
15
#include <botan/tls_session.h>
16
#include <algorithm>
17

18
#if defined(BOTAN_HAS_TLS_13)
19
   #include <botan/tls_psk_identity_13.h>
20
#endif
21

22
namespace Botan::TLS {
23

24
Session_Manager::Session_Manager(const std::shared_ptr<RandomNumberGenerator>& rng) : m_rng(rng) {
9,630✔
25
   BOTAN_ASSERT_NONNULL(m_rng);
9,630✔
26
}
9,630✔
27

28
std::optional<Session_Handle> Session_Manager::establish(const Session& session,
242✔
29
                                                         const std::optional<Session_ID>& id,
30
                                                         bool tls12_no_ticket) {
31
   // Establishing a session does not require locking at this level as
32
   // concurrent TLS instances on a server will create unique sessions.
33

34
   // By default, the session manager does not emit session tickets anyway
35
   BOTAN_UNUSED(tls12_no_ticket);
242✔
36
   BOTAN_ASSERT(session.side() == Connection_Side::Server, "Client tried to establish a session");
242✔
37

38
   Session_Handle handle(id.value_or(m_rng->random_vec<Session_ID>(32)));
726✔
39
   store(session, handle);
242✔
40
   return handle;
242✔
41
}
242✔
42

43
std::optional<Session> Session_Manager::retrieve(const Session_Handle& handle,
587✔
44
                                                 Callbacks& callbacks,
45
                                                 const Policy& policy) {
46
   // Retrieving a session for a given handle does not require locking on this
47
   // level. Concurrent threads might handle the removal of an expired ticket
48
   // more than once, but removing an already removed ticket is a harmless NOOP.
49

50
   auto session = retrieve_one(handle);
587✔
51
   if(!session.has_value()) {
587✔
52
      return std::nullopt;
185✔
53
   }
54

55
   // A value of '0' means: No policy restrictions.
56
   const std::chrono::seconds policy_lifetime =
402✔
57
      (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
402✔
58

59
   // RFC 5077 3.3 -- "Old Session Tickets"
60
   //    A server MAY treat a ticket as valid for a shorter or longer period of
61
   //    time than what is stated in the ticket_lifetime_hint.
62
   //
63
   // RFC 5246 F.1.4 -- TLS 1.2
64
   //    If either party suspects that the session may have been compromised, or
65
   //    that certificates may have expired or been revoked, it should force a
66
   //    full handshake.  An upper limit of 24 hours is suggested for session ID
67
   //    lifetimes.
68
   //
69
   // RFC 8446 4.6.1 -- TLS 1.3
70
   //    A server MAY treat a ticket as valid for a shorter period of time than
71
   //    what is stated in the ticket_lifetime.
72
   //
73
   // Note: This disregards what is stored in the session (e.g. "lifetime_hint")
74
   //       and only takes the local policy into account. The lifetime stored in
75
   //       the sessions was taken from the same policy anyways and changes by
76
   //       the application should have an immediate effect.
77
   const auto ticket_age =
402✔
78
      std::chrono::duration_cast<std::chrono::seconds>(callbacks.tls_current_timestamp() - session->start_time());
402✔
79
   const bool expired = ticket_age > policy_lifetime;
402✔
80

81
   if(expired) {
402✔
82
      remove(handle);
10✔
83
      return std::nullopt;
10✔
84
   } else {
85
      return session;
979✔
86
   }
87
}
587✔
88

89
std::vector<Session_with_Handle> Session_Manager::find_and_filter(const Server_Information& info,
3,655✔
90
                                                                  Callbacks& callbacks,
91
                                                                  const Policy& policy) {
92
   // A value of '0' means: No policy restrictions. Session ticket lifetimes as
93
   // communicated by the server apply regardless.
94
   const std::chrono::seconds policy_lifetime =
3,655✔
95
      (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
3,655✔
96

97
   const size_t max_sessions_hint = std::max(policy.maximum_session_tickets_per_client_hello(), size_t(1));
3,655✔
98
   const auto now = callbacks.tls_current_timestamp();
3,655✔
99

100
   // An arbitrary number of loop iterations to perform before giving up
101
   // to avoid a potential endless loop with a misbehaving session manager.
102
   constexpr unsigned int max_attempts = 10;
3,655✔
103
   std::vector<Session_with_Handle> sessions_and_handles;
3,655✔
104

105
   // Query the session manager implementation for new sessions until at least
106
   // one session passes the filter or no more sessions are found.
107
   for(unsigned int attempt = 0; attempt < max_attempts && sessions_and_handles.empty(); ++attempt) {
4,079✔
108
      sessions_and_handles = find_some(info, max_sessions_hint);
3,664✔
109

110
      // ... underlying implementation didn't find anything. Early exit.
111
      if(sessions_and_handles.empty()) {
3,664✔
112
         break;
113
      }
114

115
      std::erase_if(sessions_and_handles, [&](const auto& session) {
424✔
116
         const auto age = std::chrono::duration_cast<std::chrono::seconds>(now - session.session.start_time());
850✔
117

118
         // RFC 5077 3.3 -- "Old Session Tickets"
119
         //    The ticket_lifetime_hint field contains a hint from the
120
         //    server about how long the ticket should be stored. [...]
121
         //    A client SHOULD delete the ticket and associated state when
122
         //    the time expires. It MAY delete the ticket earlier based on
123
         //    local policy.
124
         //
125
         // RFC 5246 F.1.4 -- TLS 1.2
126
         //    If either party suspects that the session may have been
127
         //    compromised, or that certificates may have expired or been
128
         //    revoked, it should force a full handshake.  An upper limit of
129
         //    24 hours is suggested for session ID lifetimes.
130
         //
131
         // RFC 8446 4.2.11.1 -- TLS 1.3
132
         //    The client's view of the age of a ticket is the time since the
133
         //    receipt of the NewSessionTicket message.  Clients MUST NOT
134
         //    attempt to use tickets which have ages greater than the
135
         //    "ticket_lifetime" value which was provided with the ticket.
136
         //
137
         // RFC 8446 4.6.1 -- TLS 1.3
138
         //    Clients MUST NOT cache tickets for longer than 7 days,
139
         //    regardless of the ticket_lifetime, and MAY delete tickets
140
         //    earlier based on local policy.
141
         //
142
         // Note: TLS 1.3 tickets with a lifetime longer than 7 days are
143
         //       rejected during parsing with an "Illegal Parameter" alert.
144
         //       Other suggestions are left to the application via
145
         //       Policy::session_ticket_lifetime(). Session lifetimes as
146
         //       communicated by the server via the "lifetime_hint" are
147
         //       obeyed regardless of the policy setting.
148
         const auto session_lifetime_hint = session.session.lifetime_hint();
850✔
149
         const bool expired = age > std::min(policy_lifetime, session_lifetime_hint);
1,726✔
150

151
         if(expired) {
850✔
152
            remove(session.handle);
22✔
153
         }
154

155
         return expired;
850✔
156
      });
157
   }
158

159
   return sessions_and_handles;
3,655✔
160
}
×
161

162
std::vector<Session_with_Handle> Session_Manager::find(const Server_Information& info,
3,655✔
163
                                                       Callbacks& callbacks,
164
                                                       const Policy& policy) {
165
   auto allow_reusing_tickets = policy.reuse_session_tickets();
3,655✔
166

167
   // Session_Manager::find() must be an atomic getter if ticket reuse is not
168
   // allowed. I.e. each ticket handed to concurrently requesting threads must
169
   // be unique. In that case we must hold a lock while retrieving a ticket.
170
   // Otherwise, no locking is required on this level.
171
   std::optional<lock_guard_type<recursive_mutex_type>> lk;
3,655✔
172
   if(!allow_reusing_tickets) {
3,655✔
173
      lk.emplace(mutex());
3,632✔
174
   }
175

176
   auto sessions_and_handles = find_and_filter(info, callbacks, policy);
3,655✔
177

178
   // std::vector::resize() cannot be used as the vector's members aren't
179
   // default constructible.
180
   const auto session_limit = policy.maximum_session_tickets_per_client_hello();
3,655✔
181
   while(session_limit > 0 && sessions_and_handles.size() > session_limit) {
4,045✔
182
      sessions_and_handles.pop_back();
390✔
183
   }
184

185
   // RFC 8446 Appendix C.4
186
   //    Clients SHOULD NOT reuse a ticket for multiple connections. Reuse of
187
   //    a ticket allows passive observers to correlate different connections.
188
   //
189
   // When reuse of session tickets is not allowed, remove all tickets to be
190
   // returned from the implementation's internal storage.
191
   if(!allow_reusing_tickets) {
3,655✔
192
      // The lock must be held here, otherwise we cannot guarantee the
193
      // transactional retrieval of tickets to concurrently requesting clients.
194
      BOTAN_ASSERT_NOMSG(lk.has_value());
3,632✔
195
      for(const auto& [session, handle] : sessions_and_handles) {
4,034✔
196
         if(!session.version().is_pre_tls_13() || !handle.is_id()) {
402✔
197
            remove(handle);
265✔
198
         }
199
      }
200
   }
201

202
   return sessions_and_handles;
3,655✔
203
}
3,655✔
204

205
#if defined(BOTAN_HAS_TLS_13)
206

207
std::optional<std::pair<Session, uint16_t>> Session_Manager::choose_from_offered_tickets(
112✔
208
   const std::vector<PskIdentity>& tickets,
209
   std::string_view hash_function,
210
   Callbacks& callbacks,
211
   const Policy& policy) {
212
   // Note that the TLS server currently does not ensure that tickets aren't
213
   // reused. As a result, no locking is required on this level.
214

215
   for(uint16_t i = 0; const auto& ticket : tickets) {
132✔
216
      auto session = retrieve(Session_Handle(Opaque_Session_Handle(ticket.identity())), callbacks, policy);
246✔
217
      if(session.has_value() && session->ciphersuite().prf_algo() == hash_function &&
457✔
218
         session->version().is_tls_13_or_later()) {
228✔
219
         return std::pair{std::move(session.value()), i};
103✔
220
      }
221

222
      // RFC 8446 4.2.10
223
      //    For PSKs provisioned via NewSessionTicket, a server MUST validate
224
      //    that the ticket age for the selected PSK identity [...] is within a
225
      //    small tolerance of the time since the ticket was issued.  If it is
226
      //    not, the server SHOULD proceed with the handshake but reject 0-RTT,
227
      //    and SHOULD NOT take any other action that assumes that this
228
      //    ClientHello is fresh.
229
      //
230
      // TODO: The ticket-age is currently not checked (as 0-RTT is not
231
      //       implemented) and we simply take the SHOULD at face value.
232
      //       Instead we could add a policy check letting the user decide.
233

234
      ++i;
20✔
235
   }
123✔
236

237
   return std::nullopt;
9✔
238
}
239

240
#endif
241

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