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 struct AuthConfigMethods 138 { 139 bool basic = BMCWEB_BASIC_AUTH; 140 bool sessionToken = BMCWEB_SESSION_AUTH; 141 bool xtoken = BMCWEB_XTOKEN_AUTH; 142 bool cookie = BMCWEB_COOKIE_AUTH; 143 bool tls = BMCWEB_MUTUAL_TLS_AUTH; 144 145 void fromJson(const nlohmann::json::object_t& j) 146 { 147 for (const auto& element : j) 148 { 149 const bool* value = element.second.get_ptr<const bool*>(); 150 if (value == nullptr) 151 { 152 continue; 153 } 154 155 if (element.first == "XToken") 156 { 157 xtoken = *value; 158 } 159 else if (element.first == "Cookie") 160 { 161 cookie = *value; 162 } 163 else if (element.first == "SessionToken") 164 { 165 sessionToken = *value; 166 } 167 else if (element.first == "BasicAuth") 168 { 169 basic = *value; 170 } 171 else if (element.first == "TLS") 172 { 173 tls = *value; 174 } 175 } 176 } 177 }; 178 179 class SessionStore 180 { 181 public: 182 std::shared_ptr<UserSession> generateUserSession( 183 std::string_view username, const boost::asio::ip::address& clientIp, 184 const std::optional<std::string>& clientId, 185 PersistenceType persistence = PersistenceType::TIMEOUT, 186 bool isConfigureSelfOnly = false) 187 { 188 // Only need csrf tokens for cookie based auth, token doesn't matter 189 std::string sessionToken = 190 bmcweb::getRandomIdOfLength(sessionTokenSize); 191 std::string csrfToken = bmcweb::getRandomIdOfLength(sessionTokenSize); 192 std::string uniqueId = bmcweb::getRandomIdOfLength(10); 193 194 // 195 if (sessionToken.empty() || csrfToken.empty() || uniqueId.empty()) 196 { 197 BMCWEB_LOG_ERROR("Failed to generate session tokens"); 198 return nullptr; 199 } 200 201 auto session = std::make_shared<UserSession>( 202 UserSession{uniqueId, 203 sessionToken, 204 std::string(username), 205 csrfToken, 206 clientId, 207 redfish::ip_util::toString(clientIp), 208 std::chrono::steady_clock::now(), 209 persistence, 210 false, 211 isConfigureSelfOnly, 212 "", 213 {}}); 214 auto it = authTokens.emplace(sessionToken, session); 215 // Only need to write to disk if session isn't about to be destroyed. 216 needWrite = persistence == PersistenceType::TIMEOUT; 217 return it.first->second; 218 } 219 220 std::shared_ptr<UserSession> loginSessionByToken(std::string_view token) 221 { 222 applySessionTimeouts(); 223 if (token.size() != sessionTokenSize) 224 { 225 return nullptr; 226 } 227 auto sessionIt = authTokens.find(std::string(token)); 228 if (sessionIt == authTokens.end()) 229 { 230 return nullptr; 231 } 232 std::shared_ptr<UserSession> userSession = sessionIt->second; 233 userSession->lastUpdated = std::chrono::steady_clock::now(); 234 return userSession; 235 } 236 237 std::shared_ptr<UserSession> getSessionByUid(std::string_view uid) 238 { 239 applySessionTimeouts(); 240 // TODO(Ed) this is inefficient 241 auto sessionIt = authTokens.begin(); 242 while (sessionIt != authTokens.end()) 243 { 244 if (sessionIt->second->uniqueId == uid) 245 { 246 return sessionIt->second; 247 } 248 sessionIt++; 249 } 250 return nullptr; 251 } 252 253 void removeSession(const std::shared_ptr<UserSession>& session) 254 { 255 authTokens.erase(session->sessionToken); 256 needWrite = true; 257 } 258 259 std::vector<const std::string*> getUniqueIds( 260 bool getAll = true, 261 const PersistenceType& type = PersistenceType::SINGLE_REQUEST) 262 { 263 applySessionTimeouts(); 264 265 std::vector<const std::string*> ret; 266 ret.reserve(authTokens.size()); 267 for (auto& session : authTokens) 268 { 269 if (getAll || type == session.second->persistence) 270 { 271 ret.push_back(&session.second->uniqueId); 272 } 273 } 274 return ret; 275 } 276 277 void removeSessionsByUsername(std::string_view username) 278 { 279 std::erase_if(authTokens, [username](const auto& value) { 280 if (value.second == nullptr) 281 { 282 return false; 283 } 284 return value.second->username == username; 285 }); 286 } 287 288 void removeSessionsByUsernameExceptSession( 289 std::string_view username, const std::shared_ptr<UserSession>& session) 290 { 291 std::erase_if(authTokens, [username, session](const auto& value) { 292 if (value.second == nullptr) 293 { 294 return false; 295 } 296 297 return value.second->username == username && 298 value.second->uniqueId != session->uniqueId; 299 }); 300 } 301 302 void updateAuthMethodsConfig(const AuthConfigMethods& config) 303 { 304 bool isTLSchanged = (authMethodsConfig.tls != config.tls); 305 authMethodsConfig = config; 306 needWrite = true; 307 if (isTLSchanged) 308 { 309 // recreate socket connections with new settings 310 std::raise(SIGHUP); 311 } 312 } 313 314 AuthConfigMethods& getAuthMethodsConfig() 315 { 316 return authMethodsConfig; 317 } 318 319 bool needsWrite() const 320 { 321 return needWrite; 322 } 323 int64_t getTimeoutInSeconds() const 324 { 325 return std::chrono::seconds(timeoutInSeconds).count(); 326 } 327 328 void updateSessionTimeout(std::chrono::seconds newTimeoutInSeconds) 329 { 330 timeoutInSeconds = newTimeoutInSeconds; 331 needWrite = true; 332 } 333 334 static SessionStore& getInstance() 335 { 336 static SessionStore sessionStore; 337 return sessionStore; 338 } 339 340 void applySessionTimeouts() 341 { 342 auto timeNow = std::chrono::steady_clock::now(); 343 if (timeNow - lastTimeoutUpdate > std::chrono::seconds(1)) 344 { 345 lastTimeoutUpdate = timeNow; 346 auto authTokensIt = authTokens.begin(); 347 while (authTokensIt != authTokens.end()) 348 { 349 if (timeNow - authTokensIt->second->lastUpdated >= 350 timeoutInSeconds) 351 { 352 authTokensIt = authTokens.erase(authTokensIt); 353 354 needWrite = true; 355 } 356 else 357 { 358 authTokensIt++; 359 } 360 } 361 } 362 } 363 364 SessionStore(const SessionStore&) = delete; 365 SessionStore& operator=(const SessionStore&) = delete; 366 SessionStore(SessionStore&&) = delete; 367 SessionStore& operator=(const SessionStore&&) = delete; 368 ~SessionStore() = default; 369 370 std::unordered_map<std::string, std::shared_ptr<UserSession>, 371 std::hash<std::string>, 372 crow::utility::ConstantTimeCompare> 373 authTokens; 374 375 std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate; 376 bool needWrite{false}; 377 std::chrono::seconds timeoutInSeconds; 378 AuthConfigMethods authMethodsConfig; 379 380 private: 381 SessionStore() : timeoutInSeconds(1800) {} 382 }; 383 384 } // namespace persistent_data 385