Botan 3.6.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/rng.h>
12#include <botan/tls_callbacks.h>
13#include <botan/tls_policy.h>
14
15namespace Botan::TLS {
16
17Session_Manager::Session_Manager(const std::shared_ptr<RandomNumberGenerator>& rng) : m_rng(rng) {
19}
20
21std::optional<Session_Handle> Session_Manager::establish(const Session& session,
22 const std::optional<Session_ID>& id,
23 bool tls12_no_ticket) {
24 // Establishing a session does not require locking at this level as
25 // concurrent TLS instances on a server will create unique sessions.
26
27 // By default, the session manager does not emit session tickets anyway
28 BOTAN_UNUSED(tls12_no_ticket);
29 BOTAN_ASSERT(session.side() == Connection_Side::Server, "Client tried to establish a session");
30
31 Session_Handle handle(id.value_or(m_rng->random_vec<Session_ID>(32)));
32 store(session, handle);
33 return handle;
34}
35
36std::optional<Session> Session_Manager::retrieve(const Session_Handle& handle,
37 Callbacks& callbacks,
38 const Policy& policy) {
39 // Retrieving a session for a given handle does not require locking on this
40 // level. Concurrent threads might handle the removal of an expired ticket
41 // more than once, but removing an already removed ticket is a harmless NOOP.
42
43 auto session = retrieve_one(handle);
44 if(!session.has_value()) {
45 return std::nullopt;
46 }
47
48 // A value of '0' means: No policy restrictions.
49 const std::chrono::seconds policy_lifetime =
50 (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
51
52 // RFC 5077 3.3 -- "Old Session Tickets"
53 // A server MAY treat a ticket as valid for a shorter or longer period of
54 // time than what is stated in the ticket_lifetime_hint.
55 //
56 // RFC 5246 F.1.4 -- TLS 1.2
57 // If either party suspects that the session may have been compromised, or
58 // that certificates may have expired or been revoked, it should force a
59 // full handshake. An upper limit of 24 hours is suggested for session ID
60 // lifetimes.
61 //
62 // RFC 8446 4.6.1 -- TLS 1.3
63 // A server MAY treat a ticket as valid for a shorter period of time than
64 // what is stated in the ticket_lifetime.
65 //
66 // Note: This disregards what is stored in the session (e.g. "lifetime_hint")
67 // and only takes the local policy into account. The lifetime stored in
68 // the sessions was taken from the same policy anyways and changes by
69 // the application should have an immediate effect.
70 const auto ticket_age =
71 std::chrono::duration_cast<std::chrono::seconds>(callbacks.tls_current_timestamp() - session->start_time());
72 const bool expired = ticket_age > policy_lifetime;
73
74 if(expired) {
75 remove(handle);
76 return std::nullopt;
77 } else {
78 return session;
79 }
80}
81
82std::vector<Session_with_Handle> Session_Manager::find_and_filter(const Server_Information& info,
83 Callbacks& callbacks,
84 const Policy& policy) {
85 // A value of '0' means: No policy restrictions. Session ticket lifetimes as
86 // communicated by the server apply regardless.
87 const std::chrono::seconds policy_lifetime =
88 (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
89
90 const size_t max_sessions_hint = std::max(policy.maximum_session_tickets_per_client_hello(), size_t(1));
91 const auto now = callbacks.tls_current_timestamp();
92
93 // An arbitrary number of loop iterations to perform before giving up
94 // to avoid a potential endless loop with a misbehaving session manager.
95 constexpr unsigned int max_attempts = 10;
96 std::vector<Session_with_Handle> sessions_and_handles;
97
98 // Query the session manager implementation for new sessions until at least
99 // one session passes the filter or no more sessions are found.
100 for(unsigned int attempt = 0; attempt < max_attempts && sessions_and_handles.empty(); ++attempt) {
101 sessions_and_handles = find_some(info, max_sessions_hint);
102
103 // ... underlying implementation didn't find anything. Early exit.
104 if(sessions_and_handles.empty()) {
105 break;
106 }
107
108 // TODO: C++20, use std::ranges::remove_if() once XCode and Android NDK caught up.
109 sessions_and_handles.erase(
110 std::remove_if(sessions_and_handles.begin(),
111 sessions_and_handles.end(),
112 [&](const auto& session) {
113 const auto age =
114 std::chrono::duration_cast<std::chrono::seconds>(now - session.session.start_time());
115
116 // RFC 5077 3.3 -- "Old Session Tickets"
117 // The ticket_lifetime_hint field contains a hint from the
118 // server about how long the ticket should be stored. [...]
119 // A client SHOULD delete the ticket and associated state when
120 // the time expires. It MAY delete the ticket earlier based on
121 // local policy.
122 //
123 // RFC 5246 F.1.4 -- TLS 1.2
124 // If either party suspects that the session may have been
125 // compromised, or that certificates may have expired or been
126 // revoked, it should force a full handshake. An upper limit of
127 // 24 hours is suggested for session ID lifetimes.
128 //
129 // RFC 8446 4.2.11.1 -- TLS 1.3
130 // The client's view of the age of a ticket is the time since the
131 // receipt of the NewSessionTicket message. Clients MUST NOT
132 // attempt to use tickets which have ages greater than the
133 // "ticket_lifetime" value which was provided with the ticket.
134 //
135 // RFC 8446 4.6.1 -- TLS 1.3
136 // Clients MUST NOT cache tickets for longer than 7 days,
137 // regardless of the ticket_lifetime, and MAY delete tickets
138 // earlier based on local policy.
139 //
140 // Note: TLS 1.3 tickets with a lifetime longer than 7 days are
141 // rejected during parsing with an "Illegal Parameter" alert.
142 // Other suggestions are left to the application via
143 // Policy::session_ticket_lifetime(). Session lifetimes as
144 // communicated by the server via the "lifetime_hint" are
145 // obeyed regardless of the policy setting.
146 const auto session_lifetime_hint = session.session.lifetime_hint();
147 const bool expired = age > std::min(policy_lifetime, session_lifetime_hint);
148
149 if(expired) {
150 remove(session.handle);
151 }
152
153 return expired;
154 }),
155 sessions_and_handles.end());
156 }
157
158 return sessions_and_handles;
159}
160
161std::vector<Session_with_Handle> Session_Manager::find(const Server_Information& info,
162 Callbacks& callbacks,
163 const Policy& policy) {
164 auto allow_reusing_tickets = policy.reuse_session_tickets();
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;
171 if(!allow_reusing_tickets) {
172 lk.emplace(mutex());
173 }
174
175 auto sessions_and_handles = find_and_filter(info, callbacks, policy);
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();
180 while(session_limit > 0 && sessions_and_handles.size() > session_limit) {
181 sessions_and_handles.pop_back();
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) {
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());
194 for(const auto& [session, handle] : sessions_and_handles) {
195 if(!session.version().is_pre_tls_13() || !handle.is_id()) {
196 remove(handle);
197 }
198 }
199 }
200
201 return sessions_and_handles;
202}
203
204#if defined(BOTAN_HAS_TLS_13)
205
206std::optional<std::pair<Session, uint16_t>> Session_Manager::choose_from_offered_tickets(
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) {
215 auto session = retrieve(Opaque_Session_Handle(ticket.identity()), callbacks, policy);
216 if(session.has_value() && session->ciphersuite().prf_algo() == hash_function &&
217 session->version().is_tls_13_or_later()) {
218 return std::pair{std::move(session.value()), i};
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;
234 }
235
236 return std::nullopt;
237}
238
239#endif
240
241} // namespace Botan::TLS
#define BOTAN_UNUSED
Definition assert.h:118
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:86
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:50
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
Helper class to embody a session handle in all protocol versions.
Definition tls_session.h:64
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)
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)
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.