xref: /openbmc/bmcweb/redfish-core/lib/account_service.hpp (revision 23a21a1cbed23ace4174664950e595df961e9e69)
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 #include "node.hpp"
18 
19 #include <dbus_utility.hpp>
20 #include <error_messages.hpp>
21 #include <openbmc_dbus_rest.hpp>
22 #include <persistent_data.hpp>
23 #include <utils/json_utils.hpp>
24 
25 #include <variant>
26 
27 namespace redfish
28 {
29 
30 constexpr const char* ldapConfigObjectName =
31     "/xyz/openbmc_project/user/ldap/openldap";
32 constexpr const char* ADConfigObject =
33     "/xyz/openbmc_project/user/ldap/active_directory";
34 
35 constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
36 constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
37 constexpr const char* ldapConfigInterface =
38     "xyz.openbmc_project.User.Ldap.Config";
39 constexpr const char* ldapCreateInterface =
40     "xyz.openbmc_project.User.Ldap.Create";
41 constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
42 constexpr const char* ldapPrivMapperInterface =
43     "xyz.openbmc_project.User.PrivilegeMapper";
44 constexpr const char* dbusObjManagerIntf = "org.freedesktop.DBus.ObjectManager";
45 constexpr const char* propertyInterface = "org.freedesktop.DBus.Properties";
46 constexpr const char* mapperBusName = "xyz.openbmc_project.ObjectMapper";
47 constexpr const char* mapperObjectPath = "/xyz/openbmc_project/object_mapper";
48 constexpr const char* mapperIntf = "xyz.openbmc_project.ObjectMapper";
49 
50 struct LDAPRoleMapData
51 {
52     std::string groupName;
53     std::string privilege;
54 };
55 
56 struct LDAPConfigData
57 {
58     std::string uri{};
59     std::string bindDN{};
60     std::string baseDN{};
61     std::string searchScope{};
62     std::string serverType{};
63     bool serviceEnabled = false;
64     std::string userNameAttribute{};
65     std::string groupAttribute{};
66     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
67 };
68 
69 using DbusVariantType = std::variant<bool, int32_t, std::string>;
70 
71 using DbusInterfaceType = boost::container::flat_map<
72     std::string, boost::container::flat_map<std::string, DbusVariantType>>;
73 
74 using ManagedObjectType =
75     std::vector<std::pair<sdbusplus::message::object_path, DbusInterfaceType>>;
76 
77 using GetObjectType =
78     std::vector<std::pair<std::string, std::vector<std::string>>>;
79 
80 inline std::string getRoleIdFromPrivilege(std::string_view role)
81 {
82     if (role == "priv-admin")
83     {
84         return "Administrator";
85     }
86     else if (role == "priv-user")
87     {
88         return "ReadOnly";
89     }
90     else if (role == "priv-operator")
91     {
92         return "Operator";
93     }
94     else if ((role == "") || (role == "priv-noaccess"))
95     {
96         return "NoAccess";
97     }
98     return "";
99 }
100 inline std::string getPrivilegeFromRoleId(std::string_view role)
101 {
102     if (role == "Administrator")
103     {
104         return "priv-admin";
105     }
106     else if (role == "ReadOnly")
107     {
108         return "priv-user";
109     }
110     else if (role == "Operator")
111     {
112         return "priv-operator";
113     }
114     else if ((role == "NoAccess") || (role == ""))
115     {
116         return "priv-noaccess";
117     }
118     return "";
119 }
120 
121 inline void userErrorMessageHandler(const sd_bus_error* e,
122                                     std::shared_ptr<AsyncResp> asyncResp,
123                                     const std::string& newUser,
124                                     const std::string& username)
125 {
126     const char* errorMessage = e->name;
127     if (e == nullptr)
128     {
129         messages::internalError(asyncResp->res);
130         return;
131     }
132 
133     if (strcmp(errorMessage,
134                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
135     {
136         messages::resourceAlreadyExists(asyncResp->res,
137                                         "#ManagerAccount.v1_4_0.ManagerAccount",
138                                         "UserName", newUser);
139     }
140     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
141                                   "UserNameDoesNotExist") == 0)
142     {
143         messages::resourceNotFound(
144             asyncResp->res, "#ManagerAccount.v1_4_0.ManagerAccount", username);
145     }
146     else if (strcmp(errorMessage,
147                     "xyz.openbmc_project.Common.Error.InvalidArgument") == 0)
148     {
149         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
150     }
151     else if (strcmp(errorMessage,
152                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
153     {
154         messages::createLimitReachedForResource(asyncResp->res);
155     }
156     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
157                                   "UserNameGroupFail") == 0)
158     {
159         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
160     }
161     else
162     {
163         messages::internalError(asyncResp->res);
164     }
165 
166     return;
167 }
168 
169 inline void parseLDAPConfigData(nlohmann::json& json_response,
170                                 const LDAPConfigData& confData,
171                                 const std::string& ldapType)
172 {
173     std::string service =
174         (ldapType == "LDAP") ? "LDAPService" : "ActiveDirectoryService";
175     nlohmann::json ldap = {
176         {"ServiceEnabled", confData.serviceEnabled},
177         {"ServiceAddresses", nlohmann::json::array({confData.uri})},
178         {"Authentication",
179          {{"AuthenticationType", "UsernameAndPassword"},
180           {"Username", confData.bindDN},
181           {"Password", nullptr}}},
182         {"LDAPService",
183          {{"SearchSettings",
184            {{"BaseDistinguishedNames",
185              nlohmann::json::array({confData.baseDN})},
186             {"UsernameAttribute", confData.userNameAttribute},
187             {"GroupsAttribute", confData.groupAttribute}}}}},
188     };
189 
190     json_response[ldapType].update(std::move(ldap));
191 
192     nlohmann::json& roleMapArray = json_response[ldapType]["RemoteRoleMapping"];
193     roleMapArray = nlohmann::json::array();
194     for (auto& obj : confData.groupRoleList)
195     {
196         BMCWEB_LOG_DEBUG << "Pushing the data groupName="
197                          << obj.second.groupName << "\n";
198         roleMapArray.push_back(
199             {nlohmann::json::array({"RemoteGroup", obj.second.groupName}),
200              nlohmann::json::array(
201                  {"LocalRole", getRoleIdFromPrivilege(obj.second.privilege)})});
202     }
203 }
204 
205 /**
206  *  @brief validates given JSON input and then calls appropriate method to
207  * create, to delete or to set Rolemapping object based on the given input.
208  *
209  */
210 inline void handleRoleMapPatch(
211     const std::shared_ptr<AsyncResp>& asyncResp,
212     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
213     const std::string& serverType, std::vector<nlohmann::json>& input)
214 {
215     for (size_t index = 0; index < input.size(); index++)
216     {
217         nlohmann::json& thisJson = input[index];
218 
219         if (thisJson.is_null())
220         {
221             // delete the existing object
222             if (index < roleMapObjData.size())
223             {
224                 crow::connections::systemBus->async_method_call(
225                     [asyncResp, roleMapObjData, serverType,
226                      index](const boost::system::error_code ec) {
227                         if (ec)
228                         {
229                             BMCWEB_LOG_ERROR << "DBUS response error: " << ec;
230                             messages::internalError(asyncResp->res);
231                             return;
232                         }
233                         asyncResp->res
234                             .jsonValue[serverType]["RemoteRoleMapping"][index] =
235                             nullptr;
236                     },
237                     ldapDbusService, roleMapObjData[index].first,
238                     "xyz.openbmc_project.Object.Delete", "Delete");
239             }
240             else
241             {
242                 BMCWEB_LOG_ERROR << "Can't delete the object";
243                 messages::propertyValueTypeError(
244                     asyncResp->res, thisJson.dump(),
245                     "RemoteRoleMapping/" + std::to_string(index));
246                 return;
247             }
248         }
249         else if (thisJson.empty())
250         {
251             // Don't do anything for the empty objects,parse next json
252             // eg {"RemoteRoleMapping",[{}]}
253         }
254         else
255         {
256             // update/create the object
257             std::optional<std::string> remoteGroup;
258             std::optional<std::string> localRole;
259 
260             if (!json_util::readJson(thisJson, asyncResp->res, "RemoteGroup",
261                                      remoteGroup, "LocalRole", localRole))
262             {
263                 continue;
264             }
265 
266             // Update existing RoleMapping Object
267             if (index < roleMapObjData.size())
268             {
269                 BMCWEB_LOG_DEBUG << "Update Role Map Object";
270                 // If "RemoteGroup" info is provided
271                 if (remoteGroup)
272                 {
273                     crow::connections::systemBus->async_method_call(
274                         [asyncResp, roleMapObjData, serverType, index,
275                          remoteGroup](const boost::system::error_code ec) {
276                             if (ec)
277                             {
278                                 BMCWEB_LOG_ERROR << "DBUS response error: "
279                                                  << ec;
280                                 messages::internalError(asyncResp->res);
281                                 return;
282                             }
283                             asyncResp->res
284                                 .jsonValue[serverType]["RemoteRoleMapping"]
285                                           [index]["RemoteGroup"] = *remoteGroup;
286                         },
287                         ldapDbusService, roleMapObjData[index].first,
288                         propertyInterface, "Set",
289                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
290                         "GroupName",
291                         std::variant<std::string>(std::move(*remoteGroup)));
292                 }
293 
294                 // If "LocalRole" info is provided
295                 if (localRole)
296                 {
297                     crow::connections::systemBus->async_method_call(
298                         [asyncResp, roleMapObjData, serverType, index,
299                          localRole](const boost::system::error_code ec) {
300                             if (ec)
301                             {
302                                 BMCWEB_LOG_ERROR << "DBUS response error: "
303                                                  << ec;
304                                 messages::internalError(asyncResp->res);
305                                 return;
306                             }
307                             asyncResp->res
308                                 .jsonValue[serverType]["RemoteRoleMapping"]
309                                           [index]["LocalRole"] = *localRole;
310                         },
311                         ldapDbusService, roleMapObjData[index].first,
312                         propertyInterface, "Set",
313                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
314                         "Privilege",
315                         std::variant<std::string>(
316                             getPrivilegeFromRoleId(std::move(*localRole))));
317                 }
318             }
319             // Create a new RoleMapping Object.
320             else
321             {
322                 BMCWEB_LOG_DEBUG
323                     << "setRoleMappingProperties: Creating new Object";
324                 std::string pathString =
325                     "RemoteRoleMapping/" + std::to_string(index);
326 
327                 if (!localRole)
328                 {
329                     messages::propertyMissing(asyncResp->res,
330                                               pathString + "/LocalRole");
331                     continue;
332                 }
333                 if (!remoteGroup)
334                 {
335                     messages::propertyMissing(asyncResp->res,
336                                               pathString + "/RemoteGroup");
337                     continue;
338                 }
339 
340                 std::string dbusObjectPath;
341                 if (serverType == "ActiveDirectory")
342                 {
343                     dbusObjectPath = ADConfigObject;
344                 }
345                 else if (serverType == "LDAP")
346                 {
347                     dbusObjectPath = ldapConfigObjectName;
348                 }
349 
350                 BMCWEB_LOG_DEBUG << "Remote Group=" << *remoteGroup
351                                  << ",LocalRole=" << *localRole;
352 
353                 crow::connections::systemBus->async_method_call(
354                     [asyncResp, serverType, localRole,
355                      remoteGroup](const boost::system::error_code ec) {
356                         if (ec)
357                         {
358                             BMCWEB_LOG_ERROR << "DBUS response error: " << ec;
359                             messages::internalError(asyncResp->res);
360                             return;
361                         }
362                         nlohmann::json& remoteRoleJson =
363                             asyncResp->res
364                                 .jsonValue[serverType]["RemoteRoleMapping"];
365                         remoteRoleJson.push_back(
366                             {{"LocalRole", *localRole},
367                              {"RemoteGroup", *remoteGroup}});
368                     },
369                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
370                     "Create", std::move(*remoteGroup),
371                     getPrivilegeFromRoleId(std::move(*localRole)));
372             }
373         }
374     }
375 }
376 
377 /**
378  * Function that retrieves all properties for LDAP config object
379  * into JSON
380  */
381 template <typename CallbackFunc>
382 inline void getLDAPConfigData(const std::string& ldapType,
383                               CallbackFunc&& callback)
384 {
385 
386     const std::array<const char*, 2> interfaces = {ldapEnableInterface,
387                                                    ldapConfigInterface};
388 
389     crow::connections::systemBus->async_method_call(
390         [callback, ldapType](const boost::system::error_code ec,
391                              const GetObjectType& resp) {
392             if (ec || resp.empty())
393             {
394                 BMCWEB_LOG_ERROR << "DBUS response error during getting of "
395                                     "service name: "
396                                  << ec;
397                 LDAPConfigData empty{};
398                 callback(false, empty, ldapType);
399                 return;
400             }
401             std::string service = resp.begin()->first;
402             crow::connections::systemBus->async_method_call(
403                 [callback, ldapType](const boost::system::error_code error_code,
404                                      const ManagedObjectType& ldapObjects) {
405                     LDAPConfigData confData{};
406                     if (error_code)
407                     {
408                         callback(false, confData, ldapType);
409                         BMCWEB_LOG_ERROR << "D-Bus responses error: "
410                                          << error_code;
411                         return;
412                     }
413 
414                     std::string ldapDbusType;
415                     std::string searchString;
416 
417                     if (ldapType == "LDAP")
418                     {
419                         ldapDbusType = "xyz.openbmc_project.User.Ldap.Config."
420                                        "Type.OpenLdap";
421                         searchString = "openldap";
422                     }
423                     else if (ldapType == "ActiveDirectory")
424                     {
425                         ldapDbusType =
426                             "xyz.openbmc_project.User.Ldap.Config.Type."
427                             "ActiveDirectory";
428                         searchString = "active_directory";
429                     }
430                     else
431                     {
432                         BMCWEB_LOG_ERROR
433                             << "Can't get the DbusType for the given type="
434                             << ldapType;
435                         callback(false, confData, ldapType);
436                         return;
437                     }
438 
439                     std::string ldapEnableInterfaceStr = ldapEnableInterface;
440                     std::string ldapConfigInterfaceStr = ldapConfigInterface;
441 
442                     for (const auto& object : ldapObjects)
443                     {
444                         // let's find the object whose ldap type is equal to the
445                         // given type
446                         if (object.first.str.find(searchString) ==
447                             std::string::npos)
448                         {
449                             continue;
450                         }
451 
452                         for (const auto& interface : object.second)
453                         {
454                             if (interface.first == ldapEnableInterfaceStr)
455                             {
456                                 // rest of the properties are string.
457                                 for (const auto& property : interface.second)
458                                 {
459                                     if (property.first == "Enabled")
460                                     {
461                                         const bool* value =
462                                             std::get_if<bool>(&property.second);
463                                         if (value == nullptr)
464                                         {
465                                             continue;
466                                         }
467                                         confData.serviceEnabled = *value;
468                                         break;
469                                     }
470                                 }
471                             }
472                             else if (interface.first == ldapConfigInterfaceStr)
473                             {
474 
475                                 for (const auto& property : interface.second)
476                                 {
477                                     const std::string* strValue =
478                                         std::get_if<std::string>(
479                                             &property.second);
480                                     if (strValue == nullptr)
481                                     {
482                                         continue;
483                                     }
484                                     if (property.first == "LDAPServerURI")
485                                     {
486                                         confData.uri = *strValue;
487                                     }
488                                     else if (property.first == "LDAPBindDN")
489                                     {
490                                         confData.bindDN = *strValue;
491                                     }
492                                     else if (property.first == "LDAPBaseDN")
493                                     {
494                                         confData.baseDN = *strValue;
495                                     }
496                                     else if (property.first ==
497                                              "LDAPSearchScope")
498                                     {
499                                         confData.searchScope = *strValue;
500                                     }
501                                     else if (property.first ==
502                                              "GroupNameAttribute")
503                                     {
504                                         confData.groupAttribute = *strValue;
505                                     }
506                                     else if (property.first ==
507                                              "UserNameAttribute")
508                                     {
509                                         confData.userNameAttribute = *strValue;
510                                     }
511                                     else if (property.first == "LDAPType")
512                                     {
513                                         confData.serverType = *strValue;
514                                     }
515                                 }
516                             }
517                             else if (interface.first ==
518                                      "xyz.openbmc_project.User."
519                                      "PrivilegeMapperEntry")
520                             {
521                                 LDAPRoleMapData roleMapData{};
522                                 for (const auto& property : interface.second)
523                                 {
524                                     const std::string* strValue =
525                                         std::get_if<std::string>(
526                                             &property.second);
527 
528                                     if (strValue == nullptr)
529                                     {
530                                         continue;
531                                     }
532 
533                                     if (property.first == "GroupName")
534                                     {
535                                         roleMapData.groupName = *strValue;
536                                     }
537                                     else if (property.first == "Privilege")
538                                     {
539                                         roleMapData.privilege = *strValue;
540                                     }
541                                 }
542 
543                                 confData.groupRoleList.emplace_back(
544                                     object.first.str, roleMapData);
545                             }
546                         }
547                     }
548                     callback(true, confData, ldapType);
549                 },
550                 service, ldapRootObject, dbusObjManagerIntf,
551                 "GetManagedObjects");
552         },
553         mapperBusName, mapperObjectPath, mapperIntf, "GetObject",
554         ldapConfigObjectName, interfaces);
555 }
556 
557 class AccountService : public Node
558 {
559   public:
560     AccountService(App& app) : Node(app, "/redfish/v1/AccountService/")
561     {
562         entityPrivileges = {
563             {boost::beast::http::verb::get, {{"Login"}}},
564             {boost::beast::http::verb::head, {{"Login"}}},
565             {boost::beast::http::verb::patch, {{"ConfigureUsers"}}},
566             {boost::beast::http::verb::put, {{"ConfigureUsers"}}},
567             {boost::beast::http::verb::delete_, {{"ConfigureUsers"}}},
568             {boost::beast::http::verb::post, {{"ConfigureUsers"}}}};
569     }
570 
571   private:
572     /**
573      * @brief parses the authentication section under the LDAP
574      * @param input JSON data
575      * @param asyncResp pointer to the JSON response
576      * @param userName  userName to be filled from the given JSON.
577      * @param password  password to be filled from the given JSON.
578      */
579     void
580         parseLDAPAuthenticationJson(nlohmann::json input,
581                                     const std::shared_ptr<AsyncResp>& asyncResp,
582                                     std::optional<std::string>& username,
583                                     std::optional<std::string>& password)
584     {
585         std::optional<std::string> authType;
586 
587         if (!json_util::readJson(input, asyncResp->res, "AuthenticationType",
588                                  authType, "Username", username, "Password",
589                                  password))
590         {
591             return;
592         }
593         if (!authType)
594         {
595             return;
596         }
597         if (*authType != "UsernameAndPassword")
598         {
599             messages::propertyValueNotInList(asyncResp->res, *authType,
600                                              "AuthenticationType");
601             return;
602         }
603     }
604     /**
605      * @brief parses the LDAPService section under the LDAP
606      * @param input JSON data
607      * @param asyncResp pointer to the JSON response
608      * @param baseDNList baseDN to be filled from the given JSON.
609      * @param userNameAttribute  userName to be filled from the given JSON.
610      * @param groupaAttribute  password to be filled from the given JSON.
611      */
612 
613     void parseLDAPServiceJson(
614         nlohmann::json input, const std::shared_ptr<AsyncResp>& asyncResp,
615         std::optional<std::vector<std::string>>& baseDNList,
616         std::optional<std::string>& userNameAttribute,
617         std::optional<std::string>& groupsAttribute)
618     {
619         std::optional<nlohmann::json> searchSettings;
620 
621         if (!json_util::readJson(input, asyncResp->res, "SearchSettings",
622                                  searchSettings))
623         {
624             return;
625         }
626         if (!searchSettings)
627         {
628             return;
629         }
630         if (!json_util::readJson(*searchSettings, asyncResp->res,
631                                  "BaseDistinguishedNames", baseDNList,
632                                  "UsernameAttribute", userNameAttribute,
633                                  "GroupsAttribute", groupsAttribute))
634         {
635             return;
636         }
637     }
638     /**
639      * @brief updates the LDAP server address and updates the
640               json response with the new value.
641      * @param serviceAddressList address to be updated.
642      * @param asyncResp pointer to the JSON response
643      * @param ldapServerElementName Type of LDAP
644      server(openLDAP/ActiveDirectory)
645      */
646 
647     void handleServiceAddressPatch(
648         const std::vector<std::string>& serviceAddressList,
649         const std::shared_ptr<AsyncResp>& asyncResp,
650         const std::string& ldapServerElementName,
651         const std::string& ldapConfigObject)
652     {
653         crow::connections::systemBus->async_method_call(
654             [asyncResp, ldapServerElementName,
655              serviceAddressList](const boost::system::error_code ec) {
656                 if (ec)
657                 {
658                     BMCWEB_LOG_DEBUG
659                         << "Error Occurred in updating the service address";
660                     messages::internalError(asyncResp->res);
661                     return;
662                 }
663                 std::vector<std::string> modifiedserviceAddressList = {
664                     serviceAddressList.front()};
665                 asyncResp->res
666                     .jsonValue[ldapServerElementName]["ServiceAddresses"] =
667                     modifiedserviceAddressList;
668                 if ((serviceAddressList).size() > 1)
669                 {
670                     messages::propertyValueModified(asyncResp->res,
671                                                     "ServiceAddresses",
672                                                     serviceAddressList.front());
673                 }
674                 BMCWEB_LOG_DEBUG << "Updated the service address";
675             },
676             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
677             ldapConfigInterface, "LDAPServerURI",
678             std::variant<std::string>(serviceAddressList.front()));
679     }
680     /**
681      * @brief updates the LDAP Bind DN and updates the
682               json response with the new value.
683      * @param username name of the user which needs to be updated.
684      * @param asyncResp pointer to the JSON response
685      * @param ldapServerElementName Type of LDAP
686      server(openLDAP/ActiveDirectory)
687      */
688 
689     void handleUserNamePatch(const std::string& username,
690                              const std::shared_ptr<AsyncResp>& asyncResp,
691                              const std::string& ldapServerElementName,
692                              const std::string& ldapConfigObject)
693     {
694         crow::connections::systemBus->async_method_call(
695             [asyncResp, username,
696              ldapServerElementName](const boost::system::error_code ec) {
697                 if (ec)
698                 {
699                     BMCWEB_LOG_DEBUG
700                         << "Error occurred in updating the username";
701                     messages::internalError(asyncResp->res);
702                     return;
703                 }
704                 asyncResp->res.jsonValue[ldapServerElementName]
705                                         ["Authentication"]["Username"] =
706                     username;
707                 BMCWEB_LOG_DEBUG << "Updated the username";
708             },
709             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
710             ldapConfigInterface, "LDAPBindDN",
711             std::variant<std::string>(username));
712     }
713 
714     /**
715      * @brief updates the LDAP password
716      * @param password : ldap password which needs to be updated.
717      * @param asyncResp pointer to the JSON response
718      * @param ldapServerElementName Type of LDAP
719      *        server(openLDAP/ActiveDirectory)
720      */
721 
722     void handlePasswordPatch(const std::string& password,
723                              const std::shared_ptr<AsyncResp>& asyncResp,
724                              const std::string& ldapServerElementName,
725                              const std::string& ldapConfigObject)
726     {
727         crow::connections::systemBus->async_method_call(
728             [asyncResp, password,
729              ldapServerElementName](const boost::system::error_code ec) {
730                 if (ec)
731                 {
732                     BMCWEB_LOG_DEBUG
733                         << "Error occurred in updating the password";
734                     messages::internalError(asyncResp->res);
735                     return;
736                 }
737                 asyncResp->res.jsonValue[ldapServerElementName]
738                                         ["Authentication"]["Password"] = "";
739                 BMCWEB_LOG_DEBUG << "Updated the password";
740             },
741             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
742             ldapConfigInterface, "LDAPBindDNPassword",
743             std::variant<std::string>(password));
744     }
745 
746     /**
747      * @brief updates the LDAP BaseDN and updates the
748               json response with the new value.
749      * @param baseDNList baseDN list which needs to be updated.
750      * @param asyncResp pointer to the JSON response
751      * @param ldapServerElementName Type of LDAP
752      server(openLDAP/ActiveDirectory)
753      */
754 
755     void handleBaseDNPatch(const std::vector<std::string>& baseDNList,
756                            const std::shared_ptr<AsyncResp>& asyncResp,
757                            const std::string& ldapServerElementName,
758                            const std::string& ldapConfigObject)
759     {
760         crow::connections::systemBus->async_method_call(
761             [asyncResp, baseDNList,
762              ldapServerElementName](const boost::system::error_code ec) {
763                 if (ec)
764                 {
765                     BMCWEB_LOG_DEBUG
766                         << "Error Occurred in Updating the base DN";
767                     messages::internalError(asyncResp->res);
768                     return;
769                 }
770                 auto& serverTypeJson =
771                     asyncResp->res.jsonValue[ldapServerElementName];
772                 auto& searchSettingsJson =
773                     serverTypeJson["LDAPService"]["SearchSettings"];
774                 std::vector<std::string> modifiedBaseDNList = {
775                     baseDNList.front()};
776                 searchSettingsJson["BaseDistinguishedNames"] =
777                     modifiedBaseDNList;
778                 if (baseDNList.size() > 1)
779                 {
780                     messages::propertyValueModified(asyncResp->res,
781                                                     "BaseDistinguishedNames",
782                                                     baseDNList.front());
783                 }
784                 BMCWEB_LOG_DEBUG << "Updated the base DN";
785             },
786             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
787             ldapConfigInterface, "LDAPBaseDN",
788             std::variant<std::string>(baseDNList.front()));
789     }
790     /**
791      * @brief updates the LDAP user name attribute and updates the
792               json response with the new value.
793      * @param userNameAttribute attribute to be updated.
794      * @param asyncResp pointer to the JSON response
795      * @param ldapServerElementName Type of LDAP
796      server(openLDAP/ActiveDirectory)
797      */
798 
799     void handleUserNameAttrPatch(const std::string& userNameAttribute,
800                                  const std::shared_ptr<AsyncResp>& asyncResp,
801                                  const std::string& ldapServerElementName,
802                                  const std::string& ldapConfigObject)
803     {
804         crow::connections::systemBus->async_method_call(
805             [asyncResp, userNameAttribute,
806              ldapServerElementName](const boost::system::error_code ec) {
807                 if (ec)
808                 {
809                     BMCWEB_LOG_DEBUG << "Error Occurred in Updating the "
810                                         "username attribute";
811                     messages::internalError(asyncResp->res);
812                     return;
813                 }
814                 auto& serverTypeJson =
815                     asyncResp->res.jsonValue[ldapServerElementName];
816                 auto& searchSettingsJson =
817                     serverTypeJson["LDAPService"]["SearchSettings"];
818                 searchSettingsJson["UsernameAttribute"] = userNameAttribute;
819                 BMCWEB_LOG_DEBUG << "Updated the user name attr.";
820             },
821             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
822             ldapConfigInterface, "UserNameAttribute",
823             std::variant<std::string>(userNameAttribute));
824     }
825     /**
826      * @brief updates the LDAP group attribute and updates the
827               json response with the new value.
828      * @param groupsAttribute attribute to be updated.
829      * @param asyncResp pointer to the JSON response
830      * @param ldapServerElementName Type of LDAP
831      server(openLDAP/ActiveDirectory)
832      */
833 
834     void handleGroupNameAttrPatch(const std::string& groupsAttribute,
835                                   const std::shared_ptr<AsyncResp>& asyncResp,
836                                   const std::string& ldapServerElementName,
837                                   const std::string& ldapConfigObject)
838     {
839         crow::connections::systemBus->async_method_call(
840             [asyncResp, groupsAttribute,
841              ldapServerElementName](const boost::system::error_code ec) {
842                 if (ec)
843                 {
844                     BMCWEB_LOG_DEBUG << "Error Occurred in Updating the "
845                                         "groupname attribute";
846                     messages::internalError(asyncResp->res);
847                     return;
848                 }
849                 auto& serverTypeJson =
850                     asyncResp->res.jsonValue[ldapServerElementName];
851                 auto& searchSettingsJson =
852                     serverTypeJson["LDAPService"]["SearchSettings"];
853                 searchSettingsJson["GroupsAttribute"] = groupsAttribute;
854                 BMCWEB_LOG_DEBUG << "Updated the groupname attr";
855             },
856             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
857             ldapConfigInterface, "GroupNameAttribute",
858             std::variant<std::string>(groupsAttribute));
859     }
860     /**
861      * @brief updates the LDAP service enable and updates the
862               json response with the new value.
863      * @param input JSON data.
864      * @param asyncResp pointer to the JSON response
865      * @param ldapServerElementName Type of LDAP
866      server(openLDAP/ActiveDirectory)
867      */
868 
869     void handleServiceEnablePatch(bool serviceEnabled,
870                                   const std::shared_ptr<AsyncResp>& asyncResp,
871                                   const std::string& ldapServerElementName,
872                                   const std::string& ldapConfigObject)
873     {
874         crow::connections::systemBus->async_method_call(
875             [asyncResp, serviceEnabled,
876              ldapServerElementName](const boost::system::error_code ec) {
877                 if (ec)
878                 {
879                     BMCWEB_LOG_DEBUG
880                         << "Error Occurred in Updating the service enable";
881                     messages::internalError(asyncResp->res);
882                     return;
883                 }
884                 asyncResp->res
885                     .jsonValue[ldapServerElementName]["ServiceEnabled"] =
886                     serviceEnabled;
887                 BMCWEB_LOG_DEBUG << "Updated Service enable = "
888                                  << serviceEnabled;
889             },
890             ldapDbusService, ldapConfigObject, propertyInterface, "Set",
891             ldapEnableInterface, "Enabled", std::variant<bool>(serviceEnabled));
892     }
893 
894     void handleAuthMethodsPatch(nlohmann::json& input,
895                                 const std::shared_ptr<AsyncResp>& asyncResp)
896     {
897         std::optional<bool> basicAuth;
898         std::optional<bool> cookie;
899         std::optional<bool> sessionToken;
900         std::optional<bool> xToken;
901         std::optional<bool> tls;
902 
903         if (!json_util::readJson(input, asyncResp->res, "BasicAuth", basicAuth,
904                                  "Cookie", cookie, "SessionToken", sessionToken,
905                                  "XToken", xToken, "TLS", tls))
906         {
907             BMCWEB_LOG_ERROR << "Cannot read values from AuthMethod tag";
908             return;
909         }
910 
911         // Make a copy of methods configuration
912         persistent_data::AuthConfigMethods authMethodsConfig =
913             persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
914 
915         if (basicAuth)
916         {
917             authMethodsConfig.basic = *basicAuth;
918         }
919 
920         if (cookie)
921         {
922             authMethodsConfig.cookie = *cookie;
923         }
924 
925         if (sessionToken)
926         {
927             authMethodsConfig.sessionToken = *sessionToken;
928         }
929 
930         if (xToken)
931         {
932             authMethodsConfig.xtoken = *xToken;
933         }
934 
935         if (tls)
936         {
937             authMethodsConfig.tls = *tls;
938         }
939 
940         if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
941             !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
942             !authMethodsConfig.tls)
943         {
944             // Do not allow user to disable everything
945             messages::actionNotSupported(asyncResp->res,
946                                          "of disabling all available methods");
947             return;
948         }
949 
950         persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
951             authMethodsConfig);
952         // Save configuration immediately
953         persistent_data::getConfig().writeData();
954 
955         messages::success(asyncResp->res);
956     }
957 
958     /**
959      * @brief Get the required values from the given JSON, validates the
960      *        value and create the LDAP config object.
961      * @param input JSON data
962      * @param asyncResp pointer to the JSON response
963      * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
964      */
965 
966     void handleLDAPPatch(nlohmann::json& input,
967                          const std::shared_ptr<AsyncResp>& asyncResp,
968                          const crow::Request& req,
969                          const std::vector<std::string>& params,
970                          const std::string& serverType)
971     {
972         std::string dbusObjectPath;
973         if (serverType == "ActiveDirectory")
974         {
975             dbusObjectPath = ADConfigObject;
976         }
977         else if (serverType == "LDAP")
978         {
979             dbusObjectPath = ldapConfigObjectName;
980         }
981 
982         std::optional<nlohmann::json> authentication;
983         std::optional<nlohmann::json> ldapService;
984         std::optional<std::vector<std::string>> serviceAddressList;
985         std::optional<bool> serviceEnabled;
986         std::optional<std::vector<std::string>> baseDNList;
987         std::optional<std::string> userNameAttribute;
988         std::optional<std::string> groupsAttribute;
989         std::optional<std::string> userName;
990         std::optional<std::string> password;
991         std::optional<std::vector<nlohmann::json>> remoteRoleMapData;
992 
993         if (!json_util::readJson(input, asyncResp->res, "Authentication",
994                                  authentication, "LDAPService", ldapService,
995                                  "ServiceAddresses", serviceAddressList,
996                                  "ServiceEnabled", serviceEnabled,
997                                  "RemoteRoleMapping", remoteRoleMapData))
998         {
999             return;
1000         }
1001 
1002         if (authentication)
1003         {
1004             parseLDAPAuthenticationJson(*authentication, asyncResp, userName,
1005                                         password);
1006         }
1007         if (ldapService)
1008         {
1009             parseLDAPServiceJson(*ldapService, asyncResp, baseDNList,
1010                                  userNameAttribute, groupsAttribute);
1011         }
1012         if (serviceAddressList)
1013         {
1014             if ((*serviceAddressList).size() == 0)
1015             {
1016                 messages::propertyValueNotInList(asyncResp->res, "[]",
1017                                                  "ServiceAddress");
1018                 return;
1019             }
1020         }
1021         if (baseDNList)
1022         {
1023             if ((*baseDNList).size() == 0)
1024             {
1025                 messages::propertyValueNotInList(asyncResp->res, "[]",
1026                                                  "BaseDistinguishedNames");
1027                 return;
1028             }
1029         }
1030 
1031         // nothing to update, then return
1032         if (!userName && !password && !serviceAddressList && !baseDNList &&
1033             !userNameAttribute && !groupsAttribute && !serviceEnabled &&
1034             !remoteRoleMapData)
1035         {
1036             return;
1037         }
1038 
1039         // Get the existing resource first then keep modifying
1040         // whenever any property gets updated.
1041         getLDAPConfigData(serverType, [this, asyncResp, userName, password,
1042                                        baseDNList, userNameAttribute,
1043                                        groupsAttribute, serviceAddressList,
1044                                        serviceEnabled, dbusObjectPath,
1045                                        remoteRoleMapData](
1046                                           bool success, LDAPConfigData confData,
1047                                           const std::string& serverT) {
1048             if (!success)
1049             {
1050                 messages::internalError(asyncResp->res);
1051                 return;
1052             }
1053             parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
1054             if (confData.serviceEnabled)
1055             {
1056                 // Disable the service first and update the rest of
1057                 // the properties.
1058                 handleServiceEnablePatch(false, asyncResp, serverT,
1059                                          dbusObjectPath);
1060             }
1061 
1062             if (serviceAddressList)
1063             {
1064                 handleServiceAddressPatch(*serviceAddressList, asyncResp,
1065                                           serverT, dbusObjectPath);
1066             }
1067             if (userName)
1068             {
1069                 handleUserNamePatch(*userName, asyncResp, serverT,
1070                                     dbusObjectPath);
1071             }
1072             if (password)
1073             {
1074                 handlePasswordPatch(*password, asyncResp, serverT,
1075                                     dbusObjectPath);
1076             }
1077 
1078             if (baseDNList)
1079             {
1080                 handleBaseDNPatch(*baseDNList, asyncResp, serverT,
1081                                   dbusObjectPath);
1082             }
1083             if (userNameAttribute)
1084             {
1085                 handleUserNameAttrPatch(*userNameAttribute, asyncResp, serverT,
1086                                         dbusObjectPath);
1087             }
1088             if (groupsAttribute)
1089             {
1090                 handleGroupNameAttrPatch(*groupsAttribute, asyncResp, serverT,
1091                                          dbusObjectPath);
1092             }
1093             if (serviceEnabled)
1094             {
1095                 // if user has given the value as true then enable
1096                 // the service. if user has given false then no-op
1097                 // as service is already stopped.
1098                 if (*serviceEnabled)
1099                 {
1100                     handleServiceEnablePatch(*serviceEnabled, asyncResp,
1101                                              serverT, dbusObjectPath);
1102                 }
1103             }
1104             else
1105             {
1106                 // if user has not given the service enabled value
1107                 // then revert it to the same state as it was
1108                 // before.
1109                 handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
1110                                          serverT, dbusObjectPath);
1111             }
1112 
1113             if (remoteRoleMapData)
1114             {
1115                 std::vector<nlohmann::json> remoteRoleMap =
1116                     std::move(*remoteRoleMapData);
1117 
1118                 handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
1119                                    remoteRoleMap);
1120             }
1121         });
1122     }
1123 
1124     void doGet(crow::Response& res, const crow::Request& req,
1125                const std::vector<std::string>& params) override
1126     {
1127         const persistent_data::AuthConfigMethods& authMethodsConfig =
1128             persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1129 
1130         auto asyncResp = std::make_shared<AsyncResp>(res);
1131         res.jsonValue = {
1132             {"@odata.id", "/redfish/v1/AccountService"},
1133             {"@odata.type", "#AccountService."
1134                             "v1_5_0.AccountService"},
1135             {"Id", "AccountService"},
1136             {"Name", "Account Service"},
1137             {"Description", "Account Service"},
1138             {"ServiceEnabled", true},
1139             {"MaxPasswordLength", 20},
1140             {"Accounts",
1141              {{"@odata.id", "/redfish/v1/AccountService/Accounts"}}},
1142             {"Roles", {{"@odata.id", "/redfish/v1/AccountService/Roles"}}},
1143             {"Oem",
1144              {{"OpenBMC",
1145                {{"@odata.type", "#OemAccountService.v1_0_0.AccountService"},
1146                 {"AuthMethods",
1147                  {
1148                      {"BasicAuth", authMethodsConfig.basic},
1149                      {"SessionToken", authMethodsConfig.sessionToken},
1150                      {"XToken", authMethodsConfig.xtoken},
1151                      {"Cookie", authMethodsConfig.cookie},
1152                      {"TLS", authMethodsConfig.tls},
1153                  }}}}}},
1154             {"LDAP",
1155              {{"Certificates",
1156                {{"@odata.id",
1157                  "/redfish/v1/AccountService/LDAP/Certificates"}}}}}};
1158         crow::connections::systemBus->async_method_call(
1159             [asyncResp](
1160                 const boost::system::error_code ec,
1161                 const std::vector<std::pair<
1162                     std::string, std::variant<uint32_t, uint16_t, uint8_t>>>&
1163                     propertiesList) {
1164                 if (ec)
1165                 {
1166                     messages::internalError(asyncResp->res);
1167                     return;
1168                 }
1169                 BMCWEB_LOG_DEBUG << "Got " << propertiesList.size()
1170                                  << "properties for AccountService";
1171                 for (const std::pair<std::string,
1172                                      std::variant<uint32_t, uint16_t, uint8_t>>&
1173                          property : propertiesList)
1174                 {
1175                     if (property.first == "MinPasswordLength")
1176                     {
1177                         const uint8_t* value =
1178                             std::get_if<uint8_t>(&property.second);
1179                         if (value != nullptr)
1180                         {
1181                             asyncResp->res.jsonValue["MinPasswordLength"] =
1182                                 *value;
1183                         }
1184                     }
1185                     if (property.first == "AccountUnlockTimeout")
1186                     {
1187                         const uint32_t* value =
1188                             std::get_if<uint32_t>(&property.second);
1189                         if (value != nullptr)
1190                         {
1191                             asyncResp->res.jsonValue["AccountLockoutDuration"] =
1192                                 *value;
1193                         }
1194                     }
1195                     if (property.first == "MaxLoginAttemptBeforeLockout")
1196                     {
1197                         const uint16_t* value =
1198                             std::get_if<uint16_t>(&property.second);
1199                         if (value != nullptr)
1200                         {
1201                             asyncResp->res
1202                                 .jsonValue["AccountLockoutThreshold"] = *value;
1203                         }
1204                     }
1205                 }
1206             },
1207             "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1208             "org.freedesktop.DBus.Properties", "GetAll",
1209             "xyz.openbmc_project.User.AccountPolicy");
1210 
1211         auto callback = [asyncResp](bool success, LDAPConfigData& confData,
1212                                     const std::string& ldapType) {
1213             parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1214         };
1215 
1216         getLDAPConfigData("LDAP", callback);
1217         getLDAPConfigData("ActiveDirectory", callback);
1218     }
1219 
1220     void doPatch(crow::Response& res, const crow::Request& req,
1221                  const std::vector<std::string>& params) override
1222     {
1223         auto asyncResp = std::make_shared<AsyncResp>(res);
1224 
1225         std::optional<uint32_t> unlockTimeout;
1226         std::optional<uint16_t> lockoutThreshold;
1227         std::optional<uint16_t> minPasswordLength;
1228         std::optional<uint16_t> maxPasswordLength;
1229         std::optional<nlohmann::json> ldapObject;
1230         std::optional<nlohmann::json> activeDirectoryObject;
1231         std::optional<nlohmann::json> oemObject;
1232 
1233         if (!json_util::readJson(
1234                 req, res, "AccountLockoutDuration", unlockTimeout,
1235                 "AccountLockoutThreshold", lockoutThreshold,
1236                 "MaxPasswordLength", maxPasswordLength, "MinPasswordLength",
1237                 minPasswordLength, "LDAP", ldapObject, "ActiveDirectory",
1238                 activeDirectoryObject, "Oem", oemObject))
1239         {
1240             return;
1241         }
1242 
1243         if (minPasswordLength)
1244         {
1245             messages::propertyNotWritable(asyncResp->res, "MinPasswordLength");
1246         }
1247 
1248         if (maxPasswordLength)
1249         {
1250             messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1251         }
1252 
1253         if (ldapObject)
1254         {
1255             handleLDAPPatch(*ldapObject, asyncResp, req, params, "LDAP");
1256         }
1257 
1258         if (std::optional<nlohmann::json> oemOpenBMCObject;
1259             oemObject &&
1260             json_util::readJson(*oemObject, res, "OpenBMC", oemOpenBMCObject))
1261         {
1262             if (std::optional<nlohmann::json> authMethodsObject;
1263                 oemOpenBMCObject &&
1264                 json_util::readJson(*oemOpenBMCObject, res, "AuthMethods",
1265                                     authMethodsObject))
1266             {
1267                 if (authMethodsObject)
1268                 {
1269                     handleAuthMethodsPatch(*authMethodsObject, asyncResp);
1270                 }
1271             }
1272         }
1273 
1274         if (activeDirectoryObject)
1275         {
1276             handleLDAPPatch(*activeDirectoryObject, asyncResp, req, params,
1277                             "ActiveDirectory");
1278         }
1279 
1280         if (unlockTimeout)
1281         {
1282             crow::connections::systemBus->async_method_call(
1283                 [asyncResp](const boost::system::error_code ec) {
1284                     if (ec)
1285                     {
1286                         messages::internalError(asyncResp->res);
1287                         return;
1288                     }
1289                     messages::success(asyncResp->res);
1290                 },
1291                 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1292                 "org.freedesktop.DBus.Properties", "Set",
1293                 "xyz.openbmc_project.User.AccountPolicy",
1294                 "AccountUnlockTimeout", std::variant<uint32_t>(*unlockTimeout));
1295         }
1296         if (lockoutThreshold)
1297         {
1298             crow::connections::systemBus->async_method_call(
1299                 [asyncResp](const boost::system::error_code ec) {
1300                     if (ec)
1301                     {
1302                         messages::internalError(asyncResp->res);
1303                         return;
1304                     }
1305                     messages::success(asyncResp->res);
1306                 },
1307                 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1308                 "org.freedesktop.DBus.Properties", "Set",
1309                 "xyz.openbmc_project.User.AccountPolicy",
1310                 "MaxLoginAttemptBeforeLockout",
1311                 std::variant<uint16_t>(*lockoutThreshold));
1312         }
1313     }
1314 };
1315 
1316 class AccountsCollection : public Node
1317 {
1318   public:
1319     AccountsCollection(App& app) :
1320         Node(app, "/redfish/v1/AccountService/Accounts/")
1321     {
1322         entityPrivileges = {
1323             // According to the PrivilegeRegistry, GET should actually be
1324             // "Login". A "Login" only privilege would return an empty "Members"
1325             // list. Not going to worry about this since none of the defined
1326             // roles are just "Login". E.g. Readonly is {"Login",
1327             // "ConfigureSelf"}. In the rare event anyone defines a role that
1328             // has Login but not ConfigureSelf, implement this.
1329             {boost::beast::http::verb::get,
1330              {{"ConfigureUsers"}, {"ConfigureSelf"}}},
1331             {boost::beast::http::verb::head, {{"Login"}}},
1332             {boost::beast::http::verb::patch, {{"ConfigureUsers"}}},
1333             {boost::beast::http::verb::put, {{"ConfigureUsers"}}},
1334             {boost::beast::http::verb::delete_, {{"ConfigureUsers"}}},
1335             {boost::beast::http::verb::post, {{"ConfigureUsers"}}}};
1336     }
1337 
1338   private:
1339     void doGet(crow::Response& res, const crow::Request& req,
1340                const std::vector<std::string>& params) override
1341     {
1342         auto asyncResp = std::make_shared<AsyncResp>(res);
1343         res.jsonValue = {{"@odata.id", "/redfish/v1/AccountService/Accounts"},
1344                          {"@odata.type", "#ManagerAccountCollection."
1345                                          "ManagerAccountCollection"},
1346                          {"Name", "Accounts Collection"},
1347                          {"Description", "BMC User Accounts"}};
1348 
1349         crow::connections::systemBus->async_method_call(
1350             [asyncResp, &req, this](const boost::system::error_code ec,
1351                                     const ManagedObjectType& users) {
1352                 if (ec)
1353                 {
1354                     messages::internalError(asyncResp->res);
1355                     return;
1356                 }
1357 
1358                 nlohmann::json& memberArray =
1359                     asyncResp->res.jsonValue["Members"];
1360                 memberArray = nlohmann::json::array();
1361 
1362                 for (auto& user : users)
1363                 {
1364                     const std::string& path =
1365                         static_cast<const std::string&>(user.first);
1366                     std::size_t lastIndex = path.rfind("/");
1367                     if (lastIndex == std::string::npos)
1368                     {
1369                         lastIndex = 0;
1370                     }
1371                     else
1372                     {
1373                         lastIndex += 1;
1374                     }
1375 
1376                     // As clarified by Redfish here:
1377                     // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
1378                     // Users without ConfigureUsers, only see their own account.
1379                     // Users with ConfigureUsers, see all accounts.
1380                     if (req.session->username == path.substr(lastIndex) ||
1381                         isAllowedWithoutConfigureSelf(req))
1382                     {
1383                         memberArray.push_back(
1384                             {{"@odata.id",
1385                               "/redfish/v1/AccountService/Accounts/" +
1386                                   path.substr(lastIndex)}});
1387                     }
1388                 }
1389                 asyncResp->res.jsonValue["Members@odata.count"] =
1390                     memberArray.size();
1391             },
1392             "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1393             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1394     }
1395     void doPost(crow::Response& res, const crow::Request& req,
1396                 const std::vector<std::string>& params) override
1397     {
1398         auto asyncResp = std::make_shared<AsyncResp>(res);
1399 
1400         std::string username;
1401         std::string password;
1402         std::optional<std::string> roleId("User");
1403         std::optional<bool> enabled = true;
1404         if (!json_util::readJson(req, res, "UserName", username, "Password",
1405                                  password, "RoleId", roleId, "Enabled",
1406                                  enabled))
1407         {
1408             return;
1409         }
1410 
1411         std::string priv = getPrivilegeFromRoleId(*roleId);
1412         if (priv.empty())
1413         {
1414             messages::propertyValueNotInList(asyncResp->res, *roleId, "RoleId");
1415             return;
1416         }
1417         // TODO: Following override will be reverted once support in
1418         // phosphor-user-manager is added. In order to avoid dependency issues,
1419         // this is added in bmcweb, which will removed, once
1420         // phosphor-user-manager supports priv-noaccess.
1421         if (priv == "priv-noaccess")
1422         {
1423             roleId = "";
1424         }
1425         else
1426         {
1427             roleId = priv;
1428         }
1429 
1430         // Reading AllGroups property
1431         crow::connections::systemBus->async_method_call(
1432             [asyncResp, username, password{std::move(password)}, roleId,
1433              enabled](const boost::system::error_code ec,
1434                       const std::variant<std::vector<std::string>>& allGroups) {
1435                 if (ec)
1436                 {
1437                     BMCWEB_LOG_DEBUG << "ERROR with async_method_call";
1438                     messages::internalError(asyncResp->res);
1439                     return;
1440                 }
1441 
1442                 const std::vector<std::string>* allGroupsList =
1443                     std::get_if<std::vector<std::string>>(&allGroups);
1444 
1445                 if (allGroupsList == nullptr || allGroupsList->empty())
1446                 {
1447                     messages::internalError(asyncResp->res);
1448                     return;
1449                 }
1450 
1451                 crow::connections::systemBus->async_method_call(
1452                     [asyncResp, username, password{std::move(password)}](
1453                         const boost::system::error_code ec2,
1454                         sdbusplus::message::message& m) {
1455                         if (ec2)
1456                         {
1457                             userErrorMessageHandler(m.get_error(), asyncResp,
1458                                                     username, "");
1459                             return;
1460                         }
1461 
1462                         if (pamUpdatePassword(username, password) !=
1463                             PAM_SUCCESS)
1464                         {
1465                             // At this point we have a user that's been created,
1466                             // but the password set failed.Something is wrong,
1467                             // so delete the user that we've already created
1468                             crow::connections::systemBus->async_method_call(
1469                                 [asyncResp, password](
1470                                     const boost::system::error_code ec3) {
1471                                     if (ec3)
1472                                     {
1473                                         messages::internalError(asyncResp->res);
1474                                         return;
1475                                     }
1476 
1477                                     // If password is invalid
1478                                     messages::propertyValueFormatError(
1479                                         asyncResp->res, password, "Password");
1480                                 },
1481                                 "xyz.openbmc_project.User.Manager",
1482                                 "/xyz/openbmc_project/user/" + username,
1483                                 "xyz.openbmc_project.Object.Delete", "Delete");
1484 
1485                             BMCWEB_LOG_ERROR << "pamUpdatePassword Failed";
1486                             return;
1487                         }
1488 
1489                         messages::created(asyncResp->res);
1490                         asyncResp->res.addHeader(
1491                             "Location",
1492                             "/redfish/v1/AccountService/Accounts/" + username);
1493                     },
1494                     "xyz.openbmc_project.User.Manager",
1495                     "/xyz/openbmc_project/user",
1496                     "xyz.openbmc_project.User.Manager", "CreateUser", username,
1497                     *allGroupsList, *roleId, *enabled);
1498             },
1499             "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1500             "org.freedesktop.DBus.Properties", "Get",
1501             "xyz.openbmc_project.User.Manager", "AllGroups");
1502     }
1503 };
1504 
1505 class ManagerAccount : public Node
1506 {
1507   public:
1508     ManagerAccount(App& app) :
1509         Node(app, "/redfish/v1/AccountService/Accounts/<str>/", std::string())
1510     {
1511         entityPrivileges = {
1512             {boost::beast::http::verb::get,
1513              {{"ConfigureUsers"}, {"ConfigureManager"}, {"ConfigureSelf"}}},
1514             {boost::beast::http::verb::head, {{"Login"}}},
1515             {boost::beast::http::verb::patch,
1516              {{"ConfigureUsers"}, {"ConfigureSelf"}}},
1517             {boost::beast::http::verb::put, {{"ConfigureUsers"}}},
1518             {boost::beast::http::verb::delete_, {{"ConfigureUsers"}}},
1519             {boost::beast::http::verb::post, {{"ConfigureUsers"}}}};
1520     }
1521 
1522   private:
1523     void doGet(crow::Response& res, const crow::Request& req,
1524                const std::vector<std::string>& params) override
1525     {
1526         auto asyncResp = std::make_shared<AsyncResp>(res);
1527 
1528         if (params.size() != 1)
1529         {
1530             messages::internalError(asyncResp->res);
1531             return;
1532         }
1533 
1534         // Perform a proper ConfigureSelf authority check.  If the
1535         // user is operating on an account not their own, then their
1536         // ConfigureSelf privilege does not apply.  In this case,
1537         // perform the authority check again without the user's
1538         // ConfigureSelf privilege.
1539         if (req.session->username != params[0])
1540         {
1541             if (!isAllowedWithoutConfigureSelf(req))
1542             {
1543                 BMCWEB_LOG_DEBUG << "GET Account denied access";
1544                 messages::insufficientPrivilege(asyncResp->res);
1545                 return;
1546             }
1547         }
1548 
1549         crow::connections::systemBus->async_method_call(
1550             [asyncResp, accountName{std::string(params[0])}](
1551                 const boost::system::error_code ec,
1552                 const ManagedObjectType& users) {
1553                 if (ec)
1554                 {
1555                     messages::internalError(asyncResp->res);
1556                     return;
1557                 }
1558                 auto userIt = users.begin();
1559 
1560                 for (; userIt != users.end(); userIt++)
1561                 {
1562                     if (boost::ends_with(userIt->first.str, "/" + accountName))
1563                     {
1564                         break;
1565                     }
1566                 }
1567                 if (userIt == users.end())
1568                 {
1569                     messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1570                                                accountName);
1571                     return;
1572                 }
1573 
1574                 asyncResp->res.jsonValue = {
1575                     {"@odata.type", "#ManagerAccount.v1_4_0.ManagerAccount"},
1576                     {"Name", "User Account"},
1577                     {"Description", "User Account"},
1578                     {"Password", nullptr},
1579                     {"AccountTypes", {"Redfish"}}};
1580 
1581                 for (const auto& interface : userIt->second)
1582                 {
1583                     if (interface.first ==
1584                         "xyz.openbmc_project.User.Attributes")
1585                     {
1586                         for (const auto& property : interface.second)
1587                         {
1588                             if (property.first == "UserEnabled")
1589                             {
1590                                 const bool* userEnabled =
1591                                     std::get_if<bool>(&property.second);
1592                                 if (userEnabled == nullptr)
1593                                 {
1594                                     BMCWEB_LOG_ERROR
1595                                         << "UserEnabled wasn't a bool";
1596                                     messages::internalError(asyncResp->res);
1597                                     return;
1598                                 }
1599                                 asyncResp->res.jsonValue["Enabled"] =
1600                                     *userEnabled;
1601                             }
1602                             else if (property.first ==
1603                                      "UserLockedForFailedAttempt")
1604                             {
1605                                 const bool* userLocked =
1606                                     std::get_if<bool>(&property.second);
1607                                 if (userLocked == nullptr)
1608                                 {
1609                                     BMCWEB_LOG_ERROR << "UserLockedForF"
1610                                                         "ailedAttempt "
1611                                                         "wasn't a bool";
1612                                     messages::internalError(asyncResp->res);
1613                                     return;
1614                                 }
1615                                 asyncResp->res.jsonValue["Locked"] =
1616                                     *userLocked;
1617                                 asyncResp->res.jsonValue
1618                                     ["Locked@Redfish.AllowableValues"] = {
1619                                     "false"}; // can only unlock accounts
1620                             }
1621                             else if (property.first == "UserPrivilege")
1622                             {
1623                                 const std::string* userPrivPtr =
1624                                     std::get_if<std::string>(&property.second);
1625                                 if (userPrivPtr == nullptr)
1626                                 {
1627                                     BMCWEB_LOG_ERROR
1628                                         << "UserPrivilege wasn't a "
1629                                            "string";
1630                                     messages::internalError(asyncResp->res);
1631                                     return;
1632                                 }
1633                                 std::string role =
1634                                     getRoleIdFromPrivilege(*userPrivPtr);
1635                                 if (role.empty())
1636                                 {
1637                                     BMCWEB_LOG_ERROR << "Invalid user role";
1638                                     messages::internalError(asyncResp->res);
1639                                     return;
1640                                 }
1641                                 asyncResp->res.jsonValue["RoleId"] = role;
1642 
1643                                 asyncResp->res.jsonValue["Links"]["Role"] = {
1644                                     {"@odata.id", "/redfish/v1/AccountService/"
1645                                                   "Roles/" +
1646                                                       role}};
1647                             }
1648                             else if (property.first == "UserPasswordExpired")
1649                             {
1650                                 const bool* userPasswordExpired =
1651                                     std::get_if<bool>(&property.second);
1652                                 if (userPasswordExpired == nullptr)
1653                                 {
1654                                     BMCWEB_LOG_ERROR << "UserPassword"
1655                                                         "Expired "
1656                                                         "wasn't a bool";
1657                                     messages::internalError(asyncResp->res);
1658                                     return;
1659                                 }
1660                                 asyncResp->res
1661                                     .jsonValue["PasswordChangeRequired"] =
1662                                     *userPasswordExpired;
1663                             }
1664                         }
1665                     }
1666                 }
1667 
1668                 asyncResp->res.jsonValue["@odata.id"] =
1669                     "/redfish/v1/AccountService/Accounts/" + accountName;
1670                 asyncResp->res.jsonValue["Id"] = accountName;
1671                 asyncResp->res.jsonValue["UserName"] = accountName;
1672             },
1673             "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1674             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1675     }
1676 
1677     void doPatch(crow::Response& res, const crow::Request& req,
1678                  const std::vector<std::string>& params) override
1679     {
1680         auto asyncResp = std::make_shared<AsyncResp>(res);
1681         if (params.size() != 1)
1682         {
1683             messages::internalError(asyncResp->res);
1684             return;
1685         }
1686 
1687         std::optional<std::string> newUserName;
1688         std::optional<std::string> password;
1689         std::optional<bool> enabled;
1690         std::optional<std::string> roleId;
1691         std::optional<bool> locked;
1692         if (!json_util::readJson(req, res, "UserName", newUserName, "Password",
1693                                  password, "RoleId", roleId, "Enabled", enabled,
1694                                  "Locked", locked))
1695         {
1696             return;
1697         }
1698 
1699         const std::string& username = params[0];
1700 
1701         // Perform a proper ConfigureSelf authority check.  If the
1702         // session is being used to PATCH a property other than
1703         // Password, then the ConfigureSelf privilege does not apply.
1704         // If the user is operating on an account not their own, then
1705         // their ConfigureSelf privilege does not apply.  In either
1706         // case, perform the authority check again without the user's
1707         // ConfigureSelf privilege.
1708         if ((username != req.session->username) ||
1709             (newUserName || enabled || roleId || locked))
1710         {
1711             if (!isAllowedWithoutConfigureSelf(req))
1712             {
1713                 BMCWEB_LOG_WARNING << "PATCH Password denied access";
1714                 asyncResp->res.clear();
1715                 messages::insufficientPrivilege(asyncResp->res);
1716                 return;
1717             }
1718         }
1719 
1720         // if user name is not provided in the patch method or if it
1721         // matches the user name in the URI, then we are treating it as updating
1722         // user properties other then username. If username provided doesn't
1723         // match the URI, then we are treating this as user rename request.
1724         if (!newUserName || (newUserName.value() == username))
1725         {
1726             updateUserProperties(asyncResp, username, password, enabled, roleId,
1727                                  locked);
1728             return;
1729         }
1730         else
1731         {
1732             crow::connections::systemBus->async_method_call(
1733                 [this, asyncResp, username, password(std::move(password)),
1734                  roleId(std::move(roleId)), enabled(std::move(enabled)),
1735                  newUser{std::string(*newUserName)},
1736                  locked(std::move(locked))](const boost::system::error_code ec,
1737                                             sdbusplus::message::message& m) {
1738                     if (ec)
1739                     {
1740                         userErrorMessageHandler(m.get_error(), asyncResp,
1741                                                 newUser, username);
1742                         return;
1743                     }
1744 
1745                     updateUserProperties(asyncResp, newUser, password, enabled,
1746                                          roleId, locked);
1747                 },
1748                 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1749                 "xyz.openbmc_project.User.Manager", "RenameUser", username,
1750                 *newUserName);
1751         }
1752     }
1753 
1754     void updateUserProperties(std::shared_ptr<AsyncResp> asyncResp,
1755                               const std::string& username,
1756                               std::optional<std::string> password,
1757                               std::optional<bool> enabled,
1758                               std::optional<std::string> roleId,
1759                               std::optional<bool> locked)
1760     {
1761         std::string dbusObjectPath = "/xyz/openbmc_project/user/" + username;
1762         dbus::utility::escapePathForDbus(dbusObjectPath);
1763 
1764         dbus::utility::checkDbusPathExists(
1765             dbusObjectPath,
1766             [dbusObjectPath(std::move(dbusObjectPath)), username,
1767              password(std::move(password)), roleId(std::move(roleId)),
1768              enabled(std::move(enabled)), locked(std::move(locked)),
1769              asyncResp{std::move(asyncResp)}](int rc) {
1770                 if (!rc)
1771                 {
1772                     messages::resourceNotFound(
1773                         asyncResp->res, "#ManagerAccount.v1_4_0.ManagerAccount",
1774                         username);
1775                     return;
1776                 }
1777 
1778                 if (password)
1779                 {
1780                     int retval = pamUpdatePassword(username, *password);
1781 
1782                     if (retval == PAM_USER_UNKNOWN)
1783                     {
1784                         messages::resourceNotFound(
1785                             asyncResp->res,
1786                             "#ManagerAccount.v1_4_0.ManagerAccount", username);
1787                     }
1788                     else if (retval == PAM_AUTHTOK_ERR)
1789                     {
1790                         // If password is invalid
1791                         messages::propertyValueFormatError(
1792                             asyncResp->res, *password, "Password");
1793                         BMCWEB_LOG_ERROR << "pamUpdatePassword Failed";
1794                     }
1795                     else if (retval != PAM_SUCCESS)
1796                     {
1797                         messages::internalError(asyncResp->res);
1798                         return;
1799                     }
1800                 }
1801 
1802                 if (enabled)
1803                 {
1804                     crow::connections::systemBus->async_method_call(
1805                         [asyncResp](const boost::system::error_code ec) {
1806                             if (ec)
1807                             {
1808                                 BMCWEB_LOG_ERROR << "D-Bus responses error: "
1809                                                  << ec;
1810                                 messages::internalError(asyncResp->res);
1811                                 return;
1812                             }
1813                             messages::success(asyncResp->res);
1814                             return;
1815                         },
1816                         "xyz.openbmc_project.User.Manager",
1817                         dbusObjectPath.c_str(),
1818                         "org.freedesktop.DBus.Properties", "Set",
1819                         "xyz.openbmc_project.User.Attributes", "UserEnabled",
1820                         std::variant<bool>{*enabled});
1821                 }
1822 
1823                 if (roleId)
1824                 {
1825                     std::string priv = getPrivilegeFromRoleId(*roleId);
1826                     if (priv.empty())
1827                     {
1828                         messages::propertyValueNotInList(asyncResp->res,
1829                                                          *roleId, "RoleId");
1830                         return;
1831                     }
1832                     if (priv == "priv-noaccess")
1833                     {
1834                         priv = "";
1835                     }
1836 
1837                     crow::connections::systemBus->async_method_call(
1838                         [asyncResp](const boost::system::error_code ec) {
1839                             if (ec)
1840                             {
1841                                 BMCWEB_LOG_ERROR << "D-Bus responses error: "
1842                                                  << ec;
1843                                 messages::internalError(asyncResp->res);
1844                                 return;
1845                             }
1846                             messages::success(asyncResp->res);
1847                         },
1848                         "xyz.openbmc_project.User.Manager",
1849                         dbusObjectPath.c_str(),
1850                         "org.freedesktop.DBus.Properties", "Set",
1851                         "xyz.openbmc_project.User.Attributes", "UserPrivilege",
1852                         std::variant<std::string>{priv});
1853                 }
1854 
1855                 if (locked)
1856                 {
1857                     // admin can unlock the account which is locked by
1858                     // successive authentication failures but admin should
1859                     // not be allowed to lock an account.
1860                     if (*locked)
1861                     {
1862                         messages::propertyValueNotInList(asyncResp->res, "true",
1863                                                          "Locked");
1864                         return;
1865                     }
1866 
1867                     crow::connections::systemBus->async_method_call(
1868                         [asyncResp](const boost::system::error_code ec) {
1869                             if (ec)
1870                             {
1871                                 BMCWEB_LOG_ERROR << "D-Bus responses error: "
1872                                                  << ec;
1873                                 messages::internalError(asyncResp->res);
1874                                 return;
1875                             }
1876                             messages::success(asyncResp->res);
1877                             return;
1878                         },
1879                         "xyz.openbmc_project.User.Manager",
1880                         dbusObjectPath.c_str(),
1881                         "org.freedesktop.DBus.Properties", "Set",
1882                         "xyz.openbmc_project.User.Attributes",
1883                         "UserLockedForFailedAttempt",
1884                         std::variant<bool>{*locked});
1885                 }
1886             });
1887     }
1888 
1889     void doDelete(crow::Response& res, const crow::Request& req,
1890                   const std::vector<std::string>& params) override
1891     {
1892         auto asyncResp = std::make_shared<AsyncResp>(res);
1893 
1894         if (params.size() != 1)
1895         {
1896             messages::internalError(asyncResp->res);
1897             return;
1898         }
1899 
1900         const std::string userPath = "/xyz/openbmc_project/user/" + params[0];
1901 
1902         crow::connections::systemBus->async_method_call(
1903             [asyncResp, username{std::move(params[0])}](
1904                 const boost::system::error_code ec) {
1905                 if (ec)
1906                 {
1907                     messages::resourceNotFound(
1908                         asyncResp->res, "#ManagerAccount.v1_4_0.ManagerAccount",
1909                         username);
1910                     return;
1911                 }
1912 
1913                 messages::accountRemoved(asyncResp->res);
1914             },
1915             "xyz.openbmc_project.User.Manager", userPath,
1916             "xyz.openbmc_project.Object.Delete", "Delete");
1917     }
1918 };
1919 
1920 } // namespace redfish
1921