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