Botan 3.14.1
Crypto and TLS for C&
Botan::TLS::Session_Manager_SQLite Class Referencefinal

#include <tls_session_manager_sqlite.h>

Inheritance diagram for Botan::TLS::Session_Manager_SQLite:
Botan::TLS::Session_Manager_SQL Botan::TLS::Session_Manager

Public Member Functions

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)
bool emits_session_tickets () override
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.
size_t remove (const Session_Handle &handle) override
size_t remove_all () override
virtual std::optional< Session > retrieve (const Session_Handle &handle, Callbacks &callbacks, const Policy &policy)
 Retrieves a specific session given a handle.
 Session_Manager_SQLite (std::string_view passphrase, const std::shared_ptr< RandomNumberGenerator > &rng, std::string_view db_filename, size_t max_sessions=1000)
void store (const Session &session, const Session_Handle &handle) override
 Save a Session under a Session_Handle (TLS Client).

Protected Member Functions

virtual bool database_is_threadsafe () const
std::vector< Session_with_Handle > find_some (const Server_Information &info, size_t max_sessions_hint) override
 Internal retrieval function to find sessions to resume.
recursive_mutex_type & mutex ()
std::optional< Session > retrieve_one (const Session_Handle &handle) override
 Internal retrieval function for a single session.

Protected Attributes

std::shared_ptr< RandomNumberGenerator > m_rng

Detailed Description

An implementation of Session_Manager that saves values in a SQLite3 database file, with the session data encrypted using a passphrase.

Warning
For clients, the hostnames associated with the saved sessions are stored in the database in plaintext. This may be a serious privacy risk in some situations.

Definition at line 27 of file tls_session_manager_sqlite.h.

Constructor & Destructor Documentation

◆ Session_Manager_SQLite()

Botan::TLS::Session_Manager_SQLite::Session_Manager_SQLite ( std::string_view passphrase,
const std::shared_ptr< RandomNumberGenerator > & rng,
std::string_view db_filename,
size_t max_sessions = 1000 )
Parameters
passphraseused to encrypt the session data
Random Number Generatorsa random number generator
db_filenamefilename of the SQLite database file. The table names tls_sessions and tls_sessions_metadata will be used. A new file is created with the default permissions of the process, so it should be placed in a directory that is not accessible to other users.
max_sessionsthe maximum number of sessions kept in the database; whenever a session is stored, the oldest sessions beyond this limit are permanently deleted. (If zero, don't cap)

Definition at line 14 of file tls_session_manager_sqlite.cpp.

17 :
18 Session_Manager_SQL(std::make_shared<Sqlite3_Database>(db_filename), passphrase, rng, max_sessions) {}
Session_Manager_SQL(std::shared_ptr< SQL_Database > db, std::string_view passphrase, const std::shared_ptr< RandomNumberGenerator > &rng, size_t max_sessions=1000)

References Botan::TLS::Session_Manager_SQL::Session_Manager_SQL().

Member Function Documentation

◆ choose_from_offered_tickets()

std::optional< std::pair< Session, uint16_t > > Botan::TLS::Session_Manager::choose_from_offered_tickets ( const std::vector< PskIdentity > & tickets,
std::string_view hash_function,
Callbacks & callbacks,
const Policy & policy )
virtualinherited

Lets the server application choose a PSK to use for a new TLS connection. Implementers must make sure that the PSK's associated hash function is equal to the passed hash_function.

RFC 8446 4.2.11 The server MUST ensure that it selects a compatible PSK (if any) and cipher suite.

The default implementation simply tries to retrieve all tickets in the order offered by the peer and picks the first that is found and features a matching hash algorithm.

This method is called only by TLS 1.3 servers. Implementations must only return sessions that were established by a TLS server (via Session_Manager::establish()), as applications may share a single manager between a client and a server role. The TLS server treats a session that was stored by a TLS client as an internal error. The default implementation relies on Session_Manager::retrieve() for this.

Parameters
ticketsa list of tickets that were offered by the client
hash_functionthe hash algorithm name we are going to use for the to-be-negotiated connection
callbackscallbacks to be used for session policy decisions
policypolicy to be used for session policy decisions
Returns
a std::pair of the Session associated to the chosen PSK and the index of the selected ticket; std::nullopt if no PSK was chosen for usage (will result in a full handshake)
Note
if no PSK is chosen, the server will attempt a regular handshake.

Definition at line 252 of file tls_session_manager.cpp.

256 {
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}
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 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...

References retrieve().

Referenced by Botan::TLS::PSK::select_offered_psk(), and store().

◆ database_is_threadsafe()

virtual bool Botan::TLS::Session_Manager_SQL::database_is_threadsafe ( ) const
inlineprotectedvirtualinherited

Decides whether the underlying database is considered threadsafe in the context the Session_Manager is used. If this returns false, accesses to the database are serialized with the base class' recursive mutex.

Definition at line 69 of file tls_session_manager_sql.h.

69{ return m_db->is_threadsafe(); }

Referenced by find_some(), retrieve_one(), and store().

◆ emits_session_tickets()

bool Botan::TLS::Session_Manager_SQL::emits_session_tickets ( )
inlineoverridevirtualinherited

Declares whether the given Session_Manager implementation may emit session tickets. Note that this does not mean that the implementation must always emit tickets.

Concrete implementations should declare this, to allow the TLS implementations to act accordingly. E.g. to advertise support for session tickets in their Server Hello.

Returns
true if the Session_Manager produces session tickets

Reimplemented from Botan::TLS::Session_Manager.

Definition at line 58 of file tls_session_manager_sql.h.

58{ return false; }

◆ establish()

std::optional< Session_Handle > Botan::TLS::Session_Manager::establish ( const Session & session,
const std::optional< Session_ID > & id = std::nullopt,
bool tls12_no_ticket = false )
virtualinherited

Save a new Session and assign a Session_Handle (TLS Server).

Save a new session on a best effort basis; the manager may not in fact be able to save the session for whatever reason; this is not an error. Callers cannot assume that calling establish() followed immediately by retrieve() or choose_from_offered_tickets() will result in a successful lookup. In case no session was stored, std::nullopt is returned.

This method is only called on TLS servers.

Note that implementations will silently refrain from sending session tickets to the client when this method returns std::nullopt.

Parameters
sessionto save
idto use (instead of an ID chosen by the manager)
tls12_no_ticketdisable tickets for this establishment (set when TLS 1.2 client does not support them)
Returns
a Session_Handle containing either an ID or a ticket if the session was saved, otherwise std::nullopt

Reimplemented in Botan::TLS::Session_Manager_Hybrid, Botan::TLS::Session_Manager_Noop, and Botan::TLS::Session_Manager_Stateless.

Definition at line 48 of file tls_session_manager.cpp.

50 {
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}
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
virtual void store(const Session &session, const Session_Handle &handle)=0
Save a Session under a Session_Handle (TLS Client).
std::shared_ptr< RandomNumberGenerator > m_rng
Strong< std::vector< uint8_t >, struct Session_ID_ > Session_ID
holds a TLS 1.2 session ID for stateful resumption

References BOTAN_ASSERT, BOTAN_UNUSED, m_rng, Botan::TLS::Server, Botan::TLS::Session_Base::side(), and store().

◆ find()

std::vector< Session_with_Handle > Botan::TLS::Session_Manager::find ( const Server_Information & info,
Callbacks & callbacks,
const Policy & policy )
virtualinherited

Find all sessions that match a given server info.

TLS clients use this to obtain session resumption information for a server they are wishing to handshake with. Typically, session info will have been received in prior connections to that same server and stored using Session_Manager::store().

The default implementation will invoke Session_Manager::find_some() and filter the result against a policy. Most notably an expiry check. Expired sessions will be removed via Session_Manager::remove().

Sessions that were established by a TLS server (via Session_Manager::establish()) are never returned, as applications may share a single manager between a client and a server role. Such sessions are not removed; they remain valid for the server role.

The TLS client implementations will query the session manager exactly once per handshake attempt. If no reuse is desired, the session manager may remove the sessions internally when handing them out to the client. The default implementation adheres to Policy::reuse_session_tickets().

For TLS 1.2 the client implementation will attempt a resumption with the first session in the returned list. For TLS 1.3, it will offer all found sessions to the server.

Applications that wish to implement their own Session_Manager may override the default implementation to add further policy checks. Though, typically implementing Session_Manager::find_some() and relying on the default implementation is enough.

Parameters
infothe info about the server we want to handshake with
callbackscallbacks to be used for session policy decisions
policypolicy to be used for session policy decisions
Returns
a list of usable sessions that might be empty if no such session exists or passed the policy validation

Reimplemented in Botan::TLS::Session_Manager_Hybrid.

Definition at line 207 of file tls_session_manager.cpp.

209 {
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}
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
virtual size_t remove(const Session_Handle &handle)=0
recursive_mutex_type & mutex()

References BOTAN_ASSERT_NOMSG, Botan::TLS::Policy::maximum_session_tickets_per_client_hello(), mutex(), remove(), and Botan::TLS::Policy::reuse_session_tickets().

Referenced by store().

◆ find_some()

std::vector< Session_with_Handle > Botan::TLS::Session_Manager_SQL::find_some ( const Server_Information & info,
size_t max_sessions_hint )
overrideprotectedvirtualinherited

Internal retrieval function to find sessions to resume.

Try to find saved sessions using info about the server we're planning to connect to. It should return a list of sessions in preference order of the session manager.

Applications that wish to implement their own Session_Manager will have to provide an implementation for it.

Note that the TLS client implementations do not perform any checks on the validity of the session for a given info. Particularly, it is the Session_Manager's responsibility to ensure the restrictions posed in RFC 8446 4.6.1 regarding server certificate validity for the given info.

This is called for TLS clients only. Sessions that were established by a TLS server (via Session_Manager::establish()) must not be returned, as applications may share a single manager between a client and a server role. Session_Manager::find() discards them regardless, but they would use up the max_sessions_hint budget.

Parameters
infothe information about the server
max_sessions_hinta non-binding guideline for an upper bound of sessions to return from this method (will be at least 1 but potentially more)
Returns
the found sessions along with their handles (containing either a session ID or a ticket)

Implements Botan::TLS::Session_Manager.

Definition at line 221 of file tls_session_manager_sql.cpp.

222 {
223 std::optional<lock_guard_type<recursive_mutex_type>> lk;
225 lk.emplace(mutex());
226 }
227
228 // Sessions established by the server role are skipped below, so the limit
229 // cannot be applied in SQL. Rows are stepped only as far as needed.
230 auto stmt = m_db->new_statement(
231 "SELECT session_id, session_ticket, session FROM tls_sessions"
232 " WHERE hostname = ?1 AND hostport = ?2"
233 " ORDER BY session_start DESC");
234
235 stmt->bind(1, info.hostname());
236 stmt->bind(2, info.port());
237
238 std::vector<Session_with_Handle> found_sessions;
239 while(found_sessions.size() < max_sessions_hint && stmt->step()) {
240 // Rows that cannot be decoded (eg due to corruption) are skipped
241 try {
242 auto handle = [&]() -> Session_Handle {
243 const auto ticket_blob = stmt->get_blob(1);
244 if(!ticket_blob.empty()) {
245 return Session_Handle(Session_Ticket(ticket_blob));
246 } else {
247 return Session_Handle(Session_ID(Botan::hex_decode(stmt->get_str(0).value())));
248 }
249 }();
250
251 auto session = Session::decrypt(stmt->get_blob(2), m_session_key);
252
253 // The hostname and port columns are not authenticated, so make sure
254 // the session actually belongs to the requested server.
255 if(session.side() == Connection_Side::Client && session.server_info() == info) {
256 found_sessions.emplace_back(Session_with_Handle{std::move(session), std::move(handle)});
257 }
258 } catch(...) {}
259 }
260
261 return found_sessions;
262}
static Session decrypt(const uint8_t ctext[], size_t ctext_size, const SymmetricKey &key)
Strong< std::vector< uint8_t >, struct Session_Ticket_ > Session_Ticket
holds a TLS 1.2 session ticket for stateless resumption
size_t hex_decode(uint8_t output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
Definition hex.cpp:75

References Botan::TLS::Client, database_is_threadsafe(), Botan::TLS::Session::decrypt(), Botan::hex_decode(), Botan::TLS::Server_Information::hostname(), Botan::TLS::Session_Manager::mutex(), and Botan::TLS::Server_Information::port().

◆ mutex()

◆ remove()

size_t Botan::TLS::Session_Manager_SQL::remove ( const Session_Handle & handle)
overridevirtualinherited

Remove a specific session from the cache, if it exists. The handle might contain either a session ID or a ticket.

Parameters
handlea Session_Handle of the session to be removed
Returns
the number of sessions that were removed

Implements Botan::TLS::Session_Manager.

Definition at line 264 of file tls_session_manager_sql.cpp.

264 {
265 // The number of deleted rows is taken globally from the database connection,
266 // therefore we need to serialize this implementation.
268
269 if(const auto id = handle.id()) {
270 const auto stmt = m_db->new_statement("DELETE FROM tls_sessions WHERE session_id = ?1");
271 stmt->bind(1, hex_encode(id->get()));
272 stmt->spin();
273 } else if(const auto ticket = handle.ticket()) {
274 const auto stmt = m_db->new_statement("DELETE FROM tls_sessions WHERE session_ticket = ?1");
275 stmt->bind(1, ticket->get());
276 stmt->spin();
277 } else {
278 // should not happen, as session handles are exclusively either an ID or a ticket
279 throw Invalid_Argument("provided a session handle that is neither ID nor ticket");
280 }
281
282 return m_db->rows_changed_by_last_statement();
283}
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
Definition hex.cpp:34
lock_guard< T > lock_guard_type
Definition mutex.h:58

References Botan::hex_encode(), Botan::TLS::Session_Handle::id(), Botan::TLS::Session_Manager::mutex(), and Botan::TLS::Session_Handle::ticket().

Referenced by ~Session_Manager_SQL().

◆ remove_all()

size_t Botan::TLS::Session_Manager_SQL::remove_all ( )
overridevirtualinherited

Remove all sessions from the cache

Returns
the number of sessions that were removed

Implements Botan::TLS::Session_Manager.

Definition at line 285 of file tls_session_manager_sql.cpp.

285 {
286 // The number of deleted rows is taken globally from the database connection,
287 // therefore we need to serialize this implementation.
289
290 m_db->exec("DELETE FROM tls_sessions");
291 return m_db->rows_changed_by_last_statement();
292}

References Botan::TLS::Session_Manager::mutex().

Referenced by ~Session_Manager_SQL().

◆ retrieve()

std::optional< Session > Botan::TLS::Session_Manager::retrieve ( const Session_Handle & handle,
Callbacks & callbacks,
const Policy & policy )
virtualinherited

Retrieves a specific session given a handle.

This is typically used by TLS servers to obtain resumption information for a previous call to Session_Manager::establish() when a client requested resumption using the handle.

Even if the session is found successfully, it is returned only if it passes policy validations. Most notably an expiry check. If the expiry check fails, the default implementation calls Session_Manager::remove() for the provided handle.

Sessions that were stored by a TLS client (via Session_Manager::store()) are never returned, as applications may share a single manager between a client and a server role. Such sessions are not removed; they remain valid for the client role. Overriding implementations must uphold this; the TLS server treats a client session returned here as an internal error.

Applications that wish to implement their own Session_Manager may override the default implementation to add further policy checks. Though, typically implementing Session_Manager::retrieve_one() and relying on the default implementation is enough.

Parameters
handlethe Session_Handle to be retrieved
callbackscallbacks to be used for session policy decisions
policypolicy to be used for session policy decisions
Returns
the obtained session or std::nullopt if no session was found or the policy checks failed

Reimplemented in Botan::TLS::Session_Manager_Hybrid.

Definition at line 63 of file tls_session_manager.cpp.

65 {
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}
virtual std::optional< Session > retrieve_one(const Session_Handle &handle)=0
Internal retrieval function for a single session.

References remove(), retrieve_one(), Botan::TLS::Server, Botan::TLS::Policy::session_ticket_lifetime(), and Botan::TLS::Callbacks::tls_current_timestamp().

Referenced by choose_from_offered_tickets(), and store().

◆ retrieve_one()

std::optional< Session > Botan::TLS::Session_Manager_SQL::retrieve_one ( const Session_Handle & handle)
overrideprotectedvirtualinherited

Internal retrieval function for a single session.

Try to obtain a Session from a Session_Handle that contains either a session ID or a session ticket. This method should not apply any policy decision (such as ticket expiry) but simply be a storage interface.

Applications that wish to implement their own Session_Manager will have to provide an implementation for it.

This method is called only by servers. Sessions that were stored by a TLS client (via Session_Manager::store()) must not be returned, as applications may share a single manager between a client and a server role. Session_Manager::retrieve() discards them regardless.

Parameters
handlea Session_Handle containing either an ID or a ticket
Returns
the obtained session or std::nullopt if none can be obtained

Implements Botan::TLS::Session_Manager.

Definition at line 196 of file tls_session_manager_sql.cpp.

196 {
197 std::optional<lock_guard_type<recursive_mutex_type>> lk;
199 lk.emplace(mutex());
200 }
201
202 if(auto session_id = handle.id()) {
203 const auto stmt = m_db->select("session", "tls_sessions", "session_id = ?1");
204
205 stmt->bind(1, hex_encode(session_id->get()));
206
207 while(stmt->step()) {
208 try {
209 auto session = Session::decrypt(stmt->get_blob(0), m_session_key);
210 // Sessions stored by the client role are not subject to server-side lookup
211 if(session.side() == Connection_Side::Server) {
212 return session;
213 }
214 } catch(...) {}
215 }
216 }
217
218 return std::nullopt;
219}

References database_is_threadsafe(), Botan::TLS::Session::decrypt(), Botan::hex_encode(), Botan::TLS::Session_Handle::id(), Botan::TLS::Session_Manager::mutex(), and Botan::TLS::Server.

◆ store()

void Botan::TLS::Session_Manager_SQL::store ( const Session & session,
const Session_Handle & handle )
overridevirtualinherited

Save a Session under a Session_Handle (TLS Client).

Save a session on a best effort basis; the manager may not in fact be able to save the session for whatever reason; this is not an error. Callers cannot assume that calling store() followed immediately by find() will result in a successful lookup.

In contrast to establish(), this stores sessions that were created by the server along with a Session_Handle also coined by the server.

This method is only called on TLS clients.

Parameters
sessionto save
handlea Session_Handle on which this session should by stored

Implements Botan::TLS::Session_Manager.

Definition at line 164 of file tls_session_manager_sql.cpp.

164 {
165 std::optional<lock_guard_type<recursive_mutex_type>> lk;
167 lk.emplace(mutex());
168 }
169
170 // Client sessions are looked up by hostname. A server however retrieves
171 // sessions by their handle, regardless of whether the client sent an SNI.
172 if(session.side() == Connection_Side::Client && session.server_info().hostname().empty()) {
173 return;
174 }
175
176 const auto stmt = m_db->upsert("tls_sessions",
177 {"session_id", "session_ticket", "session_start", "hostname", "hostport", "session"});
178
179 // Generate a random session ID if the peer did not provide one. Note that
180 // this ID will not be returned on ::find(), as the ticket is preferred.
181 const auto id = handle.id().value_or(m_rng->random_vec<Session_ID>(32));
182 const auto ticket = handle.ticket().value_or(Session_Ticket());
183
184 stmt->bind(1, hex_encode(id.get()));
185 stmt->bind(2, ticket.get());
186 stmt->bind(3, session.start_time());
187 stmt->bind(4, session.server_info().hostname());
188 stmt->bind(5, session.server_info().port());
189 stmt->bind(6, session.encrypt(m_session_key, *m_rng));
190
191 stmt->spin();
192
193 prune_session_cache();
194}

References Botan::TLS::Client, database_is_threadsafe(), Botan::TLS::Session::encrypt(), Botan::hex_encode(), Botan::TLS::Server_Information::hostname(), Botan::TLS::Session_Handle::id(), Botan::TLS::Session_Manager::m_rng, Botan::TLS::Session_Manager::mutex(), Botan::TLS::Server_Information::port(), Botan::TLS::Session_Base::server_info(), Botan::TLS::Session_Base::side(), Botan::TLS::Session_Base::start_time(), and Botan::TLS::Session_Handle::ticket().

Referenced by ~Session_Manager_SQL().

Member Data Documentation

◆ m_rng


The documentation for this class was generated from the following files: