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

randombit / botan / 5123321399

30 May 2023 04:06PM UTC coverage: 92.213% (+0.004%) from 92.209%
5123321399

Pull #3558

github

web-flow
Merge dd72f7389 into 057bcbc35
Pull Request #3558: Add braces around all if/else statements

75602 of 81986 relevant lines covered (92.21%)

11859779.3 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

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

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

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

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

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

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

174
   stmt->spin();
225✔
175

176
   prune_session_cache();
225✔
177
}
675✔
178

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

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

188
      stmt->bind(1, hex_encode(session_id->get()));
35✔
189

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

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

199
   return std::nullopt;
13✔
200
}
37✔
201

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

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

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

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

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

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

238
   return found_sessions;
98✔
239
}
98✔
240

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

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

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

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

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

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

274
   if(m_max_sessions == 0) {
225✔
275
      return;
25✔
276
   }
277

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

285
}  // namespace Botan::TLS
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