xref: /openbmc/bmcweb/include/sessions.hpp (revision 3cb42ba0)
1 #pragma once
2 
3 #include "logging.hpp"
4 #include "ossl_random.hpp"
5 #include "utility.hpp"
6 #include "utils/ip_utils.hpp"
7 
8 #include <nlohmann/json.hpp>
9 
10 #include <algorithm>
11 #include <csignal>
12 #include <optional>
13 #include <random>
14 #include <string>
15 
16 namespace persistent_data
17 {
18 
19 // entropy: 20 characters, 62 possibilities.  log2(62^20) = 119 bits of
20 // entropy.  OWASP recommends at least 64
21 // https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
22 constexpr std::size_t sessionTokenSize = 20;
23 
24 enum class PersistenceType
25 {
26     TIMEOUT, // User session times out after a predetermined amount of time
27     SINGLE_REQUEST // User times out once this request is completed.
28 };
29 
30 struct UserSession
31 {
32     std::string uniqueId;
33     std::string sessionToken;
34     std::string username;
35     std::string csrfToken;
36     std::optional<std::string> clientId;
37     std::string clientIp;
38     std::chrono::time_point<std::chrono::steady_clock> lastUpdated;
39     PersistenceType persistence{PersistenceType::TIMEOUT};
40     bool cookieAuth = false;
41     bool isConfigureSelfOnly = false;
42     std::string userRole;
43     std::vector<std::string> userGroups;
44 
45     // There are two sources of truth for isConfigureSelfOnly:
46     //  1. When pamAuthenticateUser() returns PAM_NEW_AUTHTOK_REQD.
47     //  2. D-Bus User.Manager.GetUserInfo property UserPasswordExpired.
48     // These should be in sync, but the underlying condition can change at any
49     // time.  For example, a password can expire or be changed outside of
50     // bmcweb.  The value stored here is updated at the start of each
51     // operation and used as the truth within bmcweb.
52 
53     /**
54      * @brief Fills object with data from UserSession's JSON representation
55      *
56      * This replaces nlohmann's from_json to ensure no-throw approach
57      *
58      * @param[in] j   JSON object from which data should be loaded
59      *
60      * @return a shared pointer if data has been loaded properly, nullptr
61      * otherwise
62      */
63     static std::shared_ptr<UserSession> fromJson(const nlohmann::json& j)
64     {
65         std::shared_ptr<UserSession> userSession =
66             std::make_shared<UserSession>();
67         for (const auto& element : j.items())
68         {
69             const std::string* thisValue =
70                 element.value().get_ptr<const std::string*>();
71             if (thisValue == nullptr)
72             {
73                 BMCWEB_LOG_ERROR(
74                     "Error reading persistent store.  Property {} was not of type string",
75                     element.key());
76                 continue;
77             }
78             if (element.key() == "unique_id")
79             {
80                 userSession->uniqueId = *thisValue;
81             }
82             else if (element.key() == "session_token")
83             {
84                 userSession->sessionToken = *thisValue;
85             }
86             else if (element.key() == "csrf_token")
87             {
88                 userSession->csrfToken = *thisValue;
89             }
90             else if (element.key() == "username")
91             {
92                 userSession->username = *thisValue;
93             }
94             else if (element.key() == "client_id")
95             {
96                 userSession->clientId = *thisValue;
97             }
98             else if (element.key() == "client_ip")
99             {
100                 userSession->clientIp = *thisValue;
101             }
102 
103             else
104             {
105                 BMCWEB_LOG_ERROR(
106                     "Got unexpected property reading persistent file: {}",
107                     element.key());
108                 continue;
109             }
110         }
111         // If any of these fields are missing, we can't restore the session, as
112         // we don't have enough information.  These 4 fields have been present
113         // in every version of this file in bmcwebs history, so any file, even
114         // on upgrade, should have these present
115         if (userSession->uniqueId.empty() || userSession->username.empty() ||
116             userSession->sessionToken.empty() || userSession->csrfToken.empty())
117         {
118             BMCWEB_LOG_DEBUG("Session missing required security "
119                              "information, refusing to restore");
120             return nullptr;
121         }
122 
123         // For now, sessions that were persisted through a reboot get their idle
124         // timer reset.  This could probably be overcome with a better
125         // understanding of wall clock time and steady timer time, possibly
126         // persisting values with wall clock time instead of steady timer, but
127         // the tradeoffs of all the corner cases involved are non-trivial, so
128         // this is done temporarily
129         userSession->lastUpdated = std::chrono::steady_clock::now();
130         userSession->persistence = PersistenceType::TIMEOUT;
131 
132         return userSession;
133     }
134 };
135 
136 struct AuthConfigMethods
137 {
138     bool basic = BMCWEB_BASIC_AUTH;
139     bool sessionToken = BMCWEB_SESSION_AUTH;
140     bool xtoken = BMCWEB_XTOKEN_AUTH;
141     bool cookie = BMCWEB_COOKIE_AUTH;
142     bool tls = BMCWEB_MUTUAL_TLS_AUTH;
143 
144     void fromJson(const nlohmann::json& j)
145     {
146         for (const auto& element : j.items())
147         {
148             const bool* value = element.value().get_ptr<const bool*>();
149             if (value == nullptr)
150             {
151                 continue;
152             }
153 
154             if (element.key() == "XToken")
155             {
156                 xtoken = *value;
157             }
158             else if (element.key() == "Cookie")
159             {
160                 cookie = *value;
161             }
162             else if (element.key() == "SessionToken")
163             {
164                 sessionToken = *value;
165             }
166             else if (element.key() == "BasicAuth")
167             {
168                 basic = *value;
169             }
170             else if (element.key() == "TLS")
171             {
172                 tls = *value;
173             }
174         }
175     }
176 };
177 
178 class SessionStore
179 {
180   public:
181     std::shared_ptr<UserSession> generateUserSession(
182         std::string_view username, const boost::asio::ip::address& clientIp,
183         const std::optional<std::string>& clientId,
184         PersistenceType persistence = PersistenceType::TIMEOUT,
185         bool isConfigureSelfOnly = false)
186     {
187         // Only need csrf tokens for cookie based auth, token doesn't matter
188         std::string sessionToken =
189             bmcweb::getRandomIdOfLength(sessionTokenSize);
190         std::string csrfToken = bmcweb::getRandomIdOfLength(sessionTokenSize);
191         std::string uniqueId = bmcweb::getRandomIdOfLength(10);
192 
193         //
194         if (sessionToken.empty() || csrfToken.empty() || uniqueId.empty())
195         {
196             BMCWEB_LOG_ERROR("Failed to generate session tokens");
197             return nullptr;
198         }
199 
200         auto session = std::make_shared<UserSession>(
201             UserSession{uniqueId,
202                         sessionToken,
203                         std::string(username),
204                         csrfToken,
205                         clientId,
206                         redfish::ip_util::toString(clientIp),
207                         std::chrono::steady_clock::now(),
208                         persistence,
209                         false,
210                         isConfigureSelfOnly,
211                         "",
212                         {}});
213         auto it = authTokens.emplace(sessionToken, session);
214         // Only need to write to disk if session isn't about to be destroyed.
215         needWrite = persistence == PersistenceType::TIMEOUT;
216         return it.first->second;
217     }
218 
219     std::shared_ptr<UserSession> loginSessionByToken(std::string_view token)
220     {
221         applySessionTimeouts();
222         if (token.size() != sessionTokenSize)
223         {
224             return nullptr;
225         }
226         auto sessionIt = authTokens.find(std::string(token));
227         if (sessionIt == authTokens.end())
228         {
229             return nullptr;
230         }
231         std::shared_ptr<UserSession> userSession = sessionIt->second;
232         userSession->lastUpdated = std::chrono::steady_clock::now();
233         return userSession;
234     }
235 
236     std::shared_ptr<UserSession> getSessionByUid(std::string_view uid)
237     {
238         applySessionTimeouts();
239         // TODO(Ed) this is inefficient
240         auto sessionIt = authTokens.begin();
241         while (sessionIt != authTokens.end())
242         {
243             if (sessionIt->second->uniqueId == uid)
244             {
245                 return sessionIt->second;
246             }
247             sessionIt++;
248         }
249         return nullptr;
250     }
251 
252     void removeSession(const std::shared_ptr<UserSession>& session)
253     {
254         authTokens.erase(session->sessionToken);
255         needWrite = true;
256     }
257 
258     std::vector<const std::string*> getUniqueIds(
259         bool getAll = true,
260         const PersistenceType& type = PersistenceType::SINGLE_REQUEST)
261     {
262         applySessionTimeouts();
263 
264         std::vector<const std::string*> ret;
265         ret.reserve(authTokens.size());
266         for (auto& session : authTokens)
267         {
268             if (getAll || type == session.second->persistence)
269             {
270                 ret.push_back(&session.second->uniqueId);
271             }
272         }
273         return ret;
274     }
275 
276     void removeSessionsByUsername(std::string_view username)
277     {
278         std::erase_if(authTokens, [username](const auto& value) {
279             if (value.second == nullptr)
280             {
281                 return false;
282             }
283             return value.second->username == username;
284         });
285     }
286 
287     void removeSessionsByUsernameExceptSession(
288         std::string_view username, const std::shared_ptr<UserSession>& session)
289     {
290         std::erase_if(authTokens, [username, session](const auto& value) {
291             if (value.second == nullptr)
292             {
293                 return false;
294             }
295 
296             return value.second->username == username &&
297                    value.second->uniqueId != session->uniqueId;
298         });
299     }
300 
301     void updateAuthMethodsConfig(const AuthConfigMethods& config)
302     {
303         bool isTLSchanged = (authMethodsConfig.tls != config.tls);
304         authMethodsConfig = config;
305         needWrite = true;
306         if (isTLSchanged)
307         {
308             // recreate socket connections with new settings
309             std::raise(SIGHUP);
310         }
311     }
312 
313     AuthConfigMethods& getAuthMethodsConfig()
314     {
315         return authMethodsConfig;
316     }
317 
318     bool needsWrite() const
319     {
320         return needWrite;
321     }
322     int64_t getTimeoutInSeconds() const
323     {
324         return std::chrono::seconds(timeoutInSeconds).count();
325     }
326 
327     void updateSessionTimeout(std::chrono::seconds newTimeoutInSeconds)
328     {
329         timeoutInSeconds = newTimeoutInSeconds;
330         needWrite = true;
331     }
332 
333     static SessionStore& getInstance()
334     {
335         static SessionStore sessionStore;
336         return sessionStore;
337     }
338 
339     void applySessionTimeouts()
340     {
341         auto timeNow = std::chrono::steady_clock::now();
342         if (timeNow - lastTimeoutUpdate > std::chrono::seconds(1))
343         {
344             lastTimeoutUpdate = timeNow;
345             auto authTokensIt = authTokens.begin();
346             while (authTokensIt != authTokens.end())
347             {
348                 if (timeNow - authTokensIt->second->lastUpdated >=
349                     timeoutInSeconds)
350                 {
351                     authTokensIt = authTokens.erase(authTokensIt);
352 
353                     needWrite = true;
354                 }
355                 else
356                 {
357                     authTokensIt++;
358                 }
359             }
360         }
361     }
362 
363     SessionStore(const SessionStore&) = delete;
364     SessionStore& operator=(const SessionStore&) = delete;
365     SessionStore(SessionStore&&) = delete;
366     SessionStore& operator=(const SessionStore&&) = delete;
367     ~SessionStore() = default;
368 
369     std::unordered_map<std::string, std::shared_ptr<UserSession>,
370                        std::hash<std::string>,
371                        crow::utility::ConstantTimeCompare>
372         authTokens;
373 
374     std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate;
375     bool needWrite{false};
376     std::chrono::seconds timeoutInSeconds;
377     AuthConfigMethods authMethodsConfig;
378 
379   private:
380     SessionStore() : timeoutInSeconds(1800) {}
381 };
382 
383 } // namespace persistent_data
384