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 "error_messages.hpp"
19 #include "persistent_data.hpp"
20 
21 #include <app.hpp>
22 #include <http/utility.hpp>
23 #include <query.hpp>
24 #include <registries/privilege_registry.hpp>
25 #include <utils/json_utils.hpp>
26 
27 namespace redfish
28 {
29 
30 inline void fillSessionObject(crow::Response& res,
31                               const persistent_data::UserSession& session)
32 {
33     res.jsonValue["Id"] = session.uniqueId;
34     res.jsonValue["UserName"] = session.username;
35     res.jsonValue["@odata.id"] =
36         "/redfish/v1/SessionService/Sessions/" + session.uniqueId;
37     res.jsonValue["@odata.type"] = "#Session.v1_3_0.Session";
38     res.jsonValue["Name"] = "User Session";
39     res.jsonValue["Description"] = "Manager User Session";
40     res.jsonValue["ClientOriginIPAddress"] = session.clientIp;
41 #ifdef BMCWEB_ENABLE_IBM_MANAGEMENT_CONSOLE
42     res.jsonValue["Oem"]["OpenBMC"]["@odata.type"] =
43         "#OemSession.v1_0_0.Session";
44     res.jsonValue["Oem"]["OpenBMC"]["ClientID"] = session.clientId;
45 #endif
46 }
47 
48 inline void
49     handleSessionGet(crow::App& app, const crow::Request& req,
50                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
51                      const std::string& sessionId)
52 {
53     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
54     {
55         return;
56     }
57     // Note that control also reaches here via doPost and doDelete.
58     auto session =
59         persistent_data::SessionStore::getInstance().getSessionByUid(sessionId);
60 
61     if (session == nullptr)
62     {
63         messages::resourceNotFound(asyncResp->res, "Session", sessionId);
64         return;
65     }
66 
67     fillSessionObject(asyncResp->res, *session);
68 }
69 
70 inline void
71     handleSessionDelete(crow::App& app, const crow::Request& req,
72                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
73                         const std::string& sessionId)
74 {
75     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
76     {
77         return;
78     }
79     auto session =
80         persistent_data::SessionStore::getInstance().getSessionByUid(sessionId);
81 
82     if (session == nullptr)
83     {
84         messages::resourceNotFound(asyncResp->res, "Session", sessionId);
85         return;
86     }
87 
88     // Perform a proper ConfigureSelf authority check.  If a
89     // session is being used to DELETE some other user's session,
90     // then the ConfigureSelf privilege does not apply.  In that
91     // case, perform the authority check again without the user's
92     // ConfigureSelf privilege.
93     if (req.session != nullptr && !session->username.empty() &&
94         session->username != req.session->username)
95     {
96         Privileges effectiveUserPrivileges =
97             redfish::getUserPrivileges(req.userRole);
98 
99         if (!effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"}))
100         {
101             messages::insufficientPrivilege(asyncResp->res);
102             return;
103         }
104     }
105 
106     persistent_data::SessionStore::getInstance().removeSession(session);
107     messages::success(asyncResp->res);
108 }
109 
110 inline nlohmann::json getSessionCollectionMembers()
111 {
112     std::vector<const std::string*> sessionIds =
113         persistent_data::SessionStore::getInstance().getUniqueIds(
114             false, persistent_data::PersistenceType::TIMEOUT);
115     nlohmann::json ret = nlohmann::json::array();
116     for (const std::string* uid : sessionIds)
117     {
118         nlohmann::json::object_t session;
119         session["@odata.id"] = "/redfish/v1/SessionService/Sessions/" + *uid;
120         ret.push_back(std::move(session));
121     }
122     return ret;
123 }
124 
125 inline void handleSessionCollectionGet(
126     crow::App& app, const crow::Request& req,
127     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
128 {
129     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
130     {
131         return;
132     }
133     asyncResp->res.jsonValue["Members"] = getSessionCollectionMembers();
134     asyncResp->res.jsonValue["Members@odata.count"] =
135         asyncResp->res.jsonValue["Members"].size();
136     asyncResp->res.jsonValue["@odata.type"] =
137         "#SessionCollection.SessionCollection";
138     asyncResp->res.jsonValue["@odata.id"] =
139         "/redfish/v1/SessionService/Sessions/";
140     asyncResp->res.jsonValue["Name"] = "Session Collection";
141     asyncResp->res.jsonValue["Description"] = "Session Collection";
142 }
143 
144 inline void handleSessionCollectionMembersGet(
145     crow::App& app, const crow::Request& req,
146     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
147 {
148     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
149     {
150         return;
151     }
152     asyncResp->res.jsonValue = getSessionCollectionMembers();
153 }
154 
155 inline void handleSessionCollectionPost(
156     crow::App& app, const crow::Request& req,
157     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
158 {
159     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
160     {
161         return;
162     }
163     std::string username;
164     std::string password;
165     std::optional<nlohmann::json> oemObject;
166     std::string clientId;
167     if (!json_util::readJsonPatch(req, asyncResp->res, "UserName", username,
168                                   "Password", password, "Oem", oemObject))
169     {
170         return;
171     }
172 
173     if (password.empty() || username.empty() ||
174         asyncResp->res.result() != boost::beast::http::status::ok)
175     {
176         if (username.empty())
177         {
178             messages::propertyMissing(asyncResp->res, "UserName");
179         }
180 
181         if (password.empty())
182         {
183             messages::propertyMissing(asyncResp->res, "Password");
184         }
185 
186         return;
187     }
188 
189     int pamrc = pamAuthenticateUser(username, password);
190     bool isConfigureSelfOnly = pamrc == PAM_NEW_AUTHTOK_REQD;
191     if ((pamrc != PAM_SUCCESS) && !isConfigureSelfOnly)
192     {
193         messages::resourceAtUriUnauthorized(asyncResp->res, req.urlView,
194                                             "Invalid username or password");
195         return;
196     }
197 #ifdef BMCWEB_ENABLE_IBM_MANAGEMENT_CONSOLE
198     if (oemObject)
199     {
200         std::optional<nlohmann::json> bmcOem;
201         if (!json_util::readJson(*oemObject, asyncResp->res, "OpenBMC", bmcOem))
202         {
203             return;
204         }
205         if (!json_util::readJson(*bmcOem, asyncResp->res, "ClientID", clientId))
206         {
207             BMCWEB_LOG_ERROR << "Could not read ClientId";
208             return;
209         }
210     }
211 #endif
212 
213     // User is authenticated - create session
214     std::shared_ptr<persistent_data::UserSession> session =
215         persistent_data::SessionStore::getInstance().generateUserSession(
216             username, req.ipAddress, clientId,
217             persistent_data::PersistenceType::TIMEOUT, isConfigureSelfOnly);
218     asyncResp->res.addHeader("X-Auth-Token", session->sessionToken);
219     asyncResp->res.addHeader(
220         "Location", "/redfish/v1/SessionService/Sessions/" + session->uniqueId);
221     asyncResp->res.result(boost::beast::http::status::created);
222     if (session->isConfigureSelfOnly)
223     {
224         messages::passwordChangeRequired(
225             asyncResp->res,
226             crow::utility::urlFromPieces("redfish", "v1", "AccountService",
227                                          "Accounts", req.session->username));
228     }
229 
230     fillSessionObject(asyncResp->res, *session);
231 }
232 inline void
233     handleSessionServiceGet(crow::App& app, const crow::Request& req,
234                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
235 
236 {
237     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
238     {
239         return;
240     }
241     asyncResp->res.jsonValue["@odata.type"] =
242         "#SessionService.v1_0_2.SessionService";
243     asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/SessionService/";
244     asyncResp->res.jsonValue["Name"] = "Session Service";
245     asyncResp->res.jsonValue["Id"] = "SessionService";
246     asyncResp->res.jsonValue["Description"] = "Session Service";
247     asyncResp->res.jsonValue["SessionTimeout"] =
248         persistent_data::SessionStore::getInstance().getTimeoutInSeconds();
249     asyncResp->res.jsonValue["ServiceEnabled"] = true;
250 
251     asyncResp->res.jsonValue["Sessions"]["@odata.id"] =
252         "/redfish/v1/SessionService/Sessions";
253 }
254 
255 inline void handleSessionServicePatch(
256     crow::App& app, const crow::Request& req,
257     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
258 {
259     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
260     {
261         return;
262     }
263     std::optional<int64_t> sessionTimeout;
264     if (!json_util::readJsonPatch(req, asyncResp->res, "SessionTimeout",
265                                   sessionTimeout))
266     {
267         return;
268     }
269 
270     if (sessionTimeout)
271     {
272         // The mininum & maximum allowed values for session timeout
273         // are 30 seconds and 86400 seconds respectively as per the
274         // session service schema mentioned at
275         // https://redfish.dmtf.org/schemas/v1/SessionService.v1_1_7.json
276 
277         if (*sessionTimeout <= 86400 && *sessionTimeout >= 30)
278         {
279             std::chrono::seconds sessionTimeoutInseconds(*sessionTimeout);
280             persistent_data::SessionStore::getInstance().updateSessionTimeout(
281                 sessionTimeoutInseconds);
282             messages::propertyValueModified(asyncResp->res, "SessionTimeOut",
283                                             std::to_string(*sessionTimeout));
284         }
285         else
286         {
287             messages::propertyValueNotInList(asyncResp->res,
288                                              std::to_string(*sessionTimeout),
289                                              "SessionTimeOut");
290         }
291     }
292 }
293 
294 inline void requestRoutesSession(App& app)
295 {
296     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/<str>/")
297         .privileges(redfish::privileges::getSession)
298         .methods(boost::beast::http::verb::get)(
299             std::bind_front(handleSessionGet, std::ref(app)));
300 
301     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/<str>/")
302         .privileges(redfish::privileges::deleteSession)
303         .methods(boost::beast::http::verb::delete_)(
304             std::bind_front(handleSessionDelete, std::ref(app)));
305 
306     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/")
307         .privileges(redfish::privileges::getSessionCollection)
308         .methods(boost::beast::http::verb::get)(
309             std::bind_front(handleSessionCollectionGet, std::ref(app)));
310 
311     // Note, the next two routes technically don't match the privilege
312     // registry given the way login mechanisms work.  The base privilege
313     // registry lists this endpoint as requiring login privilege, but because
314     // this is the endpoint responsible for giving the login privilege, and it
315     // is itself its own route, it needs to not require Login
316     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/")
317         .privileges({})
318         .methods(boost::beast::http::verb::post)(
319             std::bind_front(handleSessionCollectionPost, std::ref(app)));
320 
321     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/Sessions/Members/")
322         .privileges({})
323         .methods(boost::beast::http::verb::post)(
324             std::bind_front(handleSessionCollectionPost, std::ref(app)));
325 
326     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/")
327         .privileges(redfish::privileges::getSessionService)
328         .methods(boost::beast::http::verb::get)(
329             std::bind_front(handleSessionServiceGet, std::ref(app)));
330 
331     BMCWEB_ROUTE(app, "/redfish/v1/SessionService/")
332         .privileges(redfish::privileges::patchSessionService)
333         .methods(boost::beast::http::verb::patch)(
334             std::bind_front(handleSessionServicePatch, std::ref(app)));
335 }
336 
337 } // namespace redfish
338