blob: b52e2258d57a40195ae6110868d30076b17b8580 [file] [log] [blame]
Ed Tanousba9f9a62017-10-11 16:40:35 -07001#pragma once
2
Ed Tanousba9f9a62017-10-11 16:40:35 -07003#include <nlohmann/json.hpp>
4#include <pam_authenticate.hpp>
5#include <webassets.hpp>
Borawski.Lukasz16238972018-01-17 15:36:53 +01006#include <random>
Ed Tanousba9f9a62017-10-11 16:40:35 -07007#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 {
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010018
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
Ed Tanousba9f9a62017-10-11 16:40:35 -070024struct UserSession {
25 std::string unique_id;
26 std::string session_token;
27 std::string username;
28 std::string csrf_token;
Ed Tanousc963aa42017-10-27 16:00:19 -070029 std::chrono::time_point<std::chrono::steady_clock> last_updated;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010030 PersistenceType persistence;
Ed Tanousba9f9a62017-10-11 16:40:35 -070031};
32
33void to_json(nlohmann::json& j, const UserSession& p) {
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010034 if (p.persistence != PersistenceType::SINGLE_REQUEST) {
35 j = nlohmann::json{{"unique_id", p.unique_id},
36 {"session_token", p.session_token},
37 {"username", p.username},
38 {"csrf_token", p.csrf_token}};
39 }
Ed Tanousba9f9a62017-10-11 16:40:35 -070040}
41
42void from_json(const nlohmann::json& j, UserSession& p) {
43 try {
44 p.unique_id = j.at("unique_id").get<std::string>();
45 p.session_token = j.at("session_token").get<std::string>();
46 p.username = j.at("username").get<std::string>();
47 p.csrf_token = j.at("csrf_token").get<std::string>();
Ed Tanousc963aa42017-10-27 16:00:19 -070048 // For now, sessions that were persisted through a reboot get their timer
49 // reset. This could probably be overcome with a better understanding of
50 // wall clock time and steady timer time, possibly persisting values with
51 // wall clock time instead of steady timer, but the tradeoffs of all the
52 // corner cases involved are non-trivial, so this is done temporarily
53 p.last_updated = std::chrono::steady_clock::now();
Ed Tanousba9f9a62017-10-11 16:40:35 -070054 } catch (std::out_of_range) {
55 // do nothing. Session API incompatibility, leave sessions empty
56 }
57}
58
Ed Tanousc963aa42017-10-27 16:00:19 -070059class Middleware;
Ed Tanousba9f9a62017-10-11 16:40:35 -070060
Ed Tanousc963aa42017-10-27 16:00:19 -070061class SessionStore {
Ed Tanousba9f9a62017-10-11 16:40:35 -070062 public:
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010063 const UserSession& generate_user_session(
64 const std::string& username,
65 PersistenceType persistence = PersistenceType::TIMEOUT) {
66 // TODO(ed) find a secure way to not generate session identifiers if
67 // persistence is set to SINGLE_REQUEST
Ed Tanousba9f9a62017-10-11 16:40:35 -070068 static constexpr std::array<char, 62> alphanum = {
69 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
70 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
71 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
72 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
73 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
74
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010075 // entropy: 30 characters, 62 possibilities. log2(62^30) = 178 bits of
Ed Tanousba9f9a62017-10-11 16:40:35 -070076 // entropy. OWASP recommends at least 60
77 // https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Session_ID_Entropy
78 std::string session_token;
79 session_token.resize(20, '0');
80 std::uniform_int_distribution<int> dist(0, alphanum.size() - 1);
81 for (int i = 0; i < session_token.size(); ++i) {
82 session_token[i] = alphanum[dist(rd)];
83 }
84 // Only need csrf tokens for cookie based auth, token doesn't matter
85 std::string csrf_token;
86 csrf_token.resize(20, '0');
87 for (int i = 0; i < csrf_token.size(); ++i) {
88 csrf_token[i] = alphanum[dist(rd)];
89 }
90
91 std::string unique_id;
92 unique_id.resize(10, '0');
93 for (int i = 0; i < unique_id.size(); ++i) {
94 unique_id[i] = alphanum[dist(rd)];
95 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010096
Ed Tanousc963aa42017-10-27 16:00:19 -070097 const auto session_it = auth_tokens.emplace(
98 session_token,
99 std::move(UserSession{unique_id, session_token, username, csrf_token,
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100100 std::chrono::steady_clock::now(), persistence}));
Ed Tanousc963aa42017-10-27 16:00:19 -0700101 const UserSession& user = (session_it).first->second;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100102 // Only need to write to disk if session isn't about to be destroyed.
103 need_write_ = persistence == PersistenceType::TIMEOUT;
Ed Tanousc963aa42017-10-27 16:00:19 -0700104 return user;
Ed Tanousba9f9a62017-10-11 16:40:35 -0700105 }
106
Ed Tanousc963aa42017-10-27 16:00:19 -0700107 const UserSession* login_session_by_token(const std::string& token) {
108 apply_session_timeouts();
109 auto session_it = auth_tokens.find(token);
110 if (session_it == auth_tokens.end()) {
111 return nullptr;
112 }
113 UserSession& foo = session_it->second;
114 foo.last_updated = std::chrono::steady_clock::now();
115 return &foo;
116 }
117
118 const UserSession* get_session_by_uid(const std::string& uid) {
119 apply_session_timeouts();
120 // TODO(Ed) this is inefficient
121 auto session_it = auth_tokens.begin();
122 while (session_it != auth_tokens.end()) {
123 if (session_it->second.unique_id == uid) {
124 return &session_it->second;
125 }
126 session_it++;
127 }
128 return nullptr;
129 }
130
131 void remove_session(const UserSession* session) {
132 auth_tokens.erase(session->session_token);
133 need_write_ = true;
134 }
135
136 std::vector<const std::string*> get_unique_ids() {
137 std::vector<const std::string*> ret;
138 ret.reserve(auth_tokens.size());
139 for (auto& session : auth_tokens) {
140 ret.push_back(&session.second.unique_id);
141 }
142 return ret;
143 }
144
145 bool needs_write() { return need_write_; }
146
147 // Persistent data middleware needs to be able to serialize our auth_tokens
148 // structure, which is private
149 friend Middleware;
150
151 private:
152 void apply_session_timeouts() {
153 std::chrono::minutes timeout(60);
154 auto time_now = std::chrono::steady_clock::now();
155 if (time_now - last_timeout_update > std::chrono::minutes(1)) {
156 last_timeout_update = time_now;
157 auto auth_tokens_it = auth_tokens.begin();
158 while (auth_tokens_it != auth_tokens.end()) {
159 if (time_now - auth_tokens_it->second.last_updated >= timeout) {
160 auth_tokens_it = auth_tokens.erase(auth_tokens_it);
161 need_write_ = true;
162 } else {
163 auth_tokens_it++;
164 }
165 }
166 }
167 }
168 std::chrono::time_point<std::chrono::steady_clock> last_timeout_update;
169 boost::container::flat_map<std::string, UserSession> auth_tokens;
Ed Tanousba9f9a62017-10-11 16:40:35 -0700170 std::random_device rd;
Ed Tanousc963aa42017-10-27 16:00:19 -0700171 bool need_write_{false};
172};
173
174class Middleware {
175 // todo(ed) should read this from a fixed location somewhere, not CWD
176 static constexpr const char* filename = "bmcweb_persistent_data.json";
177 int json_revision = 1;
178
179 public:
180 struct context {
181 SessionStore* sessions;
182 };
183
184 Middleware() { read_data(); }
185
186 ~Middleware() {
187 if (sessions.needs_write()) {
188 write_data();
189 }
190 }
191
192 void before_handle(crow::request& req, response& res, context& ctx) {
193 ctx.sessions = &sessions;
194 }
195
196 void after_handle(request& req, response& res, context& ctx) {}
197
198 // TODO(ed) this should really use protobuf, or some other serialization
199 // library, but adding another dependency is somewhat outside the scope of
200 // this application for the moment
201 void read_data() {
202 std::ifstream persistent_file(filename);
203 int file_revision = 0;
204 if (persistent_file.is_open()) {
205 // call with exceptions disabled
206 auto data = nlohmann::json::parse(persistent_file, nullptr, false);
207 if (!data.is_discarded()) {
208 file_revision = data.value("revision", 0);
209 sessions.auth_tokens =
210 data.value("sessions", decltype(sessions.auth_tokens)());
211 system_uuid = data.value("system_uuid", "");
212 }
213 }
214 bool need_write = false;
215
216 if (system_uuid.empty()) {
217 system_uuid = boost::uuids::to_string(boost::uuids::random_generator()());
218 need_write = true;
219 }
220 if (file_revision < json_revision) {
221 need_write = true;
222 }
223 // write revision changes or system uuid changes immediately
224 if (need_write) {
225 write_data();
226 }
227 }
228
229 void write_data() {
230 std::ofstream persistent_file(filename);
231 nlohmann::json data;
232 data["sessions"] = sessions.auth_tokens;
233 data["system_uuid"] = system_uuid;
234 data["revision"] = json_revision;
235 persistent_file << data;
236 }
237
238 SessionStore sessions;
239 std::string system_uuid;
Ed Tanousba9f9a62017-10-11 16:40:35 -0700240};
241
242} // namespaec PersistentData
243} // namespace crow