xref: /openbmc/bmcweb/include/sessions.hpp (revision 3ce3688a)
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>
64         fromJson(const nlohmann::json::object_t& j)
65     {
66         std::shared_ptr<UserSession> userSession =
67             std::make_shared<UserSession>();
68         for (const auto& element : j)
69         {
70             const std::string* thisValue =
71                 element.second.get_ptr<const std::string*>();
72             if (thisValue == nullptr)
73             {
74                 BMCWEB_LOG_ERROR(
75                     "Error reading persistent store.  Property {} was not of type string",
76                     element.first);
77                 continue;
78             }
79             if (element.first == "unique_id")
80             {
81                 userSession->uniqueId = *thisValue;
82             }
83             else if (element.first == "session_token")
84             {
85                 userSession->sessionToken = *thisValue;
86             }
87             else if (element.first == "csrf_token")
88             {
89                 userSession->csrfToken = *thisValue;
90             }
91             else if (element.first == "username")
92             {
93                 userSession->username = *thisValue;
94             }
95             else if (element.first == "client_id")
96             {
97                 userSession->clientId = *thisValue;
98             }
99             else if (element.first == "client_ip")
100             {
101                 userSession->clientIp = *thisValue;
102             }
103 
104             else
105             {
106                 BMCWEB_LOG_ERROR(
107                     "Got unexpected property reading persistent file: {}",
108                     element.first);
109                 continue;
110             }
111         }
112         // If any of these fields are missing, we can't restore the session, as
113         // we don't have enough information.  These 4 fields have been present
114         // in every version of this file in bmcwebs history, so any file, even
115         // on upgrade, should have these present
116         if (userSession->uniqueId.empty() || userSession->username.empty() ||
117             userSession->sessionToken.empty() || userSession->csrfToken.empty())
118         {
119             BMCWEB_LOG_DEBUG("Session missing required security "
120                              "information, refusing to restore");
121             return nullptr;
122         }
123 
124         // For now, sessions that were persisted through a reboot get their idle
125         // timer reset.  This could probably be overcome with a better
126         // understanding of wall clock time and steady timer time, possibly
127         // persisting values with wall clock time instead of steady timer, but
128         // the tradeoffs of all the corner cases involved are non-trivial, so
129         // this is done temporarily
130         userSession->lastUpdated = std::chrono::steady_clock::now();
131         userSession->persistence = PersistenceType::TIMEOUT;
132 
133         return userSession;
134     }
135 };
136 
137 enum class MTLSCommonNameParseMode
138 {
139     Invalid = 0,
140     // This section approximately matches Redfish AccountService
141     // CertificateMappingAttribute,  plus bmcweb defined OEM ones.
142     // Note, IDs in this enum must be maintained between versions, as they are
143     // persisted to disk
144     Whole = 1,
145     CommonName = 2,
146     UserPrincipalName = 3,
147 
148     // Intentional gap for future DMTF-defined enums
149 
150     // OEM parsing modes for various OEMs
151     Meta = 100,
152 };
153 
154 inline MTLSCommonNameParseMode getMTLSCommonNameParseMode(std::string_view name)
155 {
156     if (name == "CommonName")
157     {
158         return MTLSCommonNameParseMode::CommonName;
159     }
160     if (name == "Whole")
161     {
162         // Not yet supported
163         // return MTLSCommonNameParseMode::Whole;
164     }
165     if (name == "UserPrincipalName")
166     {
167         // Not yet supported
168         // return MTLSCommonNameParseMode::UserPrincipalName;
169     }
170     if constexpr (BMCWEB_META_TLS_COMMON_NAME_PARSING)
171     {
172         if (name == "Meta")
173         {
174             return MTLSCommonNameParseMode::Meta;
175         }
176     }
177     return MTLSCommonNameParseMode::Invalid;
178 }
179 
180 struct AuthConfigMethods
181 {
182     bool basic = BMCWEB_BASIC_AUTH;
183     bool sessionToken = BMCWEB_SESSION_AUTH;
184     bool xtoken = BMCWEB_XTOKEN_AUTH;
185     bool cookie = BMCWEB_COOKIE_AUTH;
186     bool tls = BMCWEB_MUTUAL_TLS_AUTH;
187 
188     MTLSCommonNameParseMode mTLSCommonNameParsingMode =
189         getMTLSCommonNameParseMode(
190             BMCWEB_MUTUAL_TLS_COMMON_NAME_PARSING_DEFAULT);
191 
192     void fromJson(const nlohmann::json::object_t& j)
193     {
194         for (const auto& element : j)
195         {
196             const bool* value = element.second.get_ptr<const bool*>();
197             if (value != nullptr)
198             {
199                 if (element.first == "XToken")
200                 {
201                     xtoken = *value;
202                 }
203                 else if (element.first == "Cookie")
204                 {
205                     cookie = *value;
206                 }
207                 else if (element.first == "SessionToken")
208                 {
209                     sessionToken = *value;
210                 }
211                 else if (element.first == "BasicAuth")
212                 {
213                     basic = *value;
214                 }
215                 else if (element.first == "TLS")
216                 {
217                     tls = *value;
218                 }
219             }
220             const uint64_t* intValue =
221                 element.second.get_ptr<const uint64_t*>();
222             if (intValue != nullptr)
223             {
224                 if (element.first == "MTLSCommonNameParseMode")
225                 {
226                     if (*intValue <= 2 || *intValue == 100)
227                     {
228                         mTLSCommonNameParsingMode =
229                             static_cast<MTLSCommonNameParseMode>(*intValue);
230                     }
231                     else
232                     {
233                         BMCWEB_LOG_ERROR(
234                             "Json value of {} was out of range of the enum.  Ignoring",
235                             *intValue);
236                     }
237                 }
238             }
239         }
240     }
241 };
242 
243 class SessionStore
244 {
245   public:
246     std::shared_ptr<UserSession> generateUserSession(
247         std::string_view username, const boost::asio::ip::address& clientIp,
248         const std::optional<std::string>& clientId,
249         PersistenceType persistence = PersistenceType::TIMEOUT,
250         bool isConfigureSelfOnly = false)
251     {
252         // Only need csrf tokens for cookie based auth, token doesn't matter
253         std::string sessionToken =
254             bmcweb::getRandomIdOfLength(sessionTokenSize);
255         std::string csrfToken = bmcweb::getRandomIdOfLength(sessionTokenSize);
256         std::string uniqueId = bmcweb::getRandomIdOfLength(10);
257 
258         //
259         if (sessionToken.empty() || csrfToken.empty() || uniqueId.empty())
260         {
261             BMCWEB_LOG_ERROR("Failed to generate session tokens");
262             return nullptr;
263         }
264 
265         auto session = std::make_shared<UserSession>(
266             UserSession{uniqueId,
267                         sessionToken,
268                         std::string(username),
269                         csrfToken,
270                         clientId,
271                         redfish::ip_util::toString(clientIp),
272                         std::chrono::steady_clock::now(),
273                         persistence,
274                         false,
275                         isConfigureSelfOnly,
276                         "",
277                         {}});
278         auto it = authTokens.emplace(sessionToken, session);
279         // Only need to write to disk if session isn't about to be destroyed.
280         needWrite = persistence == PersistenceType::TIMEOUT;
281         return it.first->second;
282     }
283 
284     std::shared_ptr<UserSession> loginSessionByToken(std::string_view token)
285     {
286         applySessionTimeouts();
287         if (token.size() != sessionTokenSize)
288         {
289             return nullptr;
290         }
291         auto sessionIt = authTokens.find(std::string(token));
292         if (sessionIt == authTokens.end())
293         {
294             return nullptr;
295         }
296         std::shared_ptr<UserSession> userSession = sessionIt->second;
297         userSession->lastUpdated = std::chrono::steady_clock::now();
298         return userSession;
299     }
300 
301     std::shared_ptr<UserSession> getSessionByUid(std::string_view uid)
302     {
303         applySessionTimeouts();
304         // TODO(Ed) this is inefficient
305         auto sessionIt = authTokens.begin();
306         while (sessionIt != authTokens.end())
307         {
308             if (sessionIt->second->uniqueId == uid)
309             {
310                 return sessionIt->second;
311             }
312             sessionIt++;
313         }
314         return nullptr;
315     }
316 
317     void removeSession(const std::shared_ptr<UserSession>& session)
318     {
319         authTokens.erase(session->sessionToken);
320         needWrite = true;
321     }
322 
323     std::vector<const std::string*> getUniqueIds(
324         bool getAll = true,
325         const PersistenceType& type = PersistenceType::SINGLE_REQUEST)
326     {
327         applySessionTimeouts();
328 
329         std::vector<const std::string*> ret;
330         ret.reserve(authTokens.size());
331         for (auto& session : authTokens)
332         {
333             if (getAll || type == session.second->persistence)
334             {
335                 ret.push_back(&session.second->uniqueId);
336             }
337         }
338         return ret;
339     }
340 
341     void removeSessionsByUsername(std::string_view username)
342     {
343         std::erase_if(authTokens, [username](const auto& value) {
344             if (value.second == nullptr)
345             {
346                 return false;
347             }
348             return value.second->username == username;
349         });
350     }
351 
352     void removeSessionsByUsernameExceptSession(
353         std::string_view username, const std::shared_ptr<UserSession>& session)
354     {
355         std::erase_if(authTokens, [username, session](const auto& value) {
356             if (value.second == nullptr)
357             {
358                 return false;
359             }
360 
361             return value.second->username == username &&
362                    value.second->uniqueId != session->uniqueId;
363         });
364     }
365 
366     void updateAuthMethodsConfig(const AuthConfigMethods& config)
367     {
368         bool isTLSchanged = (authMethodsConfig.tls != config.tls);
369         authMethodsConfig = config;
370         needWrite = true;
371         if (isTLSchanged)
372         {
373             // recreate socket connections with new settings
374             std::raise(SIGHUP);
375         }
376     }
377 
378     AuthConfigMethods& getAuthMethodsConfig()
379     {
380         return authMethodsConfig;
381     }
382 
383     bool needsWrite() const
384     {
385         return needWrite;
386     }
387     int64_t getTimeoutInSeconds() const
388     {
389         return std::chrono::seconds(timeoutInSeconds).count();
390     }
391 
392     void updateSessionTimeout(std::chrono::seconds newTimeoutInSeconds)
393     {
394         timeoutInSeconds = newTimeoutInSeconds;
395         needWrite = true;
396     }
397 
398     static SessionStore& getInstance()
399     {
400         static SessionStore sessionStore;
401         return sessionStore;
402     }
403 
404     void applySessionTimeouts()
405     {
406         auto timeNow = std::chrono::steady_clock::now();
407         if (timeNow - lastTimeoutUpdate > std::chrono::seconds(1))
408         {
409             lastTimeoutUpdate = timeNow;
410             auto authTokensIt = authTokens.begin();
411             while (authTokensIt != authTokens.end())
412             {
413                 if (timeNow - authTokensIt->second->lastUpdated >=
414                     timeoutInSeconds)
415                 {
416                     authTokensIt = authTokens.erase(authTokensIt);
417 
418                     needWrite = true;
419                 }
420                 else
421                 {
422                     authTokensIt++;
423                 }
424             }
425         }
426     }
427 
428     SessionStore(const SessionStore&) = delete;
429     SessionStore& operator=(const SessionStore&) = delete;
430     SessionStore(SessionStore&&) = delete;
431     SessionStore& operator=(const SessionStore&&) = delete;
432     ~SessionStore() = default;
433 
434     std::unordered_map<std::string, std::shared_ptr<UserSession>,
435                        std::hash<std::string>,
436                        crow::utility::ConstantTimeCompare>
437         authTokens;
438 
439     std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate;
440     bool needWrite{false};
441     std::chrono::seconds timeoutInSeconds;
442     AuthConfigMethods authMethodsConfig;
443 
444   private:
445     SessionStore() : timeoutInSeconds(1800) {}
446 };
447 
448 } // namespace persistent_data
449