xref: /openbmc/phosphor-user-manager/user_mgr.cpp (revision 8c5c4aab519130adb56f66b1477ff5ed82731926)
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 
17 #include "config.h"
18 
19 #include "user_mgr.hpp"
20 
21 #include "file.hpp"
22 #include "shadowlock.hpp"
23 #include "users.hpp"
24 
25 #include <grp.h>
26 #include <pwd.h>
27 #include <shadow.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include <phosphor-logging/elog-errors.hpp>
34 #include <phosphor-logging/elog.hpp>
35 #include <phosphor-logging/lg2.hpp>
36 #include <xyz/openbmc_project/Common/error.hpp>
37 #include <xyz/openbmc_project/User/Common/error.hpp>
38 
39 #include <algorithm>
40 #include <array>
41 #include <chrono>
42 #include <ctime>
43 #include <filesystem>
44 #include <fstream>
45 #include <numeric>
46 #include <regex>
47 #include <span>
48 #include <string>
49 #include <string_view>
50 #include <vector>
51 namespace phosphor
52 {
53 namespace user
54 {
55 
56 static constexpr const char* passwdFileName = "/etc/passwd";
57 static constexpr size_t ipmiMaxUserNameLen = 16;
58 static constexpr size_t systemMaxUserNameLen = 100;
59 static constexpr const char* grpSsh = "ssh";
60 static constexpr int success = 0;
61 static constexpr int failure = -1;
62 static constexpr long secondsPerDay = 60 * 60 * 24;
63 
64 uint8_t maxPasswdLength = MAX_PASSWORD_LENGTH;
65 // pam modules related
66 static constexpr const char* minPasswdLenProp = "minlen";
67 static constexpr const char* remOldPasswdCount = "remember";
68 static constexpr const char* maxFailedAttempt = "deny";
69 static constexpr const char* unlockTimeout = "unlock_time";
70 static constexpr const char* defaultFaillockConfigFile =
71     "/etc/security/faillock.conf";
72 static constexpr const char* defaultPWHistoryConfigFile =
73     "/etc/security/pwhistory.conf";
74 static constexpr const char* defaultPWQualityConfigFile =
75     "/etc/security/pwquality.conf";
76 
77 // Object Manager related
78 static constexpr const char* ldapMgrObjBasePath =
79     "/xyz/openbmc_project/user/ldap";
80 
81 // Object Mapper related
82 static constexpr const char* objMapperService =
83     "xyz.openbmc_project.ObjectMapper";
84 static constexpr const char* objMapperPath =
85     "/xyz/openbmc_project/object_mapper";
86 static constexpr const char* objMapperInterface =
87     "xyz.openbmc_project.ObjectMapper";
88 
89 using namespace phosphor::logging;
90 using InsufficientPermission =
91     sdbusplus::xyz::openbmc_project::Common::Error::InsufficientPermission;
92 using InternalFailure =
93     sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
94 using InvalidArgument =
95     sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
96 using UserNameExists =
97     sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameExists;
98 using UserNameDoesNotExist =
99     sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameDoesNotExist;
100 using UserNameGroupFail =
101     sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameGroupFail;
102 using NoResource =
103     sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
104 using Argument = xyz::openbmc_project::Common::InvalidArgument;
105 using GroupNameExists =
106     sdbusplus::xyz::openbmc_project::User::Common::Error::GroupNameExists;
107 using GroupNameDoesNotExists =
108     sdbusplus::xyz::openbmc_project::User::Common::Error::GroupNameDoesNotExist;
109 using UserProperty =
110     sdbusplus::common::xyz::openbmc_project::user::Manager::UserProperty;
111 
112 namespace
113 {
114 constexpr auto mfaConfPath = "/var/lib/usr_mgr.conf";
115 // The hardcoded groups in OpenBMC projects
116 constexpr std::array<const char*, 4> predefinedGroups = {
117     "redfish", "ipmi", "ssh", "hostconsole"};
118 
119 // These prefixes are for Dynamic Redfish authorization. See
120 // https://github.com/openbmc/docs/blob/master/designs/redfish-authorization.md
121 
122 // Base role and base privileges are added by Redfish implementation (e.g.,
123 // BMCWeb) at compile time
124 constexpr std::array<const char*, 4> allowedGroupPrefix = {
125     "openbmc_rfr_",  // OpenBMC Redfish Base Role
126     "openbmc_rfp_",  // OpenBMC Redfish Base Privileges
127     "openbmc_orfr_", // OpenBMC Redfish OEM Role
128     "openbmc_orfp_", // OpenBMC Redfish OEM Privileges
129 };
130 
131 struct SystemUserInfo
132 {
133     struct passwd pwd;
134     std::vector<char> buffer;
135 };
136 
checkAndThrowsForGroupChangeAllowed(const std::string & groupName)137 void checkAndThrowsForGroupChangeAllowed(const std::string& groupName)
138 {
139     bool allowed = false;
140     for (std::string_view prefix : allowedGroupPrefix)
141     {
142         if (groupName.starts_with(prefix))
143         {
144             allowed = true;
145             break;
146         }
147     }
148     if (!allowed)
149     {
150         lg2::error("Group name '{GROUP}' is not in the allowed list", "GROUP",
151                    groupName);
152         elog<InvalidArgument>(Argument::ARGUMENT_NAME("Group Name"),
153                               Argument::ARGUMENT_VALUE(groupName.c_str()));
154     }
155 }
156 
currentDate()157 long currentDate()
158 {
159     const auto date = std::chrono::duration_cast<std::chrono::days>(
160                           std::chrono::system_clock::now().time_since_epoch())
161                           .count();
162 
163     if (date > std::numeric_limits<long>::max())
164     {
165         return std::numeric_limits<long>::max();
166     }
167 
168     if (date < std::numeric_limits<long>::min())
169     {
170         return std::numeric_limits<long>::min();
171     }
172 
173     return date;
174 }
175 
daysToSeconds(const uint64_t days)176 uint64_t daysToSeconds(const uint64_t days)
177 {
178     const uint64_t dateSeconds =
179         std::chrono::duration_cast<std::chrono::seconds>(
180             std::chrono::days{days})
181             .count();
182 
183     return dateSeconds;
184 }
185 
secondsToDays(const uint64_t seconds)186 uint64_t secondsToDays(const uint64_t seconds)
187 {
188     const uint64_t dateDays = seconds / secondsPerDay;
189 
190     return dateDays;
191 }
192 
getSystemUser(const std::string & userName)193 std::unique_ptr<struct SystemUserInfo> getSystemUser(
194     const std::string& userName)
195 {
196     static auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
197     if (buflen <= 0)
198     {
199         // Use a default size if there is no hard limit suggested by sysconf()
200         buflen = 1024;
201     }
202 
203     auto res = std::make_unique<struct SystemUserInfo>();
204     res->buffer = std::vector<char>(buflen);
205 
206     struct passwd* pwdPtr = nullptr;
207 
208     auto status = getpwnam_r(userName.c_str(), &res->pwd, res->buffer.data(),
209                              res->buffer.size(), &pwdPtr);
210     // On success, getpwnam_r() returns zero, and set *pwdPtr to pwd.
211     // If no matching password record was found, these functions return 0
212     // and store NULL in *pwdPtr
213     if (!status && (&res->pwd == pwdPtr))
214     {
215         return res;
216     }
217 
218     return nullptr;
219 }
220 
221 } // namespace
222 
getCSVFromVector(std::span<const std::string> vec)223 std::string getCSVFromVector(std::span<const std::string> vec)
224 {
225     if (vec.empty())
226     {
227         return "";
228     }
229     return std::accumulate(std::next(vec.begin()), vec.end(), vec[0],
230                            [](std::string&& val, std::string_view element) {
231                                val += ',';
232                                val += element;
233                                return val;
234                            });
235 }
236 
removeStringFromCSV(std::string & csvStr,const std::string & delStr)237 bool removeStringFromCSV(std::string& csvStr, const std::string& delStr)
238 {
239     std::string::size_type delStrPos = csvStr.find(delStr);
240     if (delStrPos != std::string::npos)
241     {
242         // need to also delete the comma char
243         if (delStrPos == 0)
244         {
245             csvStr.erase(delStrPos, delStr.size() + 1);
246         }
247         else
248         {
249             csvStr.erase(delStrPos - 1, delStr.size() + 1);
250         }
251         return true;
252     }
253     return false;
254 }
255 
isUserExist(const std::string & userName) const256 bool UserMgr::isUserExist(const std::string& userName) const
257 {
258     if (userName.empty())
259     {
260         lg2::error("User name is empty");
261         elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
262                               Argument::ARGUMENT_VALUE("Null"));
263     }
264     if (usersList.find(userName) == usersList.end())
265     {
266         return false;
267     }
268     return true;
269 }
270 
isUserExistSystem(const std::string & userName)271 bool UserMgr::isUserExistSystem(const std::string& userName)
272 {
273     if (userName.empty())
274     {
275         lg2::error("User name is empty");
276         elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
277                               Argument::ARGUMENT_VALUE("Null"));
278     }
279 
280     return getSystemUser(userName) != nullptr;
281 }
282 
throwForUserDoesNotExist(const std::string & userName) const283 void UserMgr::throwForUserDoesNotExist(const std::string& userName) const
284 {
285     if (!isUserExist(userName))
286     {
287         lg2::error("User '{USERNAME}' does not exist", "USERNAME", userName);
288         elog<UserNameDoesNotExist>();
289     }
290 }
291 
checkAndThrowForDisallowedGroupCreation(const std::string & groupName)292 void UserMgr::checkAndThrowForDisallowedGroupCreation(
293     const std::string& groupName)
294 {
295     if (groupName.size() > maxSystemGroupNameLength ||
296         !std::regex_match(groupName.c_str(),
297                           std::regex("[a-zA-Z_][a-zA-Z_0-9]*")))
298     {
299         lg2::error("Invalid group name '{GROUP}'", "GROUP", groupName);
300         elog<InvalidArgument>(Argument::ARGUMENT_NAME("Group Name"),
301                               Argument::ARGUMENT_VALUE(groupName.c_str()));
302     }
303     checkAndThrowsForGroupChangeAllowed(groupName);
304 }
305 
throwForUserExists(const std::string & userName)306 void UserMgr::throwForUserExists(const std::string& userName)
307 {
308     if (isUserExist(userName))
309     {
310         lg2::error("User '{USERNAME}' already exists", "USERNAME", userName);
311         elog<UserNameExists>();
312     }
313 }
314 
throwForUserNameConstraints(const std::string & userName,const std::vector<std::string> & groupNames)315 void UserMgr::throwForUserNameConstraints(
316     const std::string& userName, const std::vector<std::string>& groupNames)
317 {
318     if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
319         groupNames.end())
320     {
321         if (userName.length() > ipmiMaxUserNameLen)
322         {
323             lg2::error("User '{USERNAME}' exceeds IPMI username length limit "
324                        "({LENGTH} > {LIMIT})",
325                        "USERNAME", userName, "LENGTH", userName.length(),
326                        "LIMIT", ipmiMaxUserNameLen);
327             elog<UserNameGroupFail>(
328                 xyz::openbmc_project::User::Common::UserNameGroupFail::REASON(
329                     "IPMI length"));
330         }
331     }
332     if (userName.length() > systemMaxUserNameLen)
333     {
334         lg2::error("User '{USERNAME}' exceeds system username length limit "
335                    "({LENGTH} > {LIMIT})",
336                    "USERNAME", userName, "LENGTH", userName.length(), "LIMIT",
337                    systemMaxUserNameLen);
338         elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
339                               Argument::ARGUMENT_VALUE("Invalid length"));
340     }
341     if (!std::regex_match(userName.c_str(),
342                           std::regex("[a-zA-Z_][a-zA-Z_0-9]*")))
343     {
344         lg2::error("Invalid username '{USERNAME}'", "USERNAME", userName);
345         elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
346                               Argument::ARGUMENT_VALUE("Invalid data"));
347     }
348 }
349 
throwForMaxGrpUserCount(const std::vector<std::string> & groupNames)350 void UserMgr::throwForMaxGrpUserCount(
351     const std::vector<std::string>& groupNames)
352 {
353     if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
354         groupNames.end())
355     {
356         if (getIpmiUsersCount() >= ipmiMaxUsers)
357         {
358             lg2::error("IPMI user limit reached");
359             elog<NoResource>(
360                 xyz::openbmc_project::User::Common::NoResource::REASON(
361                     "IPMI user limit reached"));
362         }
363     }
364     else
365     {
366         if (usersList.size() > 0 && (usersList.size() - getIpmiUsersCount()) >=
367                                         (maxSystemUsers - ipmiMaxUsers))
368         {
369             lg2::error("Non-ipmi User limit reached");
370             elog<NoResource>(
371                 xyz::openbmc_project::User::Common::NoResource::REASON(
372                     "Non-ipmi user limit reached"));
373         }
374     }
375     return;
376 }
377 
throwForInvalidPrivilege(const std::string & priv)378 void UserMgr::throwForInvalidPrivilege(const std::string& priv)
379 {
380     if (!priv.empty() &&
381         (std::find(privMgr.begin(), privMgr.end(), priv) == privMgr.end()))
382     {
383         lg2::error("Invalid privilege '{PRIVILEGE}'", "PRIVILEGE", priv);
384         elog<InvalidArgument>(Argument::ARGUMENT_NAME("Privilege"),
385                               Argument::ARGUMENT_VALUE(priv.c_str()));
386     }
387 }
388 
throwForInvalidGroups(const std::vector<std::string> & groupNames)389 void UserMgr::throwForInvalidGroups(const std::vector<std::string>& groupNames)
390 {
391     for (auto& group : groupNames)
392     {
393         if (std::find(groupsMgr.begin(), groupsMgr.end(), group) ==
394             groupsMgr.end())
395         {
396             lg2::error("Invalid Group Name '{GROUPNAME}'", "GROUPNAME", group);
397             elog<InvalidArgument>(Argument::ARGUMENT_NAME("GroupName"),
398                                   Argument::ARGUMENT_VALUE(group.c_str()));
399         }
400     }
401 }
402 
readAllGroupsOnSystem()403 std::vector<std::string> UserMgr::readAllGroupsOnSystem()
404 {
405     std::vector<std::string> allGroups = {predefinedGroups.begin(),
406                                           predefinedGroups.end()};
407     // rewinds to the beginning of the group database
408     setgrent();
409     struct group* gr = getgrent();
410     while (gr != nullptr)
411     {
412         std::string group(gr->gr_name);
413         for (std::string_view prefix : allowedGroupPrefix)
414         {
415             if (group.starts_with(prefix))
416             {
417                 allGroups.push_back(gr->gr_name);
418             }
419         }
420         gr = getgrent();
421     }
422     // close the group database
423     endgrent();
424     return allGroups;
425 }
426 
createUserImpl(const std::string & userName,UserCreateMap props)427 void UserMgr::createUserImpl(const std::string& userName, UserCreateMap props)
428 {
429     auto priv = std::get<std::string>(props[UserProperty::Privilege]);
430     auto enabled = std::get<bool>(props[UserProperty::Enabled]);
431     auto groupNames =
432         std::get<std::vector<std::string>>(props[UserProperty::GroupNames]);
433 
434     auto passwordExpiration = getDefaultPasswordExpiration();
435     if (props.contains(UserProperty::PasswordExpiration))
436         passwordExpiration =
437             std::get<uint64_t>(props[UserProperty::PasswordExpiration]);
438 
439     throwForInvalidPrivilege(priv);
440     throwForInvalidGroups(groupNames);
441     // All user management lock has to be based on /etc/shadow
442     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
443     throwForUserExists(userName);
444     throwForUserNameConstraints(userName, groupNames);
445     throwForMaxGrpUserCount(groupNames);
446 
447     std::string groups = getCSVFromVector(groupNames);
448     bool sshRequested = removeStringFromCSV(groups, grpSsh);
449 
450     // treat privilege as a group - This is to avoid using different file to
451     // store the same.
452     if (!priv.empty())
453     {
454         if (groups.size() != 0)
455         {
456             groups += ",";
457         }
458         groups += priv;
459     }
460     try
461     {
462         executeUserAdd(userName.c_str(), groups.c_str(), sshRequested, enabled);
463     }
464     catch (const InternalFailure& e)
465     {
466         if (isUserExistSystem(userName))
467         {
468             lg2::warning(
469                 "User created despite error, attempting to delete user",
470                 "USERNAME", userName);
471             executeUserDelete(userName.c_str());
472         }
473         else
474         {
475             lg2::error("Unable to create new user '{USERNAME}'", "USERNAME",
476                        userName);
477         }
478         elog<InternalFailure>();
479     }
480 
481     // Add the users object before sending out the signal
482     sdbusplus::message::object_path tempObjPath(usersObjPath);
483     tempObjPath /= userName;
484     std::string userObj(tempObjPath);
485     std::sort(groupNames.begin(), groupNames.end());
486     usersList.emplace(userName, std::make_unique<phosphor::user::Users>(
487                                     bus, userObj.c_str(), groupNames, priv,
488                                     enabled, passwordExpiration, *this));
489     serializer.store();
490     lg2::info("User '{USERNAME}' created successfully", "USERNAME", userName);
491 
492     return;
493 }
494 
createUser(std::string userName,std::vector<std::string> groupNames,std::string priv,bool enabled)495 void UserMgr::createUser(std::string userName,
496                          std::vector<std::string> groupNames, std::string priv,
497                          bool enabled)
498 {
499     UserCreateMap props;
500     props[UserProperty::GroupNames] = std::move(groupNames);
501     props[UserProperty::Privilege] = std::move(priv);
502     props[UserProperty::Enabled] = enabled;
503 
504     createUserImpl(userName, props);
505     lg2::info("User '{USERNAME}' created successfully", "USERNAME", userName);
506 }
507 
deleteUserImpl(const std::string & userName)508 void UserMgr::deleteUserImpl(const std::string& userName)
509 {
510     // All user management lock has to be based on /etc/shadow
511     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
512     try
513     {
514         // Clear user fail records
515         executeUserClearFailRecords(userName.c_str());
516 
517         executeUserDelete(userName.c_str());
518     }
519     catch (const InternalFailure& e)
520     {
521         if (!isUserExistSystem(userName))
522         {
523             lg2::warning(
524                 "Delete User '{USERNAME}' failed, and user is no longer present, treating as success",
525                 "USERNAME", userName);
526         }
527         else
528         {
529             lg2::error("Delete User '{USERNAME}' failed", "USERNAME", userName);
530             elog<InternalFailure>();
531         }
532     }
533 
534     usersList.erase(userName);
535     serializer.store();
536     lg2::info("User '{USERNAME}' deleted successfully", "USERNAME", userName);
537     return;
538 }
539 
deleteUser(std::string userName)540 void UserMgr::deleteUser(std::string userName)
541 {
542     throwForUserDoesNotExist(userName);
543     deleteUserImpl(userName);
544     lg2::info("User '{USERNAME}' deleted successfully", "USERNAME", userName);
545 }
546 
checkDeleteGroupConstraints(const std::string & groupName)547 void UserMgr::checkDeleteGroupConstraints(const std::string& groupName)
548 {
549     if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) ==
550         groupsMgr.end())
551     {
552         lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
553         elog<GroupNameDoesNotExists>();
554     }
555     checkAndThrowsForGroupChangeAllowed(groupName);
556 }
557 
deleteGroup(std::string groupName)558 void UserMgr::deleteGroup(std::string groupName)
559 {
560     checkDeleteGroupConstraints(groupName);
561     try
562     {
563         executeGroupDeletion(groupName.c_str());
564     }
565     catch (const InternalFailure& e)
566     {
567         lg2::error("Failed to delete group '{GROUP}'", "GROUP", groupName);
568         elog<InternalFailure>();
569     }
570 
571     groupsMgr.erase(std::find(groupsMgr.begin(), groupsMgr.end(), groupName));
572     UserMgrIface::allGroups(groupsMgr);
573     lg2::info("Successfully deleted group '{GROUP}'", "GROUP", groupName);
574 }
575 
checkCreateGroupConstraints(const std::string & groupName)576 void UserMgr::checkCreateGroupConstraints(const std::string& groupName)
577 {
578     if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) !=
579         groupsMgr.end())
580     {
581         lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
582         elog<GroupNameExists>();
583     }
584     checkAndThrowForDisallowedGroupCreation(groupName);
585     if (groupsMgr.size() >= maxSystemGroupCount)
586     {
587         lg2::error("Group limit reached");
588         elog<NoResource>(xyz::openbmc_project::User::Common::NoResource::REASON(
589             "Group limit reached"));
590     }
591 }
592 
createGroup(std::string groupName)593 void UserMgr::createGroup(std::string groupName)
594 {
595     checkCreateGroupConstraints(groupName);
596     try
597     {
598         executeGroupCreation(groupName.c_str());
599     }
600     catch (const InternalFailure& e)
601     {
602         lg2::error("Failed to create group '{GROUP}'", "GROUP", groupName);
603         elog<InternalFailure>();
604     }
605     groupsMgr.push_back(groupName);
606     UserMgrIface::allGroups(groupsMgr);
607 }
608 
renameUser(std::string userName,std::string newUserName)609 void UserMgr::renameUser(std::string userName, std::string newUserName)
610 {
611     bool err = false;
612     // All user management lock has to be based on /etc/shadow
613     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
614     throwForUserDoesNotExist(userName);
615     throwForUserExists(newUserName);
616     throwForUserNameConstraints(newUserName,
617                                 usersList[userName].get()->userGroups());
618     try
619     {
620         executeUserRename(userName.c_str(), newUserName.c_str());
621     }
622     catch (const InternalFailure& e)
623     {
624         if (isUserExistSystem(newUserName))
625         {
626             lg2::error(
627                 "Rename '{USERNAME}' to '{NEWUSERNAME}' partially failed",
628                 "USERNAME", userName, "NEWUSERNAME", newUserName);
629             err = true;
630         }
631         else
632         {
633             lg2::error("Rename '{USERNAME}' to '{NEWUSERNAME}' failed",
634                        "USERNAME", userName, "NEWUSERNAME", newUserName);
635             elog<InternalFailure>();
636         }
637     }
638     const auto& user = usersList[userName];
639     std::string priv = user.get()->userPrivilege();
640     std::vector<std::string> groupNames = user.get()->userGroups();
641     bool enabled = user.get()->userEnabled();
642     uint64_t passwordExpiration = user.get()->passwordExpiration();
643     sdbusplus::message::object_path tempObjPath(usersObjPath);
644     tempObjPath /= newUserName;
645     std::string newUserObj(tempObjPath);
646     // Special group 'ipmi' needs a way to identify user renamed, in order to
647     // update encrypted password. It can't rely only on InterfacesRemoved &
648     // InterfacesAdded. So first send out userRenamed signal.
649     this->userRenamed(userName, newUserName);
650     usersList.erase(userName);
651     usersList.emplace(newUserName,
652                       std::make_unique<phosphor::user::Users>(
653                           bus, newUserObj.c_str(), groupNames, priv, enabled,
654                           passwordExpiration, *this));
655 
656     if (err)
657     {
658         elog<InternalFailure>();
659     }
660     return;
661 }
662 
updateGroupsAndPriv(const std::string & userName,std::vector<std::string> groupNames,const std::string & priv)663 void UserMgr::updateGroupsAndPriv(const std::string& userName,
664                                   std::vector<std::string> groupNames,
665                                   const std::string& priv)
666 {
667     throwForInvalidPrivilege(priv);
668     throwForInvalidGroups(groupNames);
669     // All user management lock has to be based on /etc/shadow
670     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
671     throwForUserDoesNotExist(userName);
672     const std::vector<std::string>& oldGroupNames =
673         usersList[userName].get()->userGroups();
674     std::vector<std::string> groupDiff;
675     // Note: already dealing with sorted group lists.
676     std::set_symmetric_difference(oldGroupNames.begin(), oldGroupNames.end(),
677                                   groupNames.begin(), groupNames.end(),
678                                   std::back_inserter(groupDiff));
679     if (std::find(groupDiff.begin(), groupDiff.end(), "ipmi") !=
680         groupDiff.end())
681     {
682         throwForUserNameConstraints(userName, groupNames);
683         throwForMaxGrpUserCount(groupNames);
684     }
685 
686     std::string groups = getCSVFromVector(groupNames);
687     bool sshRequested = removeStringFromCSV(groups, grpSsh);
688 
689     // treat privilege as a group - This is to avoid using different file to
690     // store the same.
691     if (!priv.empty())
692     {
693         if (groups.size() != 0)
694         {
695             groups += ",";
696         }
697         groups += priv;
698     }
699     try
700     {
701         executeUserModify(userName.c_str(), groups.c_str(), sshRequested);
702     }
703     catch (const InternalFailure& e)
704     {
705         lg2::error(
706             "Unable to modify user privilege / groups for user '{USERNAME}'",
707             "USERNAME", userName);
708         elog<InternalFailure>();
709     }
710 
711     std::sort(groupNames.begin(), groupNames.end());
712     usersList[userName]->setUserGroups(groupNames);
713     usersList[userName]->setUserPrivilege(priv);
714     lg2::info("User '{USERNAME}' groups / privilege updated successfully",
715               "USERNAME", userName);
716 }
717 
minPasswordLength(uint8_t value)718 uint8_t UserMgr::minPasswordLength(uint8_t value)
719 {
720     if (value == AccountPolicyIface::minPasswordLength())
721     {
722         return value;
723     }
724     if (value < minPasswdLength || value > maxPasswdLength)
725     {
726         std::string valueStr = std::to_string(value);
727         lg2::error("Attempting to set minPasswordLength to {VALUE}, less than "
728                    "{MINPASSWORDLENGTH} or greater than {MAXPASSWORDLENGTH}",
729                    "VALUE", value, "MINPASSWORDLENGTH", minPasswdLength,
730                    "MAXPASSWORDLENGTH", maxPasswdLength);
731         elog<InvalidArgument>(Argument::ARGUMENT_NAME("minPasswordLength"),
732                               Argument::ARGUMENT_VALUE(valueStr.data()));
733     }
734     if (setPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
735                               std::to_string(value)) != success)
736     {
737         lg2::error("Unable to set minPasswordLength to {VALUE}", "VALUE",
738                    value);
739         elog<InternalFailure>();
740     }
741     return AccountPolicyIface::minPasswordLength(value);
742 }
743 
rememberOldPasswordTimes(uint8_t value)744 uint8_t UserMgr::rememberOldPasswordTimes(uint8_t value)
745 {
746     if (value == AccountPolicyIface::rememberOldPasswordTimes())
747     {
748         return value;
749     }
750     if (setPamModuleConfValue(pwHistoryConfigFile, remOldPasswdCount,
751                               std::to_string(value)) != success)
752     {
753         lg2::error("Unable to set rememberOldPasswordTimes to {VALUE}", "VALUE",
754                    value);
755         elog<InternalFailure>();
756     }
757     return AccountPolicyIface::rememberOldPasswordTimes(value);
758 }
759 
maxLoginAttemptBeforeLockout(uint16_t value)760 uint16_t UserMgr::maxLoginAttemptBeforeLockout(uint16_t value)
761 {
762     if (value == AccountPolicyIface::maxLoginAttemptBeforeLockout())
763     {
764         return value;
765     }
766     if (setPamModuleConfValue(faillockConfigFile, maxFailedAttempt,
767                               std::to_string(value)) != success)
768     {
769         lg2::error("Unable to set maxLoginAttemptBeforeLockout to {VALUE}",
770                    "VALUE", value);
771         elog<InternalFailure>();
772     }
773     return AccountPolicyIface::maxLoginAttemptBeforeLockout(value);
774 }
775 
accountUnlockTimeout(uint32_t value)776 uint32_t UserMgr::accountUnlockTimeout(uint32_t value)
777 {
778     if (value == AccountPolicyIface::accountUnlockTimeout())
779     {
780         return value;
781     }
782     if (setPamModuleConfValue(faillockConfigFile, unlockTimeout,
783                               std::to_string(value)) != success)
784     {
785         lg2::error("Unable to set accountUnlockTimeout to {VALUE}", "VALUE",
786                    value);
787         elog<InternalFailure>();
788     }
789     return AccountPolicyIface::accountUnlockTimeout(value);
790 }
791 
getPamModuleConfValue(const std::string & confFile,const std::string & argName,std::string & argValue)792 int UserMgr::getPamModuleConfValue(const std::string& confFile,
793                                    const std::string& argName,
794                                    std::string& argValue)
795 {
796     std::ifstream fileToRead(confFile, std::ios::in);
797     if (!fileToRead.is_open())
798     {
799         lg2::error("Failed to open pam configuration file {FILENAME}",
800                    "FILENAME", confFile);
801         return failure;
802     }
803     std::string line;
804     auto argSearch = argName + "=";
805     size_t startPos = 0;
806     size_t endPos = 0;
807     while (getline(fileToRead, line))
808     {
809         // skip comments section starting with #
810         if ((startPos = line.find('#')) != std::string::npos)
811         {
812             if (startPos == 0)
813             {
814                 continue;
815             }
816             // skip comments after meaningful section and process those
817             line = line.substr(0, startPos);
818         }
819         if ((startPos = line.find(argSearch)) != std::string::npos)
820         {
821             if ((endPos = line.find(' ', startPos)) == std::string::npos)
822             {
823                 endPos = line.size();
824             }
825             startPos += argSearch.size();
826             argValue = line.substr(startPos, endPos - startPos);
827             return success;
828         }
829     }
830     return failure;
831 }
832 
setPamModuleConfValue(const std::string & confFile,const std::string & argName,const std::string & argValue)833 int UserMgr::setPamModuleConfValue(const std::string& confFile,
834                                    const std::string& argName,
835                                    const std::string& argValue)
836 {
837     std::string tmpConfFile = confFile + "_tmp";
838     std::ifstream fileToRead(confFile, std::ios::in);
839     std::ofstream fileToWrite(tmpConfFile, std::ios::out);
840     if (!fileToRead.is_open() || !fileToWrite.is_open())
841     {
842         lg2::error("Failed to open pam configuration file {FILENAME}",
843                    "FILENAME", confFile);
844         // Delete the unused tmp file
845         std::remove(tmpConfFile.c_str());
846         return failure;
847     }
848     std::string line;
849     auto argSearch = argName + "=";
850     size_t startPos = 0;
851     size_t endPos = 0;
852     bool found = false;
853     while (getline(fileToRead, line))
854     {
855         // skip comments section starting with #
856         if ((startPos = line.find('#')) != std::string::npos)
857         {
858             if (startPos == 0)
859             {
860                 fileToWrite << line << std::endl;
861                 continue;
862             }
863             // skip comments after meaningful section and process those
864             line = line.substr(0, startPos);
865         }
866         if ((startPos = line.find(argSearch)) != std::string::npos)
867         {
868             if ((endPos = line.find(' ', startPos)) == std::string::npos)
869             {
870                 endPos = line.size();
871             }
872             startPos += argSearch.size();
873             fileToWrite << line.substr(0, startPos) << argValue
874                         << line.substr(endPos, line.size() - endPos)
875                         << std::endl;
876             found = true;
877             continue;
878         }
879         fileToWrite << line << std::endl;
880     }
881     fileToWrite.close();
882     fileToRead.close();
883     if (found)
884     {
885         if (std::rename(tmpConfFile.c_str(), confFile.c_str()) == 0)
886         {
887             return success;
888         }
889     }
890     // No changes, so delete the unused tmp file
891     std::remove(tmpConfFile.c_str());
892     return failure;
893 }
894 
userEnable(const std::string & userName,bool enabled)895 void UserMgr::userEnable(const std::string& userName, bool enabled)
896 {
897     // All user management lock has to be based on /etc/shadow
898     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
899     throwForUserDoesNotExist(userName);
900     try
901     {
902         executeUserModifyUserEnable(userName.c_str(), enabled);
903     }
904     catch (const InternalFailure& e)
905     {
906         lg2::error("Unable to modify user enabled state for '{USERNAME}'",
907                    "USERNAME", userName);
908         elog<InternalFailure>();
909     }
910 
911     usersList[userName]->setUserEnabled(enabled);
912     lg2::info("User '{USERNAME}' has been {STATUS}", "USERNAME", userName,
913               "STATUS", enabled ? "Enabled" : "Disabled");
914 }
915 
916 /**
917  * faillock app will provide the user failed login list with when the attempt
918  * was made, the type, the source, and if it's valid.
919  *
920  * Valid in this case means that the attempt was made within the fail_interval
921  * time. So, we can check this list for the number of valid entries (lines
922  * ending with 'V') compared to the maximum allowed to determine if the user is
923  * locked out.
924  *
925  * This data is only refreshed when an attempt is made, so if the user appears
926  * to be locked out, we must also check if the most recent attempt was older
927  * than the unlock_time to know if the user has since been unlocked.
928  **/
parseFaillockForLockout(const std::vector<std::string> & faillockOutput)929 bool UserMgr::parseFaillockForLockout(
930     const std::vector<std::string>& faillockOutput)
931 {
932     uint16_t failAttempts = 0;
933     time_t lastFailedAttempt{};
934     for (const std::string& line : faillockOutput)
935     {
936         if (!line.ends_with("V"))
937         {
938             continue;
939         }
940 
941         // Count this failed attempt
942         failAttempts++;
943 
944         // Update the last attempt time
945         // First get the "when" which is the first two words (date and time)
946         size_t pos = line.find(" ");
947         if (pos == std::string::npos)
948         {
949             continue;
950         }
951         pos = line.find(" ", pos + 1);
952         if (pos == std::string::npos)
953         {
954             continue;
955         }
956         std::string failDateTime = line.substr(0, pos);
957 
958         // NOTE: Cannot use std::get_time() here as the implementation of %y in
959         // libstdc++ does not match POSIX strptime() before gcc 12.1.0
960         // https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=a8d3c98746098e2784be7144c1ccc9fcc34a0888
961         std::tm tmStruct = {};
962         if (!strptime(failDateTime.c_str(), "%F %T", &tmStruct))
963         {
964             lg2::error("Failed to parse latest failure date/time");
965             elog<InternalFailure>();
966         }
967 
968         time_t failTimestamp = std::mktime(&tmStruct);
969         lastFailedAttempt = std::max(failTimestamp, lastFailedAttempt);
970     }
971 
972     if (failAttempts < AccountPolicyIface::maxLoginAttemptBeforeLockout())
973     {
974         return false;
975     }
976 
977     if (lastFailedAttempt +
978             static_cast<time_t>(AccountPolicyIface::accountUnlockTimeout()) <=
979         std::time(NULL))
980     {
981         return false;
982     }
983 
984     return true;
985 }
986 
userLockedForFailedAttempt(const std::string & userName)987 bool UserMgr::userLockedForFailedAttempt(const std::string& userName)
988 {
989     // All user management lock has to be based on /etc/shadow
990     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
991     if (AccountPolicyIface::maxLoginAttemptBeforeLockout() == 0)
992     {
993         return false;
994     }
995 
996     std::vector<std::string> output;
997     try
998     {
999         output = getFailedAttempt(userName.c_str());
1000     }
1001     catch (const InternalFailure& e)
1002     {
1003         lg2::error("Unable to read login failure counter");
1004         elog<InternalFailure>();
1005     }
1006 
1007     return parseFaillockForLockout(output);
1008 }
1009 
userLockedForFailedAttempt(const std::string & userName,const bool & value)1010 bool UserMgr::userLockedForFailedAttempt(const std::string& userName,
1011                                          const bool& value)
1012 {
1013     // All user management lock has to be based on /etc/shadow
1014     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1015     if (value == true)
1016     {
1017         return userLockedForFailedAttempt(userName);
1018     }
1019 
1020     try
1021     {
1022         // Clear user fail records
1023         executeUserClearFailRecords(userName.c_str());
1024     }
1025     catch (const InternalFailure& e)
1026     {
1027         lg2::error("Unable to reset login failure counter");
1028         elog<InternalFailure>();
1029     }
1030 
1031     return userLockedForFailedAttempt(userName);
1032 }
1033 
userPasswordExpired(const std::string & userName)1034 bool UserMgr::userPasswordExpired(const std::string& userName)
1035 {
1036     // All user management lock has to be based on /etc/shadow
1037     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1038 
1039     struct spwd spwd{};
1040     struct spwd* spwdPtr = nullptr;
1041     auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1042     if (buflen <= 0)
1043     {
1044         // Use a default size if there is no hard limit suggested by sysconf()
1045         buflen = 1024;
1046     }
1047     std::vector<char> buffer(buflen);
1048     auto status =
1049         getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen, &spwdPtr);
1050     // On success, getspnam_r() returns zero, and sets *spwdPtr to spwd.
1051     // If no matching password record was found, these functions return 0
1052     // and store NULL in *spwdPtr
1053     if ((status == 0) && (&spwd == spwdPtr))
1054     {
1055         // Determine password validity per "chage" docs, where:
1056         //   spwd.sp_lstchg == 0 means password is expired, and
1057         //   spwd.sp_max == -1 means the password does not expire.
1058         long today = static_cast<long>(time(NULL)) / secondsPerDay;
1059         if ((spwd.sp_lstchg == 0) ||
1060             ((spwd.sp_max != -1) && ((spwd.sp_max + spwd.sp_lstchg) < today)))
1061         {
1062             return true;
1063         }
1064     }
1065     else
1066     {
1067         // User entry is missing in /etc/shadow, indicating no SHA password.
1068         // Treat this as new user without password entry in /etc/shadow
1069         // TODO: Add property to indicate user password was not set yet
1070         // https://github.com/openbmc/phosphor-user-manager/issues/8
1071         return false;
1072     }
1073 
1074     return false;
1075 }
1076 
getUserAndSshGrpList()1077 UserSSHLists UserMgr::getUserAndSshGrpList()
1078 {
1079     // All user management lock has to be based on /etc/shadow
1080     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1081 
1082     std::vector<std::string> userList;
1083     std::vector<std::string> sshUsersList;
1084     struct passwd pw, *pwp = nullptr;
1085     std::array<char, 1024> buffer{};
1086 
1087     phosphor::user::File passwd(passwdFileName, "r");
1088     if ((passwd)() == NULL)
1089     {
1090         lg2::error("Error opening {FILENAME}", "FILENAME", passwdFileName);
1091         elog<InternalFailure>();
1092     }
1093 
1094     while (true)
1095     {
1096         auto r = fgetpwent_r((passwd)(), &pw, buffer.data(), buffer.max_size(),
1097                              &pwp);
1098         if ((r != 0) || (pwp == NULL))
1099         {
1100             // Any error, break the loop.
1101             break;
1102         }
1103 #ifdef ENABLE_ROOT_USER_MGMT
1104         // Add all users whose UID >= 1000 and < 65534
1105         // and special UID 0.
1106         if ((pwp->pw_uid == 0) ||
1107             ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534)))
1108 #else
1109         // Add all users whose UID >=1000 and < 65534
1110         if ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534))
1111 #endif
1112         {
1113             std::string userName(pwp->pw_name);
1114             userList.emplace_back(userName);
1115 
1116             // ssh doesn't have separate group. Check login shell entry to
1117             // get all users list which are member of ssh group.
1118             std::string loginShell(pwp->pw_shell);
1119             if (loginShell == "/bin/sh")
1120             {
1121                 sshUsersList.emplace_back(userName);
1122             }
1123         }
1124     }
1125     endpwent();
1126     return std::make_pair(std::move(userList), std::move(sshUsersList));
1127 }
1128 
getIpmiUsersCount()1129 size_t UserMgr::getIpmiUsersCount()
1130 {
1131     std::vector<std::string> userList = getUsersInGroup("ipmi");
1132     return userList.size();
1133 }
1134 
getNonIpmiUsersCount()1135 size_t UserMgr::getNonIpmiUsersCount()
1136 {
1137     std::vector<std::string> ipmiUsers = getUsersInGroup("ipmi");
1138     return usersList.size() - ipmiUsers.size();
1139 }
1140 
isUserEnabled(const std::string & userName)1141 bool UserMgr::isUserEnabled(const std::string& userName)
1142 {
1143     // All user management lock has to be based on /etc/shadow
1144     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1145     std::array<char, 4096> buffer{};
1146     struct spwd spwd;
1147     struct spwd* resultPtr = nullptr;
1148     int status = getspnam_r(userName.c_str(), &spwd, buffer.data(),
1149                             buffer.max_size(), &resultPtr);
1150     if (!status && (&spwd == resultPtr))
1151     {
1152         // according to chage/usermod code -1 means that account does not expire
1153         // https://github.com/shadow-maint/shadow/blob/7a796897e52293efe9e210ab8da32b7aefe65591/src/chage.c
1154         if (resultPtr->sp_expire < 0)
1155         {
1156             return true;
1157         }
1158 
1159         // check account expiration date against current date
1160         if (resultPtr->sp_expire > currentDate())
1161         {
1162             return true;
1163         }
1164 
1165         return false;
1166     }
1167     return false; // assume user is disabled for any error.
1168 }
1169 
getUsersInGroup(const std::string & groupName)1170 std::vector<std::string> UserMgr::getUsersInGroup(const std::string& groupName)
1171 {
1172     std::vector<std::string> usersInGroup;
1173     // Should be more than enough to get the pwd structure.
1174     std::array<char, 4096> buffer{};
1175     struct group grp;
1176     struct group* resultPtr = nullptr;
1177 
1178     int status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1179                             buffer.max_size(), &resultPtr);
1180 
1181     if (!status && (&grp == resultPtr))
1182     {
1183         for (; *(grp.gr_mem) != NULL; ++(grp.gr_mem))
1184         {
1185             usersInGroup.emplace_back(*(grp.gr_mem));
1186         }
1187     }
1188     else
1189     {
1190         lg2::error("Group '{GROUPNAME}' not found", "GROUPNAME", groupName);
1191         // Don't throw error, just return empty userList - fallback
1192     }
1193     return usersInGroup;
1194 }
1195 
getPrivilegeMapperObject(void)1196 DbusUserObj UserMgr::getPrivilegeMapperObject(void)
1197 {
1198     DbusUserObj objects;
1199     try
1200     {
1201         std::string basePath = "/xyz/openbmc_project/user/ldap/openldap";
1202         std::string interface = "xyz.openbmc_project.User.Ldap.Config";
1203 
1204         auto ldapMgmtService =
1205             getServiceName(std::move(basePath), std::move(interface));
1206         auto method = bus.new_method_call(
1207             ldapMgmtService.c_str(), ldapMgrObjBasePath,
1208             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1209 
1210         auto reply = bus.call(method);
1211         reply.read(objects);
1212     }
1213     catch (const InternalFailure& e)
1214     {
1215         lg2::error("Unable to get the User Service: {ERR}", "ERR", e);
1216         throw;
1217     }
1218     catch (const sdbusplus::exception_t& e)
1219     {
1220         lg2::error("Failed to execute GetManagedObjects at {PATH}: {ERR}",
1221                    "PATH", ldapMgrObjBasePath, "ERR", e);
1222         throw;
1223     }
1224     return objects;
1225 }
1226 
getServiceName(std::string && path,std::string && intf)1227 std::string UserMgr::getServiceName(std::string&& path, std::string&& intf)
1228 {
1229     auto mapperCall = bus.new_method_call(objMapperService, objMapperPath,
1230                                           objMapperInterface, "GetObject");
1231 
1232     mapperCall.append(std::move(path));
1233     mapperCall.append(std::vector<std::string>({std::move(intf)}));
1234 
1235     std::map<std::string, std::vector<std::string>> mapperResponse;
1236     try
1237     {
1238         auto mapperResponseMsg = bus.call(mapperCall);
1239         mapperResponseMsg.read(mapperResponse);
1240     }
1241     catch (const sdbusplus::exception_t& e)
1242     {
1243         lg2::error("Error in mapper call: {ERROR}", "ERROR", e.what());
1244         elog<InternalFailure>();
1245     }
1246 
1247     if (mapperResponse.begin() == mapperResponse.end())
1248     {
1249         lg2::error("Invalid response from mapper");
1250         elog<InternalFailure>();
1251     }
1252 
1253     return mapperResponse.begin()->first;
1254 }
1255 
getPrimaryGroup(const std::string & userName) const1256 gid_t UserMgr::getPrimaryGroup(const std::string& userName) const
1257 {
1258     auto systemUser = getSystemUser(userName);
1259     if (systemUser)
1260     {
1261         return systemUser->pwd.pw_gid;
1262     }
1263 
1264     lg2::error("User {USERNAME} does not exist", "USERNAME", userName);
1265     elog<UserNameDoesNotExist>();
1266 }
1267 
isGroupMember(const std::string & userName,gid_t primaryGid,const std::string & groupName) const1268 bool UserMgr::isGroupMember(const std::string& userName, gid_t primaryGid,
1269                             const std::string& groupName) const
1270 {
1271     static auto buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
1272     if (buflen <= 0)
1273     {
1274         // Use a default size if there is no hard limit suggested by sysconf()
1275         buflen = 1024;
1276     }
1277 
1278     struct group grp;
1279     struct group* grpPtr = nullptr;
1280     std::vector<char> buffer(buflen);
1281 
1282     auto status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1283                              buffer.size(), &grpPtr);
1284 
1285     // Groups with a lot of members may require a buffer of bigger size than
1286     // suggested by _SC_GETGR_R_SIZE_MAX.
1287     // 32K should be enough for about 2K members.
1288     constexpr auto maxBufferLength = 32 * 1024;
1289     while (status == ERANGE && buflen < maxBufferLength)
1290     {
1291         buflen *= 2;
1292         buffer.resize(buflen);
1293 
1294         lg2::debug("Increase buffer for getgrnam_r() to {SIZE}", "SIZE",
1295                    buflen);
1296 
1297         status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1298                             buffer.size(), &grpPtr);
1299     }
1300 
1301     // On success, getgrnam_r() returns zero, and set *grpPtr to grp.
1302     // If no matching group record was found, these functions return 0
1303     // and store NULL in *grpPtr
1304     if (!status && (&grp == grpPtr))
1305     {
1306         if (primaryGid == grp.gr_gid)
1307         {
1308             return true;
1309         }
1310 
1311         for (auto i = 0; grp.gr_mem && grp.gr_mem[i]; ++i)
1312         {
1313             if (userName == grp.gr_mem[i])
1314             {
1315                 return true;
1316             }
1317         }
1318     }
1319     else if (status == ERANGE)
1320     {
1321         lg2::error("Group info of {GROUP} requires too much memory", "GROUP",
1322                    groupName);
1323     }
1324     else
1325     {
1326         lg2::error("Group {GROUP} does not exist", "GROUP", groupName);
1327     }
1328 
1329     return false;
1330 }
1331 
executeGroupCreation(const char * groupName)1332 void UserMgr::executeGroupCreation(const char* groupName)
1333 {
1334     executeCmd("/usr/sbin/groupadd", groupName);
1335 }
1336 
executeGroupDeletion(const char * groupName)1337 void UserMgr::executeGroupDeletion(const char* groupName)
1338 {
1339     executeCmd("/usr/sbin/groupdel", groupName);
1340 }
1341 
getUserInfo(std::string userName)1342 UserInfoMap UserMgr::getUserInfo(std::string userName)
1343 {
1344     UserInfoMap userInfo;
1345     // Check whether the given user is local user or not.
1346     if (isUserExist(userName))
1347     {
1348         const auto& user = usersList[userName];
1349         userInfo.emplace("UserPrivilege", user.get()->userPrivilege());
1350         userInfo.emplace("UserGroups", user.get()->userGroups());
1351         userInfo.emplace("UserEnabled", user.get()->userEnabled());
1352         userInfo.emplace("UserLockedForFailedAttempt",
1353                          user.get()->userLockedForFailedAttempt());
1354         userInfo.emplace("UserPasswordExpired",
1355                          user.get()->userPasswordExpired());
1356         userInfo.emplace("TOTPSecretkeyRequired",
1357                          user.get()->secretKeyGenerationRequired());
1358         userInfo.emplace("PasswordExpiration",
1359                          user.get()->passwordExpiration());
1360         userInfo.emplace("RemoteUser", false);
1361     }
1362     else
1363     {
1364         auto primaryGid = getPrimaryGroup(userName);
1365 
1366         DbusUserObj objects = getPrivilegeMapperObject();
1367 
1368         std::string ldapConfigPath;
1369         std::string userPrivilege;
1370 
1371         try
1372         {
1373             for (const auto& [path, interfaces] : objects)
1374             {
1375                 auto it = interfaces.find("xyz.openbmc_project.Object.Enable");
1376                 if (it != interfaces.end())
1377                 {
1378                     auto propIt = it->second.find("Enabled");
1379                     if (propIt != it->second.end() &&
1380                         std::get<bool>(propIt->second))
1381                     {
1382                         ldapConfigPath = path.str + '/';
1383                         break;
1384                     }
1385                 }
1386             }
1387 
1388             if (ldapConfigPath.empty())
1389             {
1390                 return userInfo;
1391             }
1392 
1393             for (const auto& [path, interfaces] : objects)
1394             {
1395                 if (!path.str.starts_with(ldapConfigPath))
1396                 {
1397                     continue;
1398                 }
1399 
1400                 auto it = interfaces.find(
1401                     "xyz.openbmc_project.User.PrivilegeMapperEntry");
1402                 if (it != interfaces.end())
1403                 {
1404                     std::string privilege;
1405                     std::string groupName;
1406 
1407                     for (const auto& [propName, propValue] : it->second)
1408                     {
1409                         if (propName == "GroupName")
1410                         {
1411                             groupName = std::get<std::string>(propValue);
1412                         }
1413                         else if (propName == "Privilege")
1414                         {
1415                             privilege = std::get<std::string>(propValue);
1416                         }
1417                     }
1418 
1419                     if (!groupName.empty() && !privilege.empty() &&
1420                         isGroupMember(userName, primaryGid, groupName))
1421                     {
1422                         userPrivilege = privilege;
1423                         break;
1424                     }
1425                 }
1426                 if (!userPrivilege.empty())
1427                 {
1428                     break;
1429                 }
1430             }
1431 
1432             if (userPrivilege.empty())
1433             {
1434                 lg2::warning("LDAP group privilege mapping does not exist");
1435             }
1436             userInfo.emplace("UserPrivilege", userPrivilege);
1437         }
1438         catch (const std::bad_variant_access& e)
1439         {
1440             lg2::error("Error while accessing variant: {ERR}", "ERR", e);
1441             elog<InternalFailure>();
1442         }
1443         userInfo.emplace("RemoteUser", true);
1444     }
1445 
1446     return userInfo;
1447 }
1448 
initializeAccountPolicy()1449 void UserMgr::initializeAccountPolicy()
1450 {
1451     std::string valueStr;
1452     auto value = minPasswdLength;
1453     unsigned long tmp = 0;
1454     if (getPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
1455                               valueStr) != success)
1456     {
1457         AccountPolicyIface::minPasswordLength(minPasswdLength);
1458     }
1459     else
1460     {
1461         try
1462         {
1463             tmp = std::stoul(valueStr, nullptr);
1464             if (tmp > std::numeric_limits<decltype(value)>::max())
1465             {
1466                 throw std::out_of_range("Out of range");
1467             }
1468             value = static_cast<decltype(value)>(tmp);
1469         }
1470         catch (const std::exception& e)
1471         {
1472             lg2::error("Exception for MinPasswordLength: {ERR}", "ERR", e);
1473             throw;
1474         }
1475         AccountPolicyIface::minPasswordLength(value);
1476     }
1477     valueStr.clear();
1478     if (getPamModuleConfValue(pwHistoryConfigFile, remOldPasswdCount,
1479                               valueStr) != success)
1480     {
1481         AccountPolicyIface::rememberOldPasswordTimes(0);
1482     }
1483     else
1484     {
1485         value = 0;
1486         try
1487         {
1488             tmp = std::stoul(valueStr, nullptr);
1489             if (tmp > std::numeric_limits<decltype(value)>::max())
1490             {
1491                 throw std::out_of_range("Out of range");
1492             }
1493             value = static_cast<decltype(value)>(tmp);
1494         }
1495         catch (const std::exception& e)
1496         {
1497             lg2::error("Exception for RememberOldPasswordTimes: {ERR}", "ERR",
1498                        e);
1499             throw;
1500         }
1501         AccountPolicyIface::rememberOldPasswordTimes(value);
1502     }
1503     valueStr.clear();
1504     if (getPamModuleConfValue(faillockConfigFile, maxFailedAttempt, valueStr) !=
1505         success)
1506     {
1507         AccountPolicyIface::maxLoginAttemptBeforeLockout(0);
1508     }
1509     else
1510     {
1511         uint16_t value16 = 0;
1512         try
1513         {
1514             tmp = std::stoul(valueStr, nullptr);
1515             if (tmp > std::numeric_limits<decltype(value16)>::max())
1516             {
1517                 throw std::out_of_range("Out of range");
1518             }
1519             value16 = static_cast<decltype(value16)>(tmp);
1520         }
1521         catch (const std::exception& e)
1522         {
1523             lg2::error("Exception for MaxLoginAttemptBeforLockout: {ERR}",
1524                        "ERR", e);
1525             throw;
1526         }
1527         AccountPolicyIface::maxLoginAttemptBeforeLockout(value16);
1528     }
1529     valueStr.clear();
1530     if (getPamModuleConfValue(faillockConfigFile, unlockTimeout, valueStr) !=
1531         success)
1532     {
1533         AccountPolicyIface::accountUnlockTimeout(0);
1534     }
1535     else
1536     {
1537         uint32_t value32 = 0;
1538         try
1539         {
1540             tmp = std::stoul(valueStr, nullptr);
1541             if (tmp > std::numeric_limits<decltype(value32)>::max())
1542             {
1543                 throw std::out_of_range("Out of range");
1544             }
1545             value32 = static_cast<decltype(value32)>(tmp);
1546         }
1547         catch (const std::exception& e)
1548         {
1549             lg2::error("Exception for AccountUnlockTimeout: {ERR}", "ERR", e);
1550             throw;
1551         }
1552         AccountPolicyIface::accountUnlockTimeout(value32);
1553     }
1554 }
1555 
initUserObjects(void)1556 void UserMgr::initUserObjects(void)
1557 {
1558     // All user management lock has to be based on /etc/shadow
1559     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1560     std::vector<std::string> userNameList;
1561     std::vector<std::string> sshGrpUsersList;
1562     UserSSHLists userSSHLists = getUserAndSshGrpList();
1563     userNameList = std::move(userSSHLists.first);
1564     sshGrpUsersList = std::move(userSSHLists.second);
1565 
1566     if (!userNameList.empty())
1567     {
1568         std::map<std::string, std::vector<std::string>> groupLists;
1569         // We only track users that are in the |predefinedGroups|
1570         // The other groups don't contain real BMC users.
1571         for (const char* grp : predefinedGroups)
1572         {
1573             if (grp == grpSsh)
1574             {
1575                 groupLists.emplace(grp, sshGrpUsersList);
1576             }
1577             else
1578             {
1579                 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1580                 groupLists.emplace(grp, grpUsersList);
1581             }
1582         }
1583         for (auto& grp : privMgr)
1584         {
1585             std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1586             groupLists.emplace(grp, grpUsersList);
1587         }
1588 
1589         for (auto& user : userNameList)
1590         {
1591             std::vector<std::string> userGroups;
1592             std::string userPriv;
1593             for (const auto& grp : groupLists)
1594             {
1595                 std::vector<std::string> tempGrp = grp.second;
1596                 if (std::find(tempGrp.begin(), tempGrp.end(), user) !=
1597                     tempGrp.end())
1598                 {
1599                     if (std::find(privMgr.begin(), privMgr.end(), grp.first) !=
1600                         privMgr.end())
1601                     {
1602                         userPriv = grp.first;
1603                     }
1604                     else
1605                     {
1606                         userGroups.emplace_back(grp.first);
1607                     }
1608                 }
1609             }
1610             // Add user objects to the Users path.
1611             sdbusplus::message::object_path tempObjPath(usersObjPath);
1612             tempObjPath /= user;
1613             std::string objPath(tempObjPath);
1614             std::sort(userGroups.begin(), userGroups.end());
1615 
1616             usersList.emplace(user, std::make_unique<phosphor::user::Users>(
1617                                         bus, objPath.c_str(), userGroups,
1618                                         userPriv, isUserEnabled(user),
1619                                         getPasswordExpiration(user), *this));
1620         }
1621     }
1622 }
1623 
load()1624 void UserMgr::load()
1625 {
1626     std::optional<std::string> authTypeStr;
1627     if (std::filesystem::exists(mfaConfPath) && serializer.load())
1628     {
1629         serializer.deserialize("authtype", authTypeStr);
1630     }
1631     auto authType =
1632         authTypeStr.transform(MultiFactorAuthConfiguration::convertStringToType)
1633             .value_or(std::optional(MultiFactorAuthType::None));
1634     if (authType)
1635     {
1636         enabled(*authType, true);
1637     }
1638 }
1639 
UserMgr(sdbusplus::bus_t & bus,const char * path)1640 UserMgr::UserMgr(sdbusplus::bus_t& bus, const char* path) :
1641     Ifaces(bus, path, Ifaces::action::defer_emit), bus(bus), path(path),
1642     serializer(mfaConfPath), faillockConfigFile(defaultFaillockConfigFile),
1643     pwHistoryConfigFile(defaultPWHistoryConfigFile),
1644     pwQualityConfigFile(defaultPWQualityConfigFile)
1645 
1646 {
1647     UserMgrIface::allPrivileges(privMgr);
1648     groupsMgr = readAllGroupsOnSystem();
1649     std::sort(groupsMgr.begin(), groupsMgr.end());
1650     UserMgrIface::allGroups(groupsMgr);
1651     initializeAccountPolicy();
1652     load();
1653     initUserObjects();
1654     // emit the signal
1655     this->emit_object_added();
1656 }
1657 
executeUserAdd(const char * userName,const char * groups,bool sshRequested,bool enabled)1658 void UserMgr::executeUserAdd(const char* userName, const char* groups,
1659                              bool sshRequested, bool enabled)
1660 {
1661     // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1662     // 1970-01-01, that's an implementation-defined behavior
1663     executeCmd("/usr/sbin/useradd", userName, "-G", groups, "-m", "-N", "-s",
1664                (sshRequested ? "/bin/sh" : "/sbin/nologin"), "-e",
1665                (enabled ? "" : "1970-01-01"));
1666 }
1667 
executeUserDelete(const char * userName)1668 void UserMgr::executeUserDelete(const char* userName)
1669 {
1670     executeCmd("/usr/sbin/userdel", userName, "-r", "-f");
1671 }
1672 
executeUserClearFailRecords(const char * userName)1673 void UserMgr::executeUserClearFailRecords(const char* userName)
1674 {
1675     executeCmd("/usr/sbin/faillock", "--user", userName, "--reset");
1676 }
1677 
executeUserRename(const char * userName,const char * newUserName)1678 void UserMgr::executeUserRename(const char* userName, const char* newUserName)
1679 {
1680     std::string newHomeDir = "/home/";
1681     newHomeDir += newUserName;
1682     executeCmd("/usr/sbin/usermod", "-l", newUserName, userName, "-d",
1683                newHomeDir.c_str(), "-m");
1684 }
1685 
executeUserModify(const char * userName,const char * newGroups,bool sshRequested)1686 void UserMgr::executeUserModify(const char* userName, const char* newGroups,
1687                                 bool sshRequested)
1688 {
1689     executeCmd("/usr/sbin/usermod", userName, "-G", newGroups, "-s",
1690                (sshRequested ? "/bin/sh" : "/sbin/nologin"));
1691 }
1692 
executeUserModifyUserEnable(const char * userName,bool enabled)1693 void UserMgr::executeUserModifyUserEnable(const char* userName, bool enabled)
1694 {
1695     // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1696     // 1970-01-01, that's an implementation-defined behavior
1697     executeCmd("/usr/sbin/usermod", userName, "-e",
1698                (enabled ? "" : "1970-01-01"));
1699 }
1700 
getFailedAttempt(const char * userName)1701 std::vector<std::string> UserMgr::getFailedAttempt(const char* userName)
1702 {
1703     return executeCmd("/usr/sbin/faillock", "--user", userName);
1704 }
1705 
enabled(MultiFactorAuthType value,bool skipSignal)1706 MultiFactorAuthType UserMgr::enabled(MultiFactorAuthType value, bool skipSignal)
1707 {
1708     if (value == enabled())
1709     {
1710         return value;
1711     }
1712     switch (value)
1713     {
1714         case MultiFactorAuthType::None:
1715             for (auto type : {MultiFactorAuthType::GoogleAuthenticator})
1716             {
1717                 for (auto& u : usersList)
1718                 {
1719                     u.second->enableMultiFactorAuth(type, false);
1720                 }
1721             }
1722             break;
1723         default:
1724             for (auto& u : usersList)
1725             {
1726                 u.second->enableMultiFactorAuth(value, true);
1727             }
1728             break;
1729     }
1730     serializer.serialize(
1731         "authtype", MultiFactorAuthConfiguration::convertTypeToString(value));
1732     serializer.store();
1733     return MultiFactorAuthConfigurationIface::enabled(value, skipSignal);
1734 }
1735 
secretKeyRequired(std::string userName)1736 bool UserMgr::secretKeyRequired(std::string userName)
1737 {
1738     if (usersList.contains(userName))
1739     {
1740         return usersList[userName]->secretKeyGenerationRequired();
1741     }
1742     return false;
1743 }
1744 
executeUserPasswordExpiration(const char * userName,const long int passwordLastChange,const long int passwordAge) const1745 void UserMgr::executeUserPasswordExpiration(const char* userName,
1746                                             const long int passwordLastChange,
1747                                             const long int passwordAge) const
1748 {
1749     executeCmd("/usr/bin/chage", userName, "--lastday",
1750                std::to_string(passwordLastChange).c_str(), "--maxdays",
1751                std::to_string(passwordAge).c_str());
1752 }
1753 
getShadowData(const std::string & userName,struct spwd & spwd) const1754 void UserMgr::getShadowData(const std::string& userName,
1755                             struct spwd& spwd) const
1756 {
1757     struct spwd* p = nullptr;
1758 
1759     auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1760     if (buflen <= 0)
1761         buflen = 1024;
1762 
1763     std::vector<char> buffer(buflen);
1764     auto status =
1765         getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen, &p);
1766     if (status)
1767     {
1768         lg2::warning("Failed to get shadow entry for the user {USER_NAME}",
1769                      "USER_NAME", userName.c_str());
1770         elog<InternalFailure>();
1771     }
1772 
1773     spwd.sp_namp = nullptr;
1774     spwd.sp_pwdp = nullptr;
1775 }
1776 
getPasswordExpiration(const std::string & userName) const1777 uint64_t UserMgr::getPasswordExpiration(const std::string& userName) const
1778 {
1779     // All user management lock has to be based on /etc/shadow
1780     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1781     struct spwd spwd{};
1782     getShadowData(userName, spwd);
1783 
1784     // use default value for maximum password age to check that password
1785     // expiration was not specified
1786     // TODO: this default value might be changed, so it should be obtain
1787     // properly instead of hardcoding
1788     if (spwd.sp_max == 99999)
1789     {
1790         return getDefaultPasswordExpiration();
1791     }
1792 
1793     // process last change date and maximum password age according to
1794     // list_fields() in
1795     // https://github.com/shadow-maint/shadow/blob/7a796897e52293efe9e210ab8da32b7aefe65591/src/chage.c#L266
1796 
1797     // if last change is negative, then password does not exprire
1798     // if last change is positive and maximum password age is negative, then
1799     // password does not expire
1800     if (spwd.sp_lstchg < 0 || (spwd.sp_lstchg > 0 && spwd.sp_max < 0))
1801     {
1802         return getUnexpiringPasswordTime();
1803     }
1804 
1805     // if last change is 0, then password must be changed
1806     // https://linux.die.net/man/5/shadow assume its now
1807     if (spwd.sp_lstchg == 0)
1808     {
1809         using namespace std::chrono;
1810         return duration_cast<seconds>(system_clock::now().time_since_epoch())
1811             .count();
1812     }
1813 
1814     return daysToSeconds(static_cast<uint64_t>(spwd.sp_lstchg) + spwd.sp_max);
1815 }
1816 
setPasswordExpiration(const std::string & userName,const uint64_t value)1817 void UserMgr::setPasswordExpiration(const std::string& userName,
1818                                     const uint64_t value)
1819 {
1820     setPasswordExpirationImpl(userName, value);
1821 
1822     lg2::info("User's '{USER_NAME}' password expiration updated successfully",
1823               "USER_NAME", userName.c_str());
1824 }
1825 
setPasswordExpirationImpl(const std::string & userName,const uint64_t value)1826 void UserMgr::setPasswordExpirationImpl(const std::string& userName,
1827                                         const uint64_t value)
1828 {
1829     // All user management lock has to be based on /etc/shadow
1830     // TODO  phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1831     const bool resetPasswordExpiration = (value == getUnexpiringPasswordTime());
1832 
1833     struct spwd spwd{};
1834     getShadowData(userName, spwd);
1835 
1836     // process last change date according to list_fields() in
1837     // https://github.com/shadow-maint/shadow/blob/7a796897e52293efe9e210ab8da32b7aefe65591/src/chage.c#L266
1838 
1839     long int lastChangeDate = spwd.sp_lstchg;
1840     if (lastChangeDate <= 0 && !resetPasswordExpiration)
1841     {
1842         // if last change is 0, then password must be changed
1843         // https://linux.die.net/man/5/shadow make last change value valid,
1844         // update it to today
1845         // if last change is negative, then password does not expire, update it
1846         // to today as well
1847         using namespace std::chrono;
1848         lastChangeDate =
1849             duration_cast<days>(system_clock::now().time_since_epoch()).count();
1850     }
1851 
1852     long int passwordAgeDays = spwd.sp_max;
1853     if (resetPasswordExpiration)
1854     {
1855         // if password expiration must be reset, do it via last negative maximum
1856         // password age
1857         passwordAgeDays = getUnexpiringPasswordAge();
1858     }
1859     else
1860     {
1861         const uint64_t date = secondsToDays(value);
1862         const long int expirationDate =
1863             (date > std::numeric_limits<long int>::max())
1864                 ? std::numeric_limits<long int>::max()
1865                 : date;
1866 
1867         // if password expiration date is less than last change date, then this
1868         // leads to the situation when password age is negative, which in turn
1869         // is treated by system as password does not expire, hence treat such a
1870         // value of password expiration as invalid
1871         if (expirationDate < lastChangeDate)
1872         {
1873             lg2::error(
1874                 "Password expiration date specified is less than password last change date for user '{USER_NAME}'",
1875                 "USER_NAME", userName.c_str());
1876             elog<InvalidArgument>(
1877                 Argument::ARGUMENT_NAME("User's password expiration date"),
1878                 Argument::ARGUMENT_VALUE("less then last change date"));
1879         }
1880 
1881         // set password expiration via maximum password age
1882         passwordAgeDays = expirationDate - lastChangeDate;
1883     }
1884 
1885     try
1886     {
1887         executeUserPasswordExpiration(userName.c_str(), lastChangeDate,
1888                                       passwordAgeDays);
1889     }
1890     catch (const std::exception& e)
1891     {
1892         lg2::error("Unable to update user's '{USER_NAME}' password expiration",
1893                    "USER_NAME", userName.c_str());
1894         elog<InternalFailure>();
1895     }
1896 }
1897 
createUser2(std::string userName,UserCreateMap createProps)1898 void UserMgr::createUser2(std::string userName, UserCreateMap createProps)
1899 {
1900     createUserImpl(userName, createProps);
1901 
1902     auto passwordExpiration = getDefaultPasswordExpiration();
1903     if (createProps.contains(UserProperty::PasswordExpiration))
1904         passwordExpiration =
1905             std::get<uint64_t>(createProps[UserProperty::PasswordExpiration]);
1906 
1907     // maximum value (default value of password expiration) means not to set
1908     // password expiration
1909     if (passwordExpiration != getDefaultPasswordExpiration())
1910     {
1911         try
1912         {
1913             setPasswordExpirationImpl(userName, passwordExpiration);
1914         }
1915         catch (const sdbusplus::exception::generated_exception& e2)
1916         {
1917             // delete user created by createUserImpl
1918             deleteUserImpl(userName);
1919             throw;
1920         }
1921         catch (const std::exception& e2)
1922         {
1923             // delete user created by createUserImpl
1924             deleteUserImpl(userName);
1925             lg2::error(
1926                 "User's password expiration value is incorrect for user '{USER_NAME}'",
1927                 "USER_NAME", userName.c_str());
1928 
1929             elog<InvalidArgument>(
1930                 Argument::ARGUMENT_NAME("Password Expiration"),
1931                 Argument::ARGUMENT_VALUE(
1932                     std::to_string(passwordExpiration).c_str()));
1933         }
1934     }
1935 
1936     lg2::info("User '{USERNAME}' created successfully", "USERNAME", userName);
1937 }
1938 
1939 } // namespace user
1940 } // namespace phosphor
1941