8#include <botan/tls_session_manager_sql.h>
10#include <botan/assert.h>
11#include <botan/database.h>
13#include <botan/pwdhash.h>
15#include <botan/tls_session.h>
16#include <botan/internal/loadstor.h>
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) {
26 create_or_migrate_and_open(passphrase);
29void Session_Manager_SQL::create_or_migrate_and_open(std::string_view passphrase) {
30 switch(detect_schema_revision()) {
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);
41 initialize_existing_database(passphrase);
44 throw Internal_Error(
"TLS session db has unknown database schema");
48Session_Manager_SQL::Schema_Revision Session_Manager_SQL::detect_schema_revision() {
50 const auto meta_data_rows = m_db->row_count(
"tls_sessions_metadata");
51 if(meta_data_rows != 1) {
54 }
catch(
const SQL_Database::SQL_DB_Error&) {
59 const auto stmt = m_db->select(
"database_revision",
"tls_sessions_metadata");
61 throw Internal_Error(
"Failed to read revision of TLS session database");
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");
67 return static_cast<Schema_Revision
>(revision);
68 }
catch(
const SQL_Database::SQL_DB_Error&) {
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;
79 m_db->create_table(DB::Table_Schema(
"tls_sessions",
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(),
89 m_db->create_table(DB::Table_Schema(
"tls_sessions_metadata",
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(),
99 m_db->exec(
"CREATE INDEX tls_tickets ON tls_sessions (session_ticket)");
101 auto salt =
m_rng->random_vec<std::vector<uint8_t>>(16);
105 const std::string pbkdf_name =
"PBKDF2(SHA-512)";
108 constexpr uint32_t desired_runtime_msec = 100;
109 auto pbkdf = pbkdf_fam->tune_params(derived_key.size(), desired_runtime_msec);
112 derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.data(), salt.size());
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));
118 const auto stmt = m_db->new_statement(
"INSERT INTO tls_sessions_metadata VALUES (?1, ?2, ?3, ?4, ?5)");
121 stmt->bind(2, iterations);
122 stmt->bind(3, check_val);
123 stmt->bind(4, pbkdf_name);
129void Session_Manager_SQL::initialize_existing_database(std::string_view passphrase) {
130 const auto stmt = m_db->select(
"*",
"tls_sessions_metadata");
132 throw Internal_Error(
"Failed to initialize TLS session database");
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(
"");
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");
150 auto pbkdf = pbkdf_fam->from_params(iterations);
153 derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.data(), salt.size());
155 const size_t check_val_created =
make_uint16(derived_key[0], derived_key[1]);
157 if(check_val_created != check_val_db) {
158 throw Invalid_Argument(
"Session database password not valid");
161 m_session_key =
SymmetricKey(std::span(derived_key).subspan(2));
165 std::optional<lock_guard_type<recursive_mutex_type>> lk;
176 const auto stmt = m_db->upsert(
"tls_sessions",
177 {
"session_id",
"session_ticket",
"session_start",
"hostname",
"hostport",
"session"});
185 stmt->bind(2, ticket.get());
193 prune_session_cache();
197 std::optional<lock_guard_type<recursive_mutex_type>> lk;
202 if(
auto session_id = handle.
id()) {
203 const auto stmt = m_db->select(
"session",
"tls_sessions",
"session_id = ?1");
207 while(stmt->step()) {
222 const size_t max_sessions_hint) {
223 std::optional<lock_guard_type<recursive_mutex_type>> lk;
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");
236 stmt->bind(2, info.
port());
238 std::vector<Session_with_Handle> found_sessions;
239 while(found_sessions.size() < max_sessions_hint && stmt->step()) {
243 const auto ticket_blob = stmt->get_blob(1);
244 if(!ticket_blob.empty()) {
261 return found_sessions;
269 if(
const auto id = handle.
id()) {
270 const auto stmt = m_db->new_statement(
"DELETE FROM tls_sessions WHERE session_id = ?1");
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());
279 throw Invalid_Argument(
"provided a session handle that is neither ID nor ticket");
282 return m_db->rows_changed_by_last_statement();
290 m_db->exec(
"DELETE FROM tls_sessions");
291 return m_db->rows_changed_by_last_statement();
294void Session_Manager_SQL::prune_session_cache() {
297 if(m_max_sessions == 0) {
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();
#define BOTAN_ARG_CHECK(expr, msg)
static std::unique_ptr< PasswordHashFamily > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Connection_Side side() const
std::chrono::system_clock::time_point start_time() const
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.
virtual bool database_is_threadsafe() const
std::optional< Session > retrieve_one(const Session_Handle &handle) override
Internal retrieval function for a single session.
size_t remove_all() override
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
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
size_t hex_decode(uint8_t output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
std::vector< T, secure_allocator< T > > secure_vector
lock_guard< T > lock_guard_type
constexpr uint16_t make_uint16(uint8_t i0, uint8_t i1)