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

randombit / botan / 21708961618

05 Feb 2026 11:02AM UTC coverage: 90.074% (+0.003%) from 90.071%
21708961618

push

github

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

Various header inclusion cleanups

102237 of 113503 relevant lines covered (90.07%)

11402808.84 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 <algorithm>
16

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

21
namespace Botan::TLS {
22

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

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

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

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

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

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

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

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

80
   if(expired) {
396✔
81
      remove(handle);
10✔
82
      return std::nullopt;
10✔
83
   } else {
84
      return session;
967✔
85
   }
86
}
581✔
87

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

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

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

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

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

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

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

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

154
         return expired;
851✔
155
      });
156
   }
157

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

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

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

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

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

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

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

204
#if defined(BOTAN_HAS_TLS_13)
205

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

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

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

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

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

239
#endif
240

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