Botan 3.14.1
Crypto and TLS for C&
tls_session_manager.cpp
Go to the documentation of this file.
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#include <chrono>
18
19#if defined(BOTAN_HAS_TLS_13)
20 #include <botan/tls_psk_identity_13.h>
21#endif
22
23namespace Botan::TLS {
24
25namespace {
26
27/*
28* A session whose start time lies in the future cannot be judged and is
29* considered expired. The age is rounded up so that a session is expired
30* as soon as its lifetime is exceeded by any fraction of a second.
31*/
32bool session_has_expired(std::chrono::system_clock::time_point now,
33 std::chrono::system_clock::time_point start_time,
34 std::chrono::seconds lifetime) {
35 if(now < start_time) {
36 return true;
37 }
38
39 return std::chrono::ceil<std::chrono::seconds>(now - start_time) > lifetime;
40}
41
42} // namespace
43
44Session_Manager::Session_Manager(const std::shared_ptr<RandomNumberGenerator>& rng) : m_rng(rng) {
46}
47
48std::optional<Session_Handle> Session_Manager::establish(const Session& session,
49 const std::optional<Session_ID>& id,
50 bool tls12_no_ticket) {
51 // Establishing a session does not require locking at this level as
52 // concurrent TLS instances on a server will create unique sessions.
53
54 // By default, the session manager does not emit session tickets anyway
55 BOTAN_UNUSED(tls12_no_ticket);
56 BOTAN_ASSERT(session.side() == Connection_Side::Server, "Client tried to establish a session");
57
58 Session_Handle handle(id.value_or(m_rng->random_vec<Session_ID>(32)));
59 store(session, handle);
60 return handle;
61}
62
63std::optional<Session> Session_Manager::retrieve(const Session_Handle& handle,
64 Callbacks& callbacks,
65 const Policy& policy) {
66 // Retrieving a session for a given handle does not require locking on this
67 // level. Concurrent threads might handle the removal of an expired ticket
68 // more than once, but removing an already removed ticket is a harmless NOOP.
69
70 auto session = retrieve_one(handle);
71 if(!session.has_value()) {
72 return std::nullopt;
73 }
74
75 // A session stored while acting as a TLS client must never be resumed in the
76 // server role. Its peer certificates are a remote *server's*, so accepting it
77 // here would present them as this connection's client certificates. The
78 // session is left in storage; it remains valid for the client role.
79 if(session->side() != Connection_Side::Server) {
80 return std::nullopt;
81 }
82
83 // A value of '0' means: No policy restrictions.
84 const std::chrono::seconds policy_lifetime =
85 (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
86
87 // RFC 5077 3.3 -- "Old Session Tickets"
88 // A server MAY treat a ticket as valid for a shorter or longer period of
89 // time than what is stated in the ticket_lifetime_hint.
90 //
91 // RFC 5246 F.1.4 -- TLS 1.2
92 // If either party suspects that the session may have been compromised, or
93 // that certificates may have expired or been revoked, it should force a
94 // full handshake. An upper limit of 24 hours is suggested for session ID
95 // lifetimes.
96 //
97 // RFC 8446 4.6.1 -- TLS 1.3
98 // A server MAY treat a ticket as valid for a shorter period of time than
99 // what is stated in the ticket_lifetime.
100 //
101 // Note: For TLS 1.2 this disregards what is stored in the session (e.g.
102 // "lifetime_hint") and only takes the local policy into account, so
103 // that changes by the application have an immediate effect. A TLS 1.3
104 // ticket additionally never outlives the ticket_lifetime it was
105 // issued with, which was sent to the client.
106 const auto lifetime =
107 session->version().is_pre_tls_13() ? policy_lifetime : std::min(policy_lifetime, session->lifetime_hint());
108 const bool expired = session_has_expired(callbacks.tls_current_timestamp(), session->start_time(), lifetime);
109
110 if(expired) {
111 remove(handle);
112 return std::nullopt;
113 } else {
114 return session;
115 }
116}
117
118std::vector<Session_with_Handle> Session_Manager::find_and_filter(const Server_Information& info,
119 Callbacks& callbacks,
120 const Policy& policy) {
121 // A value of '0' means: No policy restrictions. Session ticket lifetimes as
122 // communicated by the server apply regardless.
123 const std::chrono::seconds policy_lifetime =
124 (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
125
126 const size_t max_sessions_hint = std::max(policy.maximum_session_tickets_per_client_hello(), size_t(1));
127 const auto now = callbacks.tls_current_timestamp();
128
129 // An arbitrary number of loop iterations to perform before giving up
130 // to avoid a potential endless loop with a misbehaving session manager.
131 constexpr unsigned int max_attempts = 10;
132 std::vector<Session_with_Handle> sessions_and_handles;
133
134 // Query the session manager implementation for new sessions until at least
135 // one session passes the filter or no more sessions are found.
136 for(unsigned int attempt = 0; attempt < max_attempts && sessions_and_handles.empty(); ++attempt) {
137 sessions_and_handles = find_some(info, max_sessions_hint);
138
139 // The counterpart to the role check in retrieve(): a session established
140 // while acting as a TLS server must not be offered for resumption as a
141 // client. These are left in storage as they remain valid for the server
142 // role, so a retry would just yield them again.
143 std::erase_if(sessions_and_handles,
144 [](const auto& session) { return session.session.side() != Connection_Side::Client; });
145
146 // ... underlying implementation didn't find anything for the client role. Early exit.
147 if(sessions_and_handles.empty()) {
148 break;
149 }
150
151 std::erase_if(sessions_and_handles, [&](const auto& session) {
152 // RFC 5077 3.3 -- "Old Session Tickets"
153 // The ticket_lifetime_hint field contains a hint from the
154 // server about how long the ticket should be stored. [...]
155 // A client SHOULD delete the ticket and associated state when
156 // the time expires. It MAY delete the ticket earlier based on
157 // local policy.
158 //
159 // A value [in ticket_lifetime_hint] of zero is reserved to indicate
160 // that the lifetime of the ticket is unspecified.
161 //
162 // RFC 5246 F.1.4 -- TLS 1.2
163 // If either party suspects that the session may have been
164 // compromised, or that certificates may have expired or been
165 // revoked, it should force a full handshake. An upper limit of
166 // 24 hours is suggested for session ID lifetimes.
167 //
168 // RFC 8446 4.2.11.1 -- TLS 1.3
169 // The client's view of the age of a ticket is the time since the
170 // receipt of the NewSessionTicket message. Clients MUST NOT
171 // attempt to use tickets which have ages greater than the
172 // "ticket_lifetime" value which was provided with the ticket.
173 //
174 // RFC 8446 4.6.1 -- TLS 1.3
175 // Clients MUST NOT cache tickets for longer than 7 days,
176 // regardless of the ticket_lifetime, and MAY delete tickets
177 // earlier based on local policy.
178 //
179 // Note: TLS 1.3 tickets with a lifetime longer than 7 days are
180 // rejected during parsing with an "Illegal Parameter" alert.
181 // Other suggestions are left to the application via
182 // Policy::session_ticket_lifetime(). Session lifetimes as
183 // communicated by the server via the "lifetime_hint" are
184 // obeyed regardless of the policy setting.
185 const auto session_lifetime_hint = session.session.lifetime_hint();
186
187 const bool is_tls13 = !session.session.version().is_pre_tls_13();
188 const bool is_rfc5077_unspecified = (session_lifetime_hint.count() == 0 && !is_tls13);
189 auto effective_hint = is_rfc5077_unspecified ? std::chrono::seconds::max() : session_lifetime_hint;
190 if(is_tls13) {
191 effective_hint = std::min(effective_hint, std::chrono::seconds(604800));
192 }
193 const bool expired =
194 session_has_expired(now, session.session.start_time(), std::min(policy_lifetime, effective_hint));
195
196 if(expired) {
197 remove(session.handle);
198 }
199
200 return expired;
201 });
202 }
203
204 return sessions_and_handles;
205}
206
207std::vector<Session_with_Handle> Session_Manager::find(const Server_Information& info,
208 Callbacks& callbacks,
209 const Policy& policy) {
210 const auto allow_reusing_tickets = policy.reuse_session_tickets();
211
212 // Session_Manager::find() must be an atomic getter if ticket reuse is not
213 // allowed. I.e. each ticket handed to concurrently requesting threads must
214 // be unique. In that case we must hold a lock while retrieving a ticket.
215 // Otherwise, no locking is required on this level.
216 std::optional<lock_guard_type<recursive_mutex_type>> lk;
217 if(!allow_reusing_tickets) {
218 lk.emplace(mutex());
219 }
220
221 auto sessions_and_handles = find_and_filter(info, callbacks, policy);
222
223 // std::vector::resize() cannot be used as the vector's members aren't
224 // default constructible.
225 const auto session_limit = policy.maximum_session_tickets_per_client_hello();
226 while(session_limit > 0 && sessions_and_handles.size() > session_limit) {
227 sessions_and_handles.pop_back();
228 }
229
230 // RFC 8446 Appendix C.4
231 // Clients SHOULD NOT reuse a ticket for multiple connections. Reuse of
232 // a ticket allows passive observers to correlate different connections.
233 //
234 // When reuse of session tickets is not allowed, remove all tickets to be
235 // returned from the implementation's internal storage.
236 if(!allow_reusing_tickets) {
237 // The lock must be held here, otherwise we cannot guarantee the
238 // transactional retrieval of tickets to concurrently requesting clients.
239 BOTAN_ASSERT_NOMSG(lk.has_value());
240 for(const auto& [session, handle] : sessions_and_handles) {
241 if(!session.version().is_pre_tls_13() || !handle.is_id()) {
242 remove(handle);
243 }
244 }
245 }
246
247 return sessions_and_handles;
248}
249
250#if defined(BOTAN_HAS_TLS_13)
251
252std::optional<std::pair<Session, uint16_t>> Session_Manager::choose_from_offered_tickets(
253 const std::vector<PskIdentity>& tickets,
254 std::string_view hash_function,
255 Callbacks& callbacks,
256 const Policy& policy) {
257 // Note that the TLS server currently does not ensure that tickets aren't
258 // reused. As a result, no locking is required on this level.
259
260 // Limit how many identities we attempt to look up to prevent a client
261 // from forcing excessive session store queries.
262 const size_t max_attempts = std::min<size_t>(tickets.size(), 5);
263
264 for(size_t i = 0; i < max_attempts; ++i) {
265 const auto& ticket = tickets[i];
266
267 // An empty identity is not a valid session handle and cannot be a ticket we issued
268 if(ticket.identity().empty()) {
269 continue;
270 }
271
272 auto session = retrieve(Session_Handle(Opaque_Session_Handle(ticket.identity())), callbacks, policy);
273 if(session.has_value() && session->ciphersuite().prf_algo() == hash_function &&
274 session->version().is_tls_13_or_later()) {
275 return std::pair{std::move(session.value()), static_cast<uint16_t>(i)};
276 }
277
278 // RFC 8446 4.2.10
279 // For PSKs provisioned via NewSessionTicket, a server MUST validate
280 // that the ticket age for the selected PSK identity [...] is within a
281 // small tolerance of the time since the ticket was issued. If it is
282 // not, the server SHOULD proceed with the handshake but reject 0-RTT,
283 // and SHOULD NOT take any other action that assumes that this
284 // ClientHello is fresh.
285 //
286 // TODO: The ticket-age is currently not checked (as 0-RTT is not
287 // implemented) and we simply take the SHOULD at face value.
288 // Instead we could add a policy check letting the user decide.
289 }
290
291 return std::nullopt;
292}
293
294#endif
295
296} // namespace Botan::TLS
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
virtual std::chrono::system_clock::time_point tls_current_timestamp()
virtual bool reuse_session_tickets() const
virtual size_t maximum_session_tickets_per_client_hello() const
virtual std::chrono::seconds session_ticket_lifetime() const
Connection_Side side() const
Definition tls_session.h:89
Helper class to embody a session handle in all protocol versions.
virtual std::optional< std::pair< Session, uint16_t > > choose_from_offered_tickets(const std::vector< PskIdentity > &tickets, std::string_view hash_function, Callbacks &callbacks, const Policy &policy)
virtual size_t remove(const Session_Handle &handle)=0
virtual std::optional< Session > retrieve_one(const Session_Handle &handle)=0
Internal retrieval function for a single session.
virtual void store(const Session &session, const Session_Handle &handle)=0
Save a Session under a Session_Handle (TLS Client).
recursive_mutex_type & mutex()
BOTAN_FUTURE_EXPLICIT Session_Manager(const std::shared_ptr< RandomNumberGenerator > &rng)
virtual std::vector< Session_with_Handle > find_some(const Server_Information &info, size_t max_sessions_hint)=0
Internal retrieval function to find sessions to resume.
virtual std::optional< Session_Handle > establish(const Session &session, const std::optional< Session_ID > &id=std::nullopt, bool tls12_no_ticket=false)
Save a new Session and assign a Session_Handle (TLS Server).
virtual std::vector< Session_with_Handle > find(const Server_Information &info, Callbacks &callbacks, const Policy &policy)
Find all sessions that match a given server info.
std::shared_ptr< RandomNumberGenerator > m_rng
virtual std::optional< Session > retrieve(const Session_Handle &handle, Callbacks &callbacks, const Policy &policy)
Retrieves a specific session given a handle.
Strong< std::vector< uint8_t >, struct Session_ID_ > Session_ID
holds a TLS 1.2 session ID for stateful resumption
Strong< std::vector< uint8_t >, struct Opaque_Session_Handle_ > Opaque_Session_Handle
holds an opaque session handle as used in TLS 1.3 that could be either a ticket for stateless resumpt...