Botan 3.14.1
Crypto and TLS for C&
tls_session_manager_sql.cpp
Go to the documentation of this file.
1/*
2* SQL TLS Session Manager
3* (C) 2012,2014 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/tls_session_manager_sql.h>
9
10#include <botan/assert.h>
11#include <botan/database.h>
12#include <botan/hex.h>
13#include <botan/pwdhash.h>
14#include <botan/rng.h>
15#include <botan/tls_session.h>
16#include <botan/internal/loadstor.h>
17
18namespace Botan::TLS {
19
20Session_Manager_SQL::Session_Manager_SQL(std::shared_ptr<SQL_Database> db,
21 std::string_view passphrase,
22 const std::shared_ptr<RandomNumberGenerator>& rng,
23 size_t max_sessions) :
24 Session_Manager(rng), m_db(std::move(db)), m_max_sessions(max_sessions) {
25 BOTAN_ARG_CHECK(m_db != nullptr, "Database must not be null");
26 create_or_migrate_and_open(passphrase);
27}
28
29void Session_Manager_SQL::create_or_migrate_and_open(std::string_view passphrase) {
30 switch(detect_schema_revision()) {
31 case CORRUPTED:
32 case PRE_BOTAN_3_0:
33 case EMPTY:
34 // Legacy sessions before Botan 3.0 are simply dropped, no actual
35 // migration is implemented. Same for apparently corrupt databases.
36 m_db->exec("DROP TABLE IF EXISTS tls_sessions");
37 m_db->exec("DROP TABLE IF EXISTS tls_sessions_metadata");
38 create_with_latest_schema(passphrase, BOTAN_3_0);
39 break;
40 case BOTAN_3_0:
41 initialize_existing_database(passphrase);
42 break;
43 default:
44 throw Internal_Error("TLS session db has unknown database schema");
45 }
46}
47
48Session_Manager_SQL::Schema_Revision Session_Manager_SQL::detect_schema_revision() {
49 try {
50 const auto meta_data_rows = m_db->row_count("tls_sessions_metadata");
51 if(meta_data_rows != 1) {
52 return CORRUPTED;
53 }
54 } catch(const SQL_Database::SQL_DB_Error&) {
55 return EMPTY; // `tls_sessions_metadata` probably didn't exist at all
56 }
57
58 try {
59 const auto stmt = m_db->select("database_revision", "tls_sessions_metadata");
60 if(!stmt->step()) {
61 throw Internal_Error("Failed to read revision of TLS session database");
62 }
63 const size_t revision = stmt->get_size_t(0);
64 if(revision != PRE_BOTAN_3_0 && revision != BOTAN_3_0) {
65 throw Internal_Error("TLS session db has unknown database schema");
66 }
67 return static_cast<Schema_Revision>(revision);
68 } catch(const SQL_Database::SQL_DB_Error&) {
69 return PRE_BOTAN_3_0; // `database_revision` did not exist yet -> preparing the statement failed
70 }
71}
72
73void Session_Manager_SQL::create_with_latest_schema(std::string_view passphrase, Schema_Revision rev) {
74 using DB = SQL_Database;
75 const auto blob = DB::Column_Type::Blob;
76 const auto str = DB::Column_Type::String;
77 const auto integer = DB::Column_Type::Integer;
78
79 m_db->create_table(DB::Table_Schema("tls_sessions",
80 {
81 DB::Column("session_id", str).primary_key(),
82 DB::Column("session_ticket", blob),
83 DB::Column("session_start", integer),
84 DB::Column("hostname", str),
85 DB::Column("hostport", integer),
86 DB::Column("session", blob).not_null(),
87 }));
88
89 m_db->create_table(DB::Table_Schema("tls_sessions_metadata",
90 {
91 DB::Column("passphrase_salt", blob).not_null(),
92 DB::Column("passphrase_iterations", integer).not_null(),
93 DB::Column("passphrase_check", integer).not_null(),
94 DB::Column("password_hash_family", str).not_null(),
95 DB::Column("database_revision", integer).not_null(),
96 }));
97
98 // speeds up lookups on session_tickets when deleting
99 m_db->exec("CREATE INDEX tls_tickets ON tls_sessions (session_ticket)");
100
101 auto salt = m_rng->random_vec<std::vector<uint8_t>>(16);
102
103 secure_vector<uint8_t> derived_key(32 + 2);
104
105 const std::string pbkdf_name = "PBKDF2(SHA-512)";
106 auto pbkdf_fam = PasswordHashFamily::create_or_throw(pbkdf_name);
107
108 constexpr uint32_t desired_runtime_msec = 100;
109 auto pbkdf = pbkdf_fam->tune_params(derived_key.size(), desired_runtime_msec);
110
111 pbkdf->derive_key(
112 derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.data(), salt.size());
113
114 const size_t iterations = pbkdf->iterations();
115 const size_t check_val = make_uint16(derived_key[0], derived_key[1]);
116 m_session_key = SymmetricKey(std::span(derived_key).subspan(2));
117
118 const auto stmt = m_db->new_statement("INSERT INTO tls_sessions_metadata VALUES (?1, ?2, ?3, ?4, ?5)");
119
120 stmt->bind(1, salt);
121 stmt->bind(2, iterations);
122 stmt->bind(3, check_val);
123 stmt->bind(4, pbkdf_name);
124 stmt->bind(5, rev);
125
126 stmt->spin();
127}
128
129void Session_Manager_SQL::initialize_existing_database(std::string_view passphrase) {
130 const auto stmt = m_db->select("*", "tls_sessions_metadata");
131 if(!stmt->step()) {
132 throw Internal_Error("Failed to initialize TLS session database");
133 }
134
135 const auto salt = stmt->get_blob(0);
136 const size_t iterations = stmt->get_size_t(1);
137 const size_t check_val_db = stmt->get_size_t(2);
138 const std::string pbkdf_name = stmt->get_str(3).value_or("");
139
140 // The metadata is not authenticated; only accept what create_with_latest_schema()
141 // writes, rather than letting it request an arbitrary amount of work.
142 constexpr size_t max_iterations = 10'000'000;
143 if(pbkdf_name != "PBKDF2(SHA-512)" || salt.size() != 16 || iterations == 0 || iterations > max_iterations) {
144 throw Invalid_Argument("TLS session database has invalid passphrase parameters");
145 }
146
147 secure_vector<uint8_t> derived_key(32 + 2);
148
149 auto pbkdf_fam = PasswordHashFamily::create_or_throw(pbkdf_name);
150 auto pbkdf = pbkdf_fam->from_params(iterations);
151
152 pbkdf->derive_key(
153 derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.data(), salt.size());
154
155 const size_t check_val_created = make_uint16(derived_key[0], derived_key[1]);
156
157 if(check_val_created != check_val_db) {
158 throw Invalid_Argument("Session database password not valid");
159 }
160
161 m_session_key = SymmetricKey(std::span(derived_key).subspan(2));
162}
163
164void Session_Manager_SQL::store(const Session& session, const Session_Handle& handle) {
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}
195
196std::optional<Session> Session_Manager_SQL::retrieve_one(const Session_Handle& handle) {
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}
220
221std::vector<Session_with_Handle> Session_Manager_SQL::find_some(const Server_Information& info,
222 const size_t max_sessions_hint) {
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}
263
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}
284
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}
293
294void Session_Manager_SQL::prune_session_cache() {
295 // internal API: assuming that the lock is held already if needed
296
297 if(m_max_sessions == 0) {
298 return;
299 }
300
301 const auto remove_oldest = m_db->new_statement(
302 "DELETE FROM tls_sessions WHERE session_id NOT IN "
303 "(SELECT session_id FROM tls_sessions ORDER BY session_start DESC LIMIT ?1)");
304 remove_oldest->bind(1, m_max_sessions);
305 remove_oldest->spin();
306}
307
308} // namespace Botan::TLS
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
static std::unique_ptr< PasswordHashFamily > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition pwdhash.cpp:125
Connection_Side side() const
Definition tls_session.h:89
std::chrono::system_clock::time_point start_time() const
Definition tls_session.h:69
const Server_Information & server_info() const
Helper class to embody a session handle in all protocol versions.
std::optional< Session_Ticket > ticket() const
std::optional< Session_ID > id() const
Session_Manager_SQL(std::shared_ptr< SQL_Database > db, std::string_view passphrase, const std::shared_ptr< RandomNumberGenerator > &rng, size_t max_sessions=1000)
void store(const Session &session, const Session_Handle &handle) override
Save a Session under a Session_Handle (TLS Client).
size_t remove(const Session_Handle &handle) override
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.
std::optional< Session > retrieve_one(const Session_Handle &handle) override
Internal retrieval function for a single session.
recursive_mutex_type & mutex()
BOTAN_FUTURE_EXPLICIT Session_Manager(const std::shared_ptr< RandomNumberGenerator > &rng)
std::shared_ptr< RandomNumberGenerator > m_rng
std::vector< uint8_t > encrypt(const SymmetricKey &key, RandomNumberGenerator &rng) const
static Session decrypt(const uint8_t ctext[], size_t ctext_size, const SymmetricKey &key)
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 Session_Ticket_ > Session_Ticket
holds a TLS 1.2 session ticket for stateless resumption
OctetString SymmetricKey
Definition symkey.h:153
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
Definition hex.cpp:34
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
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
lock_guard< T > lock_guard_type
Definition mutex.h:58
constexpr uint16_t make_uint16(uint8_t i0, uint8_t i1)
Definition loadstor.h:92