xref: /openbmc/bmcweb/include/sessions.hpp (revision d78572018fc2022091ff8b8eb5a7fef2172ba3d6)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 
5 #include "bmcweb_config.h"
6 
7 #include "logging.hpp"
8 #include "ossl_random.hpp"
9 #include "utils/ip_utils.hpp"
10 
11 // misc-include-cleaner complains if this isn't included,
12 // modernize-deprecated-headers complains if it is included.
13 // NOLINTNEXTLINE(modernize-deprecated-headers)
14 #include <signal.h>
15 
16 #include <boost/asio/ip/address.hpp>
17 #include <nlohmann/json.hpp>
18 
19 #include <chrono>
20 #include <csignal>
21 #include <cstddef>
22 #include <cstdint>
23 #include <functional>
24 #include <memory>
25 #include <optional>
26 #include <string>
27 #include <string_view>
28 #include <unordered_map>
29 #include <vector>
30 
31 namespace persistent_data
32 {
33 
34 // entropy: 20 characters, 62 possibilities.  log2(62^20) = 119 bits of
35 // entropy.  OWASP recommends at least 64
36 // https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
37 constexpr std::size_t sessionTokenSize = 20;
38 
39 enum class SessionType
40 {
41     None,
42     Basic,
43     Session,
44     Cookie,
45     MutualTLS
46 };
47 
48 struct UserSession
49 {
50     std::string uniqueId;
51     std::string sessionToken;
52     std::string username;
53     std::string csrfToken;
54     std::optional<std::string> clientId;
55     std::string clientIp;
56     std::chrono::time_point<std::chrono::steady_clock> lastUpdated;
57     SessionType sessionType{SessionType::None};
58     bool cookieAuth = false;
59     bool isConfigureSelfOnly = false;
60     std::string userRole;
61     std::vector<std::string> userGroups;
62 
63     // There are two sources of truth for isConfigureSelfOnly:
64     //  1. When pamAuthenticateUser() returns PAM_NEW_AUTHTOK_REQD.
65     //  2. D-Bus User.Manager.GetUserInfo property UserPasswordExpired.
66     // These should be in sync, but the underlying condition can change at any
67     // time.  For example, a password can expire or be changed outside of
68     // bmcweb.  The value stored here is updated at the start of each
69     // operation and used as the truth within bmcweb.
70 
71     /**
72      * @brief Fills object with data from UserSession's JSON representation
73      *
74      * This replaces nlohmann's from_json to ensure no-throw approach
75      *
76      * @param[in] j   JSON object from which data should be loaded
77      *
78      * @return a shared pointer if data has been loaded properly, nullptr
79      * otherwise
80      */
81     static std::shared_ptr<UserSession>
fromJsonpersistent_data::UserSession82         fromJson(const nlohmann::json::object_t& j)
83     {
84         std::shared_ptr<UserSession> userSession =
85             std::make_shared<UserSession>();
86         for (const auto& element : j)
87         {
88             const std::string* thisValue =
89                 element.second.get_ptr<const std::string*>();
90             if (thisValue == nullptr)
91             {
92                 BMCWEB_LOG_ERROR(
93                     "Error reading persistent store.  Property {} was not of type string",
94                     element.first);
95                 continue;
96             }
97             if (element.first == "unique_id")
98             {
99                 userSession->uniqueId = *thisValue;
100             }
101             else if (element.first == "session_token")
102             {
103                 userSession->sessionToken = *thisValue;
104             }
105             else if (element.first == "csrf_token")
106             {
107                 userSession->csrfToken = *thisValue;
108             }
109             else if (element.first == "username")
110             {
111                 userSession->username = *thisValue;
112             }
113             else if (element.first == "client_id")
114             {
115                 userSession->clientId = *thisValue;
116             }
117             else if (element.first == "client_ip")
118             {
119                 userSession->clientIp = *thisValue;
120             }
121 
122             else
123             {
124                 BMCWEB_LOG_ERROR(
125                     "Got unexpected property reading persistent file: {}",
126                     element.first);
127                 continue;
128             }
129         }
130         // If any of these fields are missing, we can't restore the session, as
131         // we don't have enough information.  These 4 fields have been present
132         // in every version of this file in bmcwebs history, so any file, even
133         // on upgrade, should have these present
134         if (userSession->uniqueId.empty() || userSession->username.empty() ||
135             userSession->sessionToken.empty() || userSession->csrfToken.empty())
136         {
137             BMCWEB_LOG_DEBUG("Session missing required security "
138                              "information, refusing to restore");
139             return nullptr;
140         }
141 
142         // For now, sessions that were persisted through a reboot get their idle
143         // timer reset.  This could probably be overcome with a better
144         // understanding of wall clock time and steady timer time, possibly
145         // persisting values with wall clock time instead of steady timer, but
146         // the tradeoffs of all the corner cases involved are non-trivial, so
147         // this is done temporarily
148         userSession->lastUpdated = std::chrono::steady_clock::now();
149         userSession->sessionType = SessionType::Session;
150 
151         return userSession;
152     }
153 };
154 
155 enum class MTLSCommonNameParseMode
156 {
157     Invalid = 0,
158     // This section approximately matches Redfish AccountService
159     // CertificateMappingAttribute,  plus bmcweb defined OEM ones.
160     // Note, IDs in this enum must be maintained between versions, as they are
161     // persisted to disk
162     Whole = 1,
163     CommonName = 2,
164     UserPrincipalName = 3,
165 
166     // Intentional gap for future DMTF-defined enums
167 
168     // OEM parsing modes for various OEMs
169     Meta = 100,
170 };
171 
getMTLSCommonNameParseMode(std::string_view name)172 inline MTLSCommonNameParseMode getMTLSCommonNameParseMode(std::string_view name)
173 {
174     if (name == "CommonName")
175     {
176         return MTLSCommonNameParseMode::CommonName;
177     }
178     if (name == "Whole")
179     {
180         // Not yet supported
181         // return MTLSCommonNameParseMode::Whole;
182     }
183     if (name == "UserPrincipalName")
184     {
185         // Not yet supported
186         // return MTLSCommonNameParseMode::UserPrincipalName;
187     }
188     if constexpr (BMCWEB_META_TLS_COMMON_NAME_PARSING)
189     {
190         if (name == "Meta")
191         {
192             return MTLSCommonNameParseMode::Meta;
193         }
194     }
195     return MTLSCommonNameParseMode::Invalid;
196 }
197 
198 struct AuthConfigMethods
199 {
200     // Authentication paths
201     bool basic = BMCWEB_BASIC_AUTH;
202     bool sessionToken = BMCWEB_SESSION_AUTH;
203     bool xtoken = BMCWEB_XTOKEN_AUTH;
204     bool cookie = BMCWEB_COOKIE_AUTH;
205     bool tls = BMCWEB_MUTUAL_TLS_AUTH;
206 
207     // Whether or not unauthenticated TLS should be accepted
208     // true = reject connections if mutual tls is not provided
209     // false = allow connection, and allow user to use other auth method
210     // Always default to false, because root certificates will not
211     // be provisioned at startup
212     bool tlsStrict = false;
213 
214     MTLSCommonNameParseMode mTLSCommonNameParsingMode =
215         getMTLSCommonNameParseMode(
216             BMCWEB_MUTUAL_TLS_COMMON_NAME_PARSING_DEFAULT);
217 
fromJsonpersistent_data::AuthConfigMethods218     void fromJson(const nlohmann::json::object_t& j)
219     {
220         for (const auto& element : j)
221         {
222             const bool* value = element.second.get_ptr<const bool*>();
223             if (value != nullptr)
224             {
225                 if (element.first == "XToken")
226                 {
227                     xtoken = *value;
228                 }
229                 else if (element.first == "Cookie")
230                 {
231                     cookie = *value;
232                 }
233                 else if (element.first == "SessionToken")
234                 {
235                     sessionToken = *value;
236                 }
237                 else if (element.first == "BasicAuth")
238                 {
239                     basic = *value;
240                 }
241                 else if (element.first == "TLS")
242                 {
243                     tls = *value;
244                 }
245                 else if (element.first == "TLSStrict")
246                 {
247                     tlsStrict = *value;
248                 }
249             }
250             const uint64_t* intValue =
251                 element.second.get_ptr<const uint64_t*>();
252             if (intValue != nullptr)
253             {
254                 if (element.first == "MTLSCommonNameParseMode")
255                 {
256                     if (*intValue <= 2 || *intValue == 100)
257                     {
258                         mTLSCommonNameParsingMode =
259                             static_cast<MTLSCommonNameParseMode>(*intValue);
260                     }
261                     else
262                     {
263                         BMCWEB_LOG_ERROR(
264                             "Json value of {} was out of range of the enum.  Ignoring",
265                             *intValue);
266                     }
267                 }
268             }
269         }
270     }
271 };
272 
273 class SessionStore
274 {
275   public:
generateUserSession(std::string_view username,const boost::asio::ip::address & clientIp,const std::optional<std::string> & clientId,SessionType sessionType,bool isConfigureSelfOnly=false)276     std::shared_ptr<UserSession> generateUserSession(
277         std::string_view username, const boost::asio::ip::address& clientIp,
278         const std::optional<std::string>& clientId, SessionType sessionType,
279         bool isConfigureSelfOnly = false)
280     {
281         // Only need csrf tokens for cookie based auth, token doesn't matter
282         std::string sessionToken =
283             bmcweb::getRandomIdOfLength(sessionTokenSize);
284         std::string csrfToken = bmcweb::getRandomIdOfLength(sessionTokenSize);
285         std::string uniqueId = bmcweb::getRandomIdOfLength(10);
286 
287         //
288         if (sessionToken.empty() || csrfToken.empty() || uniqueId.empty())
289         {
290             BMCWEB_LOG_ERROR("Failed to generate session tokens");
291             return nullptr;
292         }
293 
294         auto session = std::make_shared<UserSession>(UserSession{
295             uniqueId,
296             sessionToken,
297             std::string(username),
298             csrfToken,
299             clientId,
300             redfish::ip_util::toString(clientIp),
301             std::chrono::steady_clock::now(),
302             sessionType,
303             false,
304             isConfigureSelfOnly,
305             "",
306             {}});
307         auto it = authTokens.emplace(sessionToken, session);
308         // Only need to write to disk if session isn't about to be destroyed.
309         needWrite = sessionType != SessionType::Basic &&
310                     sessionType != SessionType::MutualTLS;
311         return it.first->second;
312     }
313 
loginSessionByToken(std::string_view token)314     std::shared_ptr<UserSession> loginSessionByToken(std::string_view token)
315     {
316         applySessionTimeouts();
317         if (token.size() != sessionTokenSize)
318         {
319             return nullptr;
320         }
321         auto sessionIt = authTokens.find(std::string(token));
322         if (sessionIt == authTokens.end())
323         {
324             return nullptr;
325         }
326         std::shared_ptr<UserSession> userSession = sessionIt->second;
327         userSession->lastUpdated = std::chrono::steady_clock::now();
328         return userSession;
329     }
330 
getSessionByUid(std::string_view uid)331     std::shared_ptr<UserSession> getSessionByUid(std::string_view uid)
332     {
333         applySessionTimeouts();
334         // TODO(Ed) this is inefficient
335         auto sessionIt = authTokens.begin();
336         while (sessionIt != authTokens.end())
337         {
338             if (sessionIt->second->uniqueId == uid)
339             {
340                 return sessionIt->second;
341             }
342             sessionIt++;
343         }
344         return nullptr;
345     }
346 
removeSession(const std::shared_ptr<UserSession> & session)347     void removeSession(const std::shared_ptr<UserSession>& session)
348     {
349         authTokens.erase(session->sessionToken);
350         needWrite = true;
351     }
352 
getAllUniqueIds()353     std::vector<std::string> getAllUniqueIds()
354     {
355         applySessionTimeouts();
356         std::vector<std::string> ret;
357         ret.reserve(authTokens.size());
358         for (auto& session : authTokens)
359         {
360             ret.push_back(session.second->uniqueId);
361         }
362         return ret;
363     }
364 
getUniqueIdsBySessionType(SessionType type)365     std::vector<std::string> getUniqueIdsBySessionType(SessionType type)
366     {
367         applySessionTimeouts();
368 
369         std::vector<std::string> ret;
370         ret.reserve(authTokens.size());
371         for (auto& session : authTokens)
372         {
373             if (type == session.second->sessionType)
374             {
375                 ret.push_back(session.second->uniqueId);
376             }
377         }
378         return ret;
379     }
380 
getSessions()381     std::vector<std::shared_ptr<UserSession>> getSessions()
382     {
383         std::vector<std::shared_ptr<UserSession>> sessions;
384         sessions.reserve(authTokens.size());
385         for (auto& session : authTokens)
386         {
387             sessions.push_back(session.second);
388         }
389         return sessions;
390     }
391 
removeSessionsByUsername(std::string_view username)392     void removeSessionsByUsername(std::string_view username)
393     {
394         std::erase_if(authTokens, [username](const auto& value) {
395             if (value.second == nullptr)
396             {
397                 return false;
398             }
399             return value.second->username == username;
400         });
401     }
402 
removeSessionsByUsernameExceptSession(std::string_view username,const std::shared_ptr<UserSession> & session)403     void removeSessionsByUsernameExceptSession(
404         std::string_view username, const std::shared_ptr<UserSession>& session)
405     {
406         std::erase_if(authTokens, [username, session](const auto& value) {
407             if (value.second == nullptr)
408             {
409                 return false;
410             }
411 
412             return value.second->username == username &&
413                    value.second->uniqueId != session->uniqueId;
414         });
415     }
416 
updateAuthMethodsConfig(const AuthConfigMethods & config)417     void updateAuthMethodsConfig(const AuthConfigMethods& config)
418     {
419         bool isTLSchanged = (authMethodsConfig.tls != config.tls);
420         authMethodsConfig = config;
421         needWrite = true;
422         if (isTLSchanged)
423         {
424             // recreate socket connections with new settings
425             std::raise(SIGHUP);
426         }
427     }
428 
getAuthMethodsConfig()429     AuthConfigMethods& getAuthMethodsConfig()
430     {
431         return authMethodsConfig;
432     }
433 
needsWrite() const434     bool needsWrite() const
435     {
436         return needWrite;
437     }
getTimeoutInSeconds() const438     int64_t getTimeoutInSeconds() const
439     {
440         return std::chrono::seconds(timeoutInSeconds).count();
441     }
442 
updateSessionTimeout(std::chrono::seconds newTimeoutInSeconds)443     void updateSessionTimeout(std::chrono::seconds newTimeoutInSeconds)
444     {
445         timeoutInSeconds = newTimeoutInSeconds;
446         needWrite = true;
447     }
448 
getInstance()449     static SessionStore& getInstance()
450     {
451         static SessionStore sessionStore;
452         return sessionStore;
453     }
454 
applySessionTimeouts()455     void applySessionTimeouts()
456     {
457         auto timeNow = std::chrono::steady_clock::now();
458         if (timeNow - lastTimeoutUpdate > std::chrono::seconds(1))
459         {
460             lastTimeoutUpdate = timeNow;
461             auto authTokensIt = authTokens.begin();
462             while (authTokensIt != authTokens.end())
463             {
464                 if (timeNow - authTokensIt->second->lastUpdated >=
465                     timeoutInSeconds)
466                 {
467                     authTokensIt = authTokens.erase(authTokensIt);
468 
469                     needWrite = true;
470                 }
471                 else
472                 {
473                     authTokensIt++;
474                 }
475             }
476         }
477     }
478 
479     SessionStore(const SessionStore&) = delete;
480     SessionStore& operator=(const SessionStore&) = delete;
481     SessionStore(SessionStore&&) = delete;
482     SessionStore& operator=(const SessionStore&&) = delete;
483     ~SessionStore() = default;
484 
485     std::unordered_map<std::string, std::shared_ptr<UserSession>,
486                        std::hash<std::string>, bmcweb::ConstantTimeCompare>
487         authTokens;
488 
489     std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate;
490     bool needWrite{false};
491     std::chrono::seconds timeoutInSeconds;
492     AuthConfigMethods authMethodsConfig;
493 
494   private:
SessionStore()495     SessionStore() : timeoutInSeconds(1800) {}
496 };
497 
498 } // namespace persistent_data
499