• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.25
/src/lib/tls/sessions_sql/tls_session_manager_sql.cpp
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/database.h>
11
#include <botan/hex.h>
12
#include <botan/pwdhash.h>
13
#include <botan/rng.h>
14
#include <botan/internal/loadstor.h>
15
#include <chrono>
16

17
namespace Botan::TLS {
18

19
Session_Manager_SQL::Session_Manager_SQL(std::shared_ptr<SQL_Database> db,
22✔
20
                                         std::string_view passphrase,
21
                                         const std::shared_ptr<RandomNumberGenerator>& rng,
22
                                         size_t max_sessions) :
22✔
23
      Session_Manager(rng), m_db(std::move(db)), m_max_sessions(max_sessions) {
22✔
24
   create_or_migrate_and_open(passphrase);
22✔
25
}
22✔
26

27
void Session_Manager_SQL::create_or_migrate_and_open(std::string_view passphrase) {
22✔
28
   switch(detect_schema_revision()) {
22✔
29
      case CORRUPTED:
22✔
30
      case PRE_BOTAN_3_0:
22✔
31
      case EMPTY:
22✔
32
         // Legacy sessions before Botan 3.0 are simply dropped, no actual
33
         // migration is implemented. Same for apparently corrupt databases.
34
         m_db->exec("DROP TABLE IF EXISTS tls_sessions");
22✔
35
         m_db->exec("DROP TABLE IF EXISTS tls_sessions_metadata");
22✔
36
         create_with_latest_schema(passphrase, BOTAN_3_0);
22✔
37
         break;
22✔
38
      case BOTAN_3_0:
×
39
         initialize_existing_database(passphrase);
×
40
         break;
×
41
      default:
×
42
         throw Internal_Error("TLS session db has unknown database schema");
×
43
   }
44
}
22✔
45

46
Session_Manager_SQL::Schema_Revision Session_Manager_SQL::detect_schema_revision() {
22✔
47
   try {
22✔
48
      const auto meta_data_rows = m_db->row_count("tls_sessions_metadata");
22✔
49
      if(meta_data_rows != 1) {
1✔
50
         return CORRUPTED;
51
      }
52
   } catch(const SQL_Database::SQL_DB_Error&) {
21✔
53
      return EMPTY;  // `tls_sessions_metadata` probably didn't exist at all
21✔
54
   }
21✔
55

56
   try {
1✔
57
      auto stmt = m_db->new_statement("SELECT database_revision FROM tls_sessions_metadata");
1✔
58
      if(!stmt->step()) {
×
59
         throw Internal_Error("Failed to read revision of TLS session database");
×
60
      }
61
      return Schema_Revision(stmt->get_size_t(0));
×
62
   } catch(const SQL_Database::SQL_DB_Error&) {
1✔
63
      return PRE_BOTAN_3_0;  // `database_revision` did not exist yet -> preparing the statement failed
1✔
64
   }
1✔
65
}
66

67
void Session_Manager_SQL::create_with_latest_schema(std::string_view passphrase, Schema_Revision rev) {
22✔
68
   m_db->create_table(
22✔
69
      "CREATE TABLE tls_sessions "
70
      "("
71
      "session_id TEXT PRIMARY KEY, "
72
      "session_ticket BLOB, "
73
      "session_start INTEGER, "
74
      "hostname TEXT, "
75
      "hostport INTEGER, "
76
      "session BLOB NOT NULL"
77
      ")");
78

79
   m_db->create_table(
22✔
80
      "CREATE TABLE tls_sessions_metadata "
81
      "("
82
      "passphrase_salt BLOB, "
83
      "passphrase_iterations INTEGER, "
84
      "passphrase_check INTEGER, "
85
      "password_hash_family TEXT, "
86
      "database_revision INTEGER"
87
      ")");
88

89
   // speeds up lookups on session_tickets when deleting
90
   m_db->create_table("CREATE INDEX tls_tickets ON tls_sessions (session_ticket)");
22✔
91

92
   auto salt = m_rng->random_vec<std::vector<uint8_t>>(16);
22✔
93

94
   secure_vector<uint8_t> derived_key(32 + 2);
22✔
95

96
   const auto pbkdf_name = "PBKDF2(SHA-512)";
22✔
97
   auto pbkdf_fam = PasswordHashFamily::create_or_throw(pbkdf_name);
22✔
98

99
   auto desired_runtime = std::chrono::milliseconds(100);
22✔
100
   auto pbkdf = pbkdf_fam->tune(derived_key.size(), desired_runtime);
22✔
101

102
   pbkdf->derive_key(
22✔
103
      derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.data(), salt.size());
22✔
104

105
   const size_t iterations = pbkdf->iterations();
22✔
106
   const size_t check_val = make_uint16(derived_key[0], derived_key[1]);
22✔
107
   m_session_key = SymmetricKey(std::span(derived_key).subspan(2));
22✔
108

109
   auto stmt = m_db->new_statement("INSERT INTO tls_sessions_metadata VALUES (?1, ?2, ?3, ?4, ?5)");
22✔
110

111
   stmt->bind(1, salt);
22✔
112
   stmt->bind(2, iterations);
22✔
113
   stmt->bind(3, check_val);
22✔
114
   stmt->bind(4, pbkdf_name);
22✔
115
   stmt->bind(5, rev);
22✔
116

117
   stmt->spin();
22✔
118
}
110✔
119

120
void Session_Manager_SQL::initialize_existing_database(std::string_view passphrase) {
×
121
   auto stmt = m_db->new_statement("SELECT * FROM tls_sessions_metadata");
×
122
   if(!stmt->step()) {
×
123
      throw Internal_Error("Failed to initialize TLS session database");
×
124
   }
125

126
   std::pair<const uint8_t*, size_t> salt = stmt->get_blob(0);
×
127
   const size_t iterations = stmt->get_size_t(1);
×
128
   const size_t check_val_db = stmt->get_size_t(2);
×
129
   const std::string pbkdf_name = stmt->get_str(3);
×
130

131
   secure_vector<uint8_t> derived_key(32 + 2);
×
132

133
   auto pbkdf_fam = PasswordHashFamily::create_or_throw(pbkdf_name);
×
134
   auto pbkdf = pbkdf_fam->from_params(iterations);
×
135

136
   pbkdf->derive_key(
×
137
      derived_key.data(), derived_key.size(), passphrase.data(), passphrase.size(), salt.first, salt.second);
138

139
   const size_t check_val_created = make_uint16(derived_key[0], derived_key[1]);
×
140

141
   if(check_val_created != check_val_db)
×
142
      throw Invalid_Argument("Session database password not valid");
×
143

144
   m_session_key = SymmetricKey(std::span(derived_key).subspan(2));
×
145
}
×
146

147
void Session_Manager_SQL::store(const Session& session, const Session_Handle& handle) {
222✔
148
   std::optional<lock_guard_type<recursive_mutex_type>> lk;
222✔
149
   if(!database_is_threadsafe()) {
222✔
150
      lk.emplace(mutex());
×
151
   }
152

153
   if(session.server_info().hostname().empty()) {
666✔
154
      return;
×
155
   }
156

157
   auto stmt = m_db->new_statement(
222✔
158
      "INSERT OR REPLACE INTO tls_sessions"
159
      " VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
222✔
160

161
   // Generate a random session ID if the peer did not provide one. Note that
162
   // this ID will not be returned on ::find(), as the ticket is preferred.
163
   const auto id = handle.id().value_or(m_rng->random_vec<Session_ID>(32));
656✔
164
   const auto ticket = handle.ticket().value_or(Session_Ticket());
444✔
165

166
   stmt->bind(1, hex_encode(id.get()));
222✔
167
   stmt->bind(2, ticket.get());
222✔
168
   stmt->bind(3, session.start_time());
222✔
169
   stmt->bind(4, session.server_info().hostname());
444✔
170
   stmt->bind(5, session.server_info().port());
222✔
171
   stmt->bind(6, session.encrypt(m_session_key, *m_rng));
222✔
172

173
   stmt->spin();
222✔
174

175
   prune_session_cache();
222✔
176
}
666✔
177

178
std::optional<Session> Session_Manager_SQL::retrieve_one(const Session_Handle& handle) {
40✔
179
   std::optional<lock_guard_type<recursive_mutex_type>> lk;
40✔
180
   if(!database_is_threadsafe()) {
40✔
181
      lk.emplace(mutex());
×
182
   }
183

184
   if(auto session_id = handle.id()) {
40✔
185
      auto stmt = m_db->new_statement("SELECT session FROM tls_sessions WHERE session_id = ?1");
38✔
186

187
      stmt->bind(1, hex_encode(session_id->get()));
38✔
188

189
      while(stmt->step()) {
38✔
190
         std::pair<const uint8_t*, size_t> blob = stmt->get_blob(0);
27✔
191

192
         try {
27✔
193
            return Session::decrypt(blob.first, blob.second, m_session_key);
27✔
194
         } catch(...) {}
×
195
      }
196
   }
38✔
197

198
   return std::nullopt;
13✔
199
}
40✔
200

201
std::vector<Session_with_Handle> Session_Manager_SQL::find_some(const Server_Information& info,
98✔
202
                                                                const size_t max_sessions_hint) {
203
   std::optional<lock_guard_type<recursive_mutex_type>> lk;
98✔
204
   if(!database_is_threadsafe()) {
98✔
205
      lk.emplace(mutex());
×
206
   }
207

208
   auto stmt = m_db->new_statement(
98✔
209
      "SELECT session_id, session_ticket, session FROM tls_sessions"
210
      " WHERE hostname = ?1 AND hostport = ?2"
211
      " ORDER BY session_start DESC"
212
      " LIMIT ?3");
98✔
213

214
   stmt->bind(1, info.hostname());
196✔
215
   stmt->bind(2, info.port());
98✔
216
   stmt->bind(3, max_sessions_hint);
98✔
217

218
   std::vector<Session_with_Handle> found_sessions;
98✔
219
   while(stmt->step()) {
202✔
220
      auto handle = [&]() -> Session_Handle {
208✔
221
         auto ticket_blob = stmt->get_blob(1);
104✔
222
         if(ticket_blob.second > 0) {
104✔
223
            return Session_Ticket(std::span(ticket_blob.first, ticket_blob.second));
26✔
224
         } else {
225
            return Session_ID(Botan::hex_decode(stmt->get_str(0)));
273✔
226
         }
227
      }();
104✔
228

229
      std::pair<const uint8_t*, size_t> blob = stmt->get_blob(2);
104✔
230

231
      try {
104✔
232
         found_sessions.emplace_back(
208✔
233
            Session_with_Handle{Session::decrypt(blob.first, blob.second, m_session_key), std::move(handle)});
104✔
234
      } catch(...) {}
×
235
   }
104✔
236

237
   return found_sessions;
98✔
238
}
98✔
239

240
size_t Session_Manager_SQL::remove(const Session_Handle& handle) {
9✔
241
   // The number of deleted rows is taken globally from the database connection,
242
   // therefore we need to serialize this implementation.
243
   lock_guard_type<recursive_mutex_type> lk(mutex());
9✔
244

245
   if(const auto id = handle.id()) {
9✔
246
      auto stmt = m_db->new_statement("DELETE FROM tls_sessions WHERE session_id = ?1");
6✔
247
      stmt->bind(1, hex_encode(id->get()));
6✔
248
      stmt->spin();
6✔
249
   } else if(const auto ticket = handle.ticket()) {
9✔
250
      auto stmt = m_db->new_statement("DELETE FROM tls_sessions WHERE session_ticket = ?1");
3✔
251
      stmt->bind(1, ticket->get());
3✔
252
      stmt->spin();
3✔
253
   } else {
3✔
254
      // should not happen, as session handles are exclusively either an ID or a ticket
255
      throw Invalid_Argument("provided a session handle that is neither ID nor ticket");
×
256
   }
3✔
257

258
   return m_db->rows_changed_by_last_statement();
9✔
259
}
9✔
260

261
size_t Session_Manager_SQL::remove_all() {
13✔
262
   // The number of deleted rows is taken globally from the database connection,
263
   // therefore we need to serialize this implementation.
264
   lock_guard_type<recursive_mutex_type> lk(mutex());
13✔
265

266
   m_db->exec("DELETE FROM tls_sessions");
13✔
267
   return m_db->rows_changed_by_last_statement();
13✔
268
}
13✔
269

270
void Session_Manager_SQL::prune_session_cache() {
222✔
271
   // internal API: assuming that the lock is held already if needed
272

273
   if(m_max_sessions == 0)
222✔
274
      return;
25✔
275

276
   auto remove_oldest = m_db->new_statement(
197✔
277
      "DELETE FROM tls_sessions WHERE session_id NOT IN "
278
      "(SELECT session_id FROM tls_sessions ORDER BY session_start DESC LIMIT ?1)");
197✔
279
   remove_oldest->bind(1, m_max_sessions);
197✔
280
   remove_oldest->spin();
197✔
281
}
197✔
282

283
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc