1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
4 #pragma once
5
6 #include "account_service.hpp"
7 #include "app.hpp"
8 #include "async_resp.hpp"
9 #include "cookies.hpp"
10 #include "dbus_privileges.hpp"
11 #include "error_messages.hpp"
12 #include "http_request.hpp"
13 #include "http_response.hpp"
14 #include "pam_authenticate.hpp"
15 #include "privileges.hpp"
16 #include "query.hpp"
17 #include "registries/privilege_registry.hpp"
18 #include "sessions.hpp"
19 #include "utils/json_utils.hpp"
20
21 #include <security/_pam_types.h>
22
23 #include <boost/beast/http/field.hpp>
24 #include <boost/beast/http/status.hpp>
25 #include <boost/beast/http/verb.hpp>
26 #include <boost/url/format.hpp>
27
28 #include <chrono>
29 #include <cstdint>
30 #include <functional>
31 #include <memory>
32 #include <optional>
33 #include <string>
34 #include <utility>
35 #include <vector>
36
37 namespace redfish
38 {
39
fillSessionObject(crow::Response & res,const persistent_data::UserSession & session)40 inline void fillSessionObject(crow::Response& res,
41 const persistent_data::UserSession& session)
42 {
43 res.jsonValue["Id"] = session.uniqueId;
44 res.jsonValue["UserName"] = session.username;
45 nlohmann::json::array_t roles;
46 roles.emplace_back(redfish::getRoleIdFromPrivilege(session.userRole));
47 res.jsonValue["Roles"] = std::move(roles);
48 res.jsonValue["@odata.id"] = boost::urls::format(
49 "/redfish/v1/SessionService/Sessions/{}", session.uniqueId);
50 res.jsonValue["@odata.type"] = "#Session.v1_7_0.Session";
51 res.jsonValue["Name"] = "User Session";
52 res.jsonValue["Description"] = "Manager User Session";
53 res.jsonValue["ClientOriginIPAddress"] = session.clientIp;
54 if (session.clientId)
55 {
56 res.jsonValue["Context"] = *session.clientId;
57 }
58 }
59
handleSessionHead(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const std::string &)60 inline void handleSessionHead(
61 crow::App& app, const crow::Request& req,
62 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
63 const std::string& /*sessionId*/)
64 {
65 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
66 {
67 return;
68 }
69 asyncResp->res.addHeader(
70 boost::beast::http::field::link,
71 "</redfish/v1/JsonSchemas/Session/Session.json>; rel=describedby");
72 }
73
handleSessionGet(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const std::string & sessionId)74 inline void handleSessionGet(
75 crow::App& app, const crow::Request& req,
76 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
77 const std::string& sessionId)
78 {
79 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
80 {
81 return;
82 }
83 asyncResp->res.addHeader(
84 boost::beast::http::field::link,
85 "</redfish/v1/JsonSchemas/Session/Session.json>; rel=describedby");
86
87 // Note that control also reaches here via doPost and doDelete.
88 auto session =
89 persistent_data::SessionStore::getInstance().getSessionByUid(sessionId);
90
91 if (session == nullptr)
92 {
93 messages::resourceNotFound(asyncResp->res, "Session", sessionId);
94 return;
95 }
96
97 fillSessionObject(asyncResp->res, *session);
98 }
99
handleSessionDelete(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const std::string & sessionId)100 inline void handleSessionDelete(
101 crow::App& app, const crow::Request& req,
102 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
103 const std::string& sessionId)
104 {
105 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
106 {
107 return;
108 }
109 auto session =
110 persistent_data::SessionStore::getInstance().getSessionByUid(sessionId);
111
112 if (session == nullptr)
113 {
114 messages::resourceNotFound(asyncResp->res, "Session", sessionId);
115 return;
116 }
117
118 // Perform a proper ConfigureSelf authority check. If a
119 // session is being used to DELETE some other user's session,
120 // then the ConfigureSelf privilege does not apply. In that
121 // case, perform the authority check again without the user's
122 // ConfigureSelf privilege.
123 if (req.session != nullptr && !session->username.empty() &&
124 session->username != req.session->username)
125 {
126 Privileges effectiveUserPrivileges =
127 redfish::getUserPrivileges(*req.session);
128
129 if (!effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"}))
130 {
131 messages::insufficientPrivilege(asyncResp->res);
132 return;
133 }
134 }
135
136 if (req.session != nullptr && req.session->uniqueId == sessionId &&
137 session->cookieAuth)
138 {
139 bmcweb::clearSessionCookies(asyncResp->res);
140 }
141
142 persistent_data::SessionStore::getInstance().removeSession(session);
143 messages::success(asyncResp->res);
144 }
145
getSessionCollectionMembers()146 inline nlohmann::json getSessionCollectionMembers()
147 {
148 std::vector<std::string> sessionIds =
149 persistent_data::SessionStore::getInstance().getAllUniqueIds();
150 nlohmann::json ret = nlohmann::json::array();
151 for (const std::string& uid : sessionIds)
152 {
153 nlohmann::json::object_t session;
154 session["@odata.id"] =
155 boost::urls::format("/redfish/v1/SessionService/Sessions/{}", uid);
156 ret.emplace_back(std::move(session));
157 }
158 return ret;
159 }
160
handleSessionCollectionHead(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)161 inline void handleSessionCollectionHead(
162 crow::App& app, const crow::Request& req,
163 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
164 {
165 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
166 {
167 return;
168 }
169 asyncResp->res.addHeader(
170 boost::beast::http::field::link,
171 "</redfish/v1/JsonSchemas/SessionCollection.json>; rel=describedby");
172 }
173
handleSessionCollectionGet(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)174 inline void handleSessionCollectionGet(
175 crow::App& app, const crow::Request& req,
176 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
177 {
178 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
179 {
180 return;
181 }
182 asyncResp->res.addHeader(
183 boost::beast::http::field::link,
184 "</redfish/v1/JsonSchemas/SessionCollection.json>; rel=describedby");
185
186 asyncResp->res.jsonValue["Members"] = getSessionCollectionMembers();
187 asyncResp->res.jsonValue["Members@odata.count"] =
188 asyncResp->res.jsonValue["Members"].size();
189 asyncResp->res.jsonValue["@odata.type"] =
190 "#SessionCollection.SessionCollection";
191 asyncResp->res.jsonValue["@odata.id"] =
192 "/redfish/v1/SessionService/Sessions";
193 asyncResp->res.jsonValue["Name"] = "Session Collection";
194 asyncResp->res.jsonValue["Description"] = "Session Collection";
195 }
196
processAfterSessionCreation(const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const crow::Request & req,const std::string & username,std::shared_ptr<persistent_data::UserSession> & session)197 inline void processAfterSessionCreation(
198 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
199 const crow::Request& req, const std::string& username,
200 std::shared_ptr<persistent_data::UserSession>& session)
201 {
202 // When session is created by webui-vue give it session cookies as a
203 // non-standard Redfish extension. This is needed for authentication for
204 // WebSockets-based functionality.
205 if (!req.getHeaderValue("X-Requested-With").empty())
206 {
207 bmcweb::setSessionCookies(asyncResp->res, *session);
208 }
209 else
210 {
211 asyncResp->res.addHeader("X-Auth-Token", session->sessionToken);
212 }
213
214 asyncResp->res.addHeader(
215 "Location", "/redfish/v1/SessionService/Sessions/" + session->uniqueId);
216 asyncResp->res.result(boost::beast::http::status::created);
217 if (session->isConfigureSelfOnly)
218 {
219 boost::urls::url url = boost::urls::format(
220 "/redfish/v1/AccountService/Accounts/{}", session->username);
221 messages::addMessageToJsonRoot(asyncResp->res.jsonValue,
222 messages::passwordChangeRequired(url));
223 }
224
225 crow::getUserInfo(asyncResp, username, session, [asyncResp, session]() {
226 fillSessionObject(asyncResp->res, *session);
227 });
228 }
229
handleSessionCollectionPost(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)230 inline void handleSessionCollectionPost(
231 crow::App& app, const crow::Request& req,
232 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
233 {
234 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
235 {
236 return;
237 }
238 std::string username;
239 std::string password;
240 std::optional<std::string> clientId;
241 std::optional<std::string> token;
242 if (!json_util::readJsonPatch( //
243 req, asyncResp->res, //
244 "Context", clientId, //
245 "Password", password, //
246 "Token", token, //
247 "UserName", username //
248 ))
249 {
250 return;
251 }
252 if (password.empty() || username.empty() ||
253 asyncResp->res.result() != boost::beast::http::status::ok)
254 {
255 if (username.empty())
256 {
257 messages::propertyMissing(asyncResp->res, "UserName");
258 }
259
260 if (password.empty())
261 {
262 messages::propertyMissing(asyncResp->res, "Password");
263 }
264
265 return;
266 }
267
268 int pamrc = pamAuthenticateUser(username, password, token);
269 bool isConfigureSelfOnly = pamrc == PAM_NEW_AUTHTOK_REQD;
270 if ((pamrc != PAM_SUCCESS) && !isConfigureSelfOnly)
271 {
272 messages::resourceAtUriUnauthorized(asyncResp->res, req.url(),
273 "Invalid username or password");
274 return;
275 }
276
277 // User is authenticated - create session
278 std::shared_ptr<persistent_data::UserSession> session =
279 persistent_data::SessionStore::getInstance().generateUserSession(
280 username, req.ipAddress, clientId,
281 persistent_data::SessionType::Session, isConfigureSelfOnly);
282 if (session == nullptr)
283 {
284 messages::internalError(asyncResp->res);
285 return;
286 }
287 processAfterSessionCreation(asyncResp, req, username, session);
288 }
289
handleSessionServiceHead(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)290 inline void handleSessionServiceHead(
291 crow::App& app, const crow::Request& req,
292 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
293 {
294 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
295 {
296 return;
297 }
298 asyncResp->res.addHeader(
299 boost::beast::http::field::link,
300 "</redfish/v1/JsonSchemas/SessionService/SessionService.json>; rel=describedby");
301 }
handleSessionServiceGet(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)302 inline void handleSessionServiceGet(
303 crow::App& app, const crow::Request& req,
304 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
305
306 {
307 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
308 {
309 return;
310 }
311 asyncResp->res.addHeader(
312 boost::beast::http::field::link,
313 "</redfish/v1/JsonSchemas/SessionService/SessionService.json>; rel=describedby");
314
315 asyncResp->res.jsonValue["@odata.type"] =
316 "#SessionService.v1_0_2.SessionService";
317 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/SessionService";
318 asyncResp->res.jsonValue["Name"] = "Session Service";
319 asyncResp->res.jsonValue["Id"] = "SessionService";
320 asyncResp->res.jsonValue["Description"] = "Session Service";
321 asyncResp->res.jsonValue["SessionTimeout"] =
322 persistent_data::SessionStore::getInstance().getTimeoutInSeconds();
323 asyncResp->res.jsonValue["ServiceEnabled"] = true;
324
325 asyncResp->res.jsonValue["Sessions"]["@odata.id"] =
326 "/redfish/v1/SessionService/Sessions";
327 }
328
handleSessionServicePatch(crow::App & app,const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)329 inline void handleSessionServicePatch(
330 crow::App& app, const crow::Request& req,
331 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
332 {
333 if (!redfish::setUpRedfishRoute(app, req, asyncResp))
334 {
335 return;
336 }
337 std::optional<int64_t> sessionTimeout;
338 if (!json_util::readJsonPatch( //
339 req, asyncResp->res, //
340 "SessionTimeout", sessionTimeout //
341 ))
342 {
343 return;
344 }
345
346 if (sessionTimeout)
347 {
348 // The minimum & maximum allowed values for session timeout
349 // are 30 seconds and 86400 seconds respectively as per the
350 // session service schema mentioned at
351 // https://redfish.dmtf.org/schemas/v1/SessionService.v1_1_7.json
352
353 if (*sessionTimeout <= 86400 && *sessionTimeout >= 30)
354 {
355 std::chrono::seconds sessionTimeoutInseconds(*sessionTimeout);
356 persistent_data::SessionStore::getInstance().updateSessionTimeout(
357 sessionTimeoutInseconds);
358 messages::propertyValueModified(asyncResp->res, "SessionTimeOut",
359 std::to_string(*sessionTimeout));
360 }
361 else
362 {
363 messages::propertyValueNotInList(asyncResp->res, *sessionTimeout,
364 "SessionTimeOut");
365 }
366 }
367 }
368
requestRoutesSession(App & app)369 inline void requestRoutesSession(App& app)
370 {
371 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/<str>/")
372 .privileges(redfish::privileges::headSession)
373 .methods(boost::beast::http::verb::head)(
374 std::bind_front(handleSessionHead, std::ref(app)));
375
376 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/<str>/")
377 .privileges(redfish::privileges::getSession)
378 .methods(boost::beast::http::verb::get)(
379 std::bind_front(handleSessionGet, std::ref(app)));
380
381 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/<str>/")
382 .privileges(redfish::privileges::deleteSession)
383 .methods(boost::beast::http::verb::delete_)(
384 std::bind_front(handleSessionDelete, std::ref(app)));
385
386 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/")
387 .privileges(redfish::privileges::headSessionCollection)
388 .methods(boost::beast::http::verb::head)(
389 std::bind_front(handleSessionCollectionHead, std::ref(app)));
390
391 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/")
392 .privileges(redfish::privileges::getSessionCollection)
393 .methods(boost::beast::http::verb::get)(
394 std::bind_front(handleSessionCollectionGet, std::ref(app)));
395
396 // Note, the next two routes technically don't match the privilege
397 // registry given the way login mechanisms work. The base privilege
398 // registry lists this endpoint as requiring login privilege, but because
399 // this is the endpoint responsible for giving the login privilege, and it
400 // is itself its own route, it needs to not require Login
401 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/")
402 .privileges({})
403 .methods(boost::beast::http::verb::post)(
404 std::bind_front(handleSessionCollectionPost, std::ref(app)));
405
406 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/Members/")
407 .privileges({})
408 .methods(boost::beast::http::verb::post)(
409 std::bind_front(handleSessionCollectionPost, std::ref(app)));
410
411 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/")
412 .privileges(redfish::privileges::headSessionService)
413 .methods(boost::beast::http::verb::head)(
414 std::bind_front(handleSessionServiceHead, std::ref(app)));
415
416 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/")
417 .privileges(redfish::privileges::getSessionService)
418 .methods(boost::beast::http::verb::get)(
419 std::bind_front(handleSessionServiceGet, std::ref(app)));
420
421 BMCWEB_ROUTE(app, "/redfish/v1/SessionService/")
422 .privileges(redfish::privileges::patchSessionService)
423 .methods(boost::beast::http::verb::patch)(
424 std::bind_front(handleSessionServicePatch, std::ref(app)));
425 }
426
427 } // namespace redfish
428