blob: b0fe1122b4a8327169596c14f534fd20dd5bac13 [file] [log] [blame]
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +01001#pragma once
2
3#include <nlohmann/json.hpp>
4#include <pam_authenticate.hpp>
5#include <webassets.hpp>
6#include <random>
7#include <crow/app.h>
8#include <crow/http_request.h>
9#include <crow/http_response.h>
10#include <boost/container/flat_map.hpp>
11#include <boost/uuid/uuid.hpp>
12#include <boost/uuid/uuid_generators.hpp>
13#include <boost/uuid/uuid_io.hpp>
14
15namespace crow {
16
17namespace PersistentData {
18
19enum class PersistenceType {
20 TIMEOUT, // User session times out after a predetermined amount of time
21 SINGLE_REQUEST // User times out once this request is completed.
22};
23
24struct UserSession {
25 std::string unique_id;
26 std::string session_token;
27 std::string username;
28 std::string csrf_token;
29 std::chrono::time_point<std::chrono::steady_clock> last_updated;
30 PersistenceType persistence;
Kowalski, Kamil5cef0f72018-02-15 15:26:51 +010031
32 /**
33 * @brief Fills object with data from UserSession's JSON representation
34 *
35 * This replaces nlohmann's from_json to ensure no-throw approach
36 *
37 * @param[in] j JSON object from which data should be loaded
38 *
39 * @return true if data has been loaded properly, false otherwise
40 */
41 bool fromJson(const nlohmann::json& j) {
42 auto jUid = j.find("unique_id");
43 auto jToken = j.find("session_token");
44 auto jUsername = j.find("username");
45 auto jCsrf = j.find("csrf_token");
46
47 // Verify existence
48 if (jUid == j.end() || jToken == j.end() || jUsername == j.end() ||
49 jCsrf == j.end()) {
50 return false;
51 }
52
53 // Verify types
54 if (!jUid->is_string() || !jToken->is_string() || !jUsername->is_string() ||
55 !jCsrf->is_string()) {
56 return false;
57 }
58
59 unique_id = jUid->get<std::string>();
60 session_token = jToken->get<std::string>();
61 username = jUsername->get<std::string>();
62 csrf_token = jCsrf->get<std::string>();
63
64 // For now, sessions that were persisted through a reboot get their timer
65 // reset. This could probably be overcome with a better understanding of
66 // wall clock time and steady timer time, possibly persisting values with
67 // wall clock time instead of steady timer, but the tradeoffs of all the
68 // corner cases involved are non-trivial, so this is done temporarily
69 last_updated = std::chrono::steady_clock::now();
70 persistence = PersistenceType::TIMEOUT;
71
72 return true;
73 }
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +010074};
75
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +010076class Middleware;
77
78class SessionStore {
79 public:
Ed Tanouse0d918b2018-03-27 17:41:04 -070080 std::shared_ptr<UserSession> generate_user_session(
81 const boost::string_view username,
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +010082 PersistenceType persistence = PersistenceType::TIMEOUT) {
83 // TODO(ed) find a secure way to not generate session identifiers if
84 // persistence is set to SINGLE_REQUEST
85 static constexpr std::array<char, 62> alphanum = {
86 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
87 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
88 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
89 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
90 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
91
92 // entropy: 30 characters, 62 possibilities. log2(62^30) = 178 bits of
93 // entropy. OWASP recommends at least 60
94 // https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Session_ID_Entropy
95 std::string session_token;
96 session_token.resize(20, '0');
97 std::uniform_int_distribution<int> dist(0, alphanum.size() - 1);
98 for (int i = 0; i < session_token.size(); ++i) {
99 session_token[i] = alphanum[dist(rd)];
100 }
101 // Only need csrf tokens for cookie based auth, token doesn't matter
102 std::string csrf_token;
103 csrf_token.resize(20, '0');
104 for (int i = 0; i < csrf_token.size(); ++i) {
105 csrf_token[i] = alphanum[dist(rd)];
106 }
107
108 std::string unique_id;
109 unique_id.resize(10, '0');
110 for (int i = 0; i < unique_id.size(); ++i) {
111 unique_id[i] = alphanum[dist(rd)];
112 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700113 auto session = std::make_shared<UserSession>(
114 UserSession{unique_id, session_token, std::string(username), csrf_token,
115 std::chrono::steady_clock::now(), persistence});
116 auto it = auth_tokens.emplace(std::make_pair(session_token, session));
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100117 // Only need to write to disk if session isn't about to be destroyed.
118 need_write_ = persistence == PersistenceType::TIMEOUT;
Ed Tanouse0d918b2018-03-27 17:41:04 -0700119 return it.first->second;
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100120 }
121
Ed Tanouse0d918b2018-03-27 17:41:04 -0700122 std::shared_ptr<UserSession> login_session_by_token(
123 const boost::string_view token) {
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100124 apply_session_timeouts();
Ed Tanouse0d918b2018-03-27 17:41:04 -0700125 auto session_it = auth_tokens.find(std::string(token));
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100126 if (session_it == auth_tokens.end()) {
127 return nullptr;
128 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700129 std::shared_ptr<UserSession> user_session = session_it->second;
130 user_session->last_updated = std::chrono::steady_clock::now();
131 return user_session;
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100132 }
133
Ed Tanouse0d918b2018-03-27 17:41:04 -0700134 std::shared_ptr<UserSession> get_session_by_uid(
135 const boost::string_view uid) {
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100136 apply_session_timeouts();
137 // TODO(Ed) this is inefficient
138 auto session_it = auth_tokens.begin();
139 while (session_it != auth_tokens.end()) {
Ed Tanouse0d918b2018-03-27 17:41:04 -0700140 if (session_it->second->unique_id == uid) {
141 return session_it->second;
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100142 }
143 session_it++;
144 }
145 return nullptr;
146 }
147
Ed Tanouse0d918b2018-03-27 17:41:04 -0700148 void remove_session(std::shared_ptr<UserSession> session) {
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100149 auth_tokens.erase(session->session_token);
150 need_write_ = true;
151 }
152
153 std::vector<const std::string*> get_unique_ids(
154 bool getAll = true,
155 const PersistenceType& type = PersistenceType::SINGLE_REQUEST) {
156 apply_session_timeouts();
157
158 std::vector<const std::string*> ret;
159 ret.reserve(auth_tokens.size());
160 for (auto& session : auth_tokens) {
Ed Tanouse0d918b2018-03-27 17:41:04 -0700161 if (getAll || type == session.second->persistence) {
162 ret.push_back(&session.second->unique_id);
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100163 }
164 }
165 return ret;
166 }
167
168 bool needs_write() { return need_write_; }
Borawski.Lukasz5d27b852018-02-08 13:24:24 +0100169 int get_timeout_in_seconds() const {
170 return std::chrono::seconds(timeout_in_minutes).count();
171 };
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100172
173 // Persistent data middleware needs to be able to serialize our auth_tokens
174 // structure, which is private
175 friend Middleware;
176
Borawski.Lukasz4b1b8682018-04-04 12:50:16 +0200177 static SessionStore& getInstance() {
178 static SessionStore sessionStore;
179 return sessionStore;
180 }
181
182 SessionStore(const SessionStore&) = delete;
183 SessionStore& operator=(const SessionStore&) = delete;
184
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100185 private:
Borawski.Lukasz4b1b8682018-04-04 12:50:16 +0200186 SessionStore() : timeout_in_minutes(60) {}
187
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100188 void apply_session_timeouts() {
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100189 auto time_now = std::chrono::steady_clock::now();
190 if (time_now - last_timeout_update > std::chrono::minutes(1)) {
191 last_timeout_update = time_now;
192 auto auth_tokens_it = auth_tokens.begin();
193 while (auth_tokens_it != auth_tokens.end()) {
Ed Tanouse0d918b2018-03-27 17:41:04 -0700194 if (time_now - auth_tokens_it->second->last_updated >=
Borawski.Lukasz5d27b852018-02-08 13:24:24 +0100195 timeout_in_minutes) {
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100196 auth_tokens_it = auth_tokens.erase(auth_tokens_it);
197 need_write_ = true;
198 } else {
199 auth_tokens_it++;
200 }
201 }
202 }
203 }
204 std::chrono::time_point<std::chrono::steady_clock> last_timeout_update;
Ed Tanouse0d918b2018-03-27 17:41:04 -0700205 boost::container::flat_map<std::string, std::shared_ptr<UserSession>>
206 auth_tokens;
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100207 std::random_device rd;
208 bool need_write_{false};
Borawski.Lukasz5d27b852018-02-08 13:24:24 +0100209 std::chrono::minutes timeout_in_minutes;
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100210};
211
Ed Tanouse0d918b2018-03-27 17:41:04 -0700212} // namespace PersistentData
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +0100213} // namespace crow
Borawski.Lukasz4b1b8682018-04-04 12:50:16 +0200214
215// to_json(...) definition for objects of UserSession type
216namespace nlohmann {
217template <>
218struct adl_serializer<std::shared_ptr<crow::PersistentData::UserSession>> {
219 static void to_json(
220 nlohmann::json& j,
221 const std::shared_ptr<crow::PersistentData::UserSession>& p) {
222 if (p->persistence !=
223 crow::PersistentData::PersistenceType::SINGLE_REQUEST) {
224 j = nlohmann::json{{"unique_id", p->unique_id},
225 {"session_token", p->session_token},
226 {"username", p->username},
227 {"csrf_token", p->csrf_token}};
228 }
229 }
230};
231} // namespace nlohmann