blob: edb25f3699164bf4825a83a8b5802c8673a2eaaa [file] [log] [blame]
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301/*
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
Patrick Williams9638afb2021-02-22 17:16:24 -060017#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>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053027#include <shadow.h>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053028#include <sys/types.h>
29#include <sys/wait.h>
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -060030#include <time.h>
Patrick Williams9638afb2021-02-22 17:16:24 -060031#include <unistd.h>
32
33#include <boost/algorithm/string/split.hpp>
Patrick Williams9638afb2021-02-22 17:16:24 -060034#include <phosphor-logging/elog-errors.hpp>
35#include <phosphor-logging/elog.hpp>
Jiaqing Zhao11ec6662022-07-05 20:55:34 +080036#include <phosphor-logging/lg2.hpp>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053037#include <xyz/openbmc_project/Common/error.hpp>
38#include <xyz/openbmc_project/User/Common/error.hpp>
Patrick Williams9638afb2021-02-22 17:16:24 -060039
40#include <algorithm>
Nan Zhouda401fe2022-10-25 00:07:18 +000041#include <array>
Jiaqing Zhaofba4bb12022-06-24 01:30:57 +080042#include <ctime>
Patrick Williams9638afb2021-02-22 17:16:24 -060043#include <fstream>
44#include <numeric>
45#include <regex>
Nan Zhoue47c09d2022-10-25 00:06:41 +000046#include <span>
47#include <string>
48#include <string_view>
49#include <vector>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053050
51namespace phosphor
52{
53namespace user
54{
55
Patrick Williams9638afb2021-02-22 17:16:24 -060056static constexpr const char* passwdFileName = "/etc/passwd";
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053057static constexpr size_t ipmiMaxUserNameLen = 16;
58static constexpr size_t systemMaxUserNameLen = 30;
Patrick Williams9638afb2021-02-22 17:16:24 -060059static constexpr const char* grpSsh = "ssh";
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +053060static constexpr int success = 0;
61static constexpr int failure = -1;
62
63// pam modules related
Patrick Williams9638afb2021-02-22 17:16:24 -060064static constexpr const char* pamPWHistory = "pam_pwhistory.so";
65static constexpr const char* minPasswdLenProp = "minlen";
66static constexpr const char* remOldPasswdCount = "remember";
67static constexpr const char* maxFailedAttempt = "deny";
68static constexpr const char* unlockTimeout = "unlock_time";
Nan Zhoue48085d2022-10-25 00:07:04 +000069static constexpr const char* defaultPamPasswdConfigFile =
70 "/etc/pam.d/common-password";
Jason M. Bills2d042d12023-03-28 15:32:45 -070071static constexpr const char* defaultFaillockConfigFile =
72 "/etc/security/faillock.conf";
73static constexpr const char* defaultPWQualityConfigFile =
74 "/etc/security/pwquality.conf";
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053075
Ratan Guptaaeaf9412019-02-11 04:41:52 -060076// Object Manager related
Patrick Williams9638afb2021-02-22 17:16:24 -060077static constexpr const char* ldapMgrObjBasePath =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060078 "/xyz/openbmc_project/user/ldap";
79
80// Object Mapper related
Patrick Williams9638afb2021-02-22 17:16:24 -060081static constexpr const char* objMapperService =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060082 "xyz.openbmc_project.ObjectMapper";
Patrick Williams9638afb2021-02-22 17:16:24 -060083static constexpr const char* objMapperPath =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060084 "/xyz/openbmc_project/object_mapper";
Patrick Williams9638afb2021-02-22 17:16:24 -060085static constexpr const char* objMapperInterface =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060086 "xyz.openbmc_project.ObjectMapper";
87
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053088using namespace phosphor::logging;
89using InsufficientPermission =
90 sdbusplus::xyz::openbmc_project::Common::Error::InsufficientPermission;
91using InternalFailure =
92 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
93using InvalidArgument =
94 sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
95using UserNameExists =
96 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameExists;
97using UserNameDoesNotExist =
98 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameDoesNotExist;
99using UserNameGroupFail =
100 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameGroupFail;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530101using NoResource =
102 sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530103using Argument = xyz::openbmc_project::Common::InvalidArgument;
Nan Zhouda401fe2022-10-25 00:07:18 +0000104using GroupNameExists =
105 sdbusplus::xyz::openbmc_project::User::Common::Error::GroupNameExists;
106using GroupNameDoesNotExists =
107 sdbusplus::xyz::openbmc_project::User::Common::Error::GroupNameDoesNotExist;
108
109namespace
110{
111
112// The hardcoded groups in OpenBMC projects
Ninad Palsule601d3db2023-03-09 10:27:37 -0600113constexpr std::array<const char*, 5> predefinedGroups = {
114 "web", "redfish", "ipmi", "ssh", "hostconsole"};
Nan Zhouda401fe2022-10-25 00:07:18 +0000115
116// These prefixes are for Dynamic Redfish authorization. See
117// https://github.com/openbmc/docs/blob/master/designs/redfish-authorization.md
118
119// Base role and base privileges are added by Redfish implementation (e.g.,
120// BMCWeb) at compile time
121constexpr std::array<const char*, 4> allowedGroupPrefix = {
122 "openbmc_rfr_", // OpenBMC Redfish Base Role
123 "openbmc_rfp_", // OpenBMC Redfish Base Privileges
124 "openbmc_orfr_", // OpenBMC Redfish OEM Role
125 "openbmc_orfp_", // OpenBMC Redfish OEM Privileges
126};
127
128void checkAndThrowsForGroupChangeAllowed(const std::string& groupName)
129{
130 bool allowed = false;
131 for (std::string_view prefix : allowedGroupPrefix)
132 {
133 if (groupName.starts_with(prefix))
134 {
135 allowed = true;
136 break;
137 }
138 }
139 if (!allowed)
140 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800141 lg2::error("Group name '{GROUP}' is not in the allowed list", "GROUP",
142 groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000143 elog<InvalidArgument>(Argument::ARGUMENT_NAME("Group Name"),
144 Argument::ARGUMENT_VALUE(groupName.c_str()));
145 }
146}
147
148} // namespace
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530149
Nan Zhoue47c09d2022-10-25 00:06:41 +0000150std::string getCSVFromVector(std::span<const std::string> vec)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530151{
Nan Zhoue47c09d2022-10-25 00:06:41 +0000152 if (vec.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530153 {
Nan Zhoue47c09d2022-10-25 00:06:41 +0000154 return "";
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530155 }
Nan Zhoue47c09d2022-10-25 00:06:41 +0000156 return std::accumulate(std::next(vec.begin()), vec.end(), vec[0],
157 [](std::string&& val, std::string_view element) {
Patrick Williamsb7043042023-05-10 07:50:52 -0500158 val += ',';
159 val += element;
160 return val;
161 });
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530162}
163
Nan Zhou332fb9d2022-10-25 00:07:03 +0000164bool removeStringFromCSV(std::string& csvStr, const std::string& delStr)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530165{
166 std::string::size_type delStrPos = csvStr.find(delStr);
167 if (delStrPos != std::string::npos)
168 {
169 // need to also delete the comma char
170 if (delStrPos == 0)
171 {
172 csvStr.erase(delStrPos, delStr.size() + 1);
173 }
174 else
175 {
176 csvStr.erase(delStrPos - 1, delStr.size() + 1);
177 }
178 return true;
179 }
180 return false;
181}
182
Patrick Williams9638afb2021-02-22 17:16:24 -0600183bool UserMgr::isUserExist(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530184{
185 if (userName.empty())
186 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800187 lg2::error("User name is empty");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530188 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
189 Argument::ARGUMENT_VALUE("Null"));
190 }
191 if (usersList.find(userName) == usersList.end())
192 {
193 return false;
194 }
195 return true;
196}
197
Patrick Williams9638afb2021-02-22 17:16:24 -0600198void UserMgr::throwForUserDoesNotExist(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530199{
Nan Zhou8a11d992022-10-25 00:07:06 +0000200 if (!isUserExist(userName))
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530201 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800202 lg2::error("User '{USERNAME}' does not exist", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530203 elog<UserNameDoesNotExist>();
204 }
205}
206
Nan Zhouda401fe2022-10-25 00:07:18 +0000207void UserMgr::checkAndThrowForDisallowedGroupCreation(
208 const std::string& groupName)
209{
210 if (groupName.size() > maxSystemGroupNameLength ||
211 !std::regex_match(groupName.c_str(),
212 std::regex("[a-zA-z_][a-zA-Z_0-9]*")))
213 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800214 lg2::error("Invalid group name '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000215 elog<InvalidArgument>(Argument::ARGUMENT_NAME("Group Name"),
216 Argument::ARGUMENT_VALUE(groupName.c_str()));
217 }
218 checkAndThrowsForGroupChangeAllowed(groupName);
219}
220
Patrick Williams9638afb2021-02-22 17:16:24 -0600221void UserMgr::throwForUserExists(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530222{
Nan Zhou8a11d992022-10-25 00:07:06 +0000223 if (isUserExist(userName))
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530224 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800225 lg2::error("User '{USERNAME}' already exists", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530226 elog<UserNameExists>();
227 }
228}
229
230void UserMgr::throwForUserNameConstraints(
Patrick Williams9638afb2021-02-22 17:16:24 -0600231 const std::string& userName, const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530232{
233 if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
234 groupNames.end())
235 {
236 if (userName.length() > ipmiMaxUserNameLen)
237 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800238 lg2::error("User '{USERNAME}' exceeds IPMI username length limit "
239 "({LENGTH} > {LIMIT})",
240 "USERNAME", userName, "LENGTH", userName.length(),
241 "LIMIT", ipmiMaxUserNameLen);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530242 elog<UserNameGroupFail>(
243 xyz::openbmc_project::User::Common::UserNameGroupFail::REASON(
244 "IPMI length"));
245 }
246 }
247 if (userName.length() > systemMaxUserNameLen)
248 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800249 lg2::error("User '{USERNAME}' exceeds system username length limit "
250 "({LENGTH} > {LIMIT})",
251 "USERNAME", userName, "LENGTH", userName.length(), "LIMIT",
252 systemMaxUserNameLen);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530253 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
254 Argument::ARGUMENT_VALUE("Invalid length"));
255 }
256 if (!std::regex_match(userName.c_str(),
257 std::regex("[a-zA-z_][a-zA-Z_0-9]*")))
258 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800259 lg2::error("Invalid username '{USERNAME}'", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530260 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
261 Argument::ARGUMENT_VALUE("Invalid data"));
262 }
263}
264
265void UserMgr::throwForMaxGrpUserCount(
Patrick Williams9638afb2021-02-22 17:16:24 -0600266 const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530267{
268 if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
269 groupNames.end())
270 {
271 if (getIpmiUsersCount() >= ipmiMaxUsers)
272 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800273 lg2::error("IPMI user limit reached");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530274 elog<NoResource>(
275 xyz::openbmc_project::User::Common::NoResource::REASON(
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800276 "IPMI user limit reached"));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530277 }
278 }
279 else
280 {
281 if (usersList.size() > 0 && (usersList.size() - getIpmiUsersCount()) >=
282 (maxSystemUsers - ipmiMaxUsers))
283 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800284 lg2::error("Non-ipmi User limit reached");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530285 elog<NoResource>(
286 xyz::openbmc_project::User::Common::NoResource::REASON(
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800287 "Non-ipmi user limit reached"));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530288 }
289 }
290 return;
291}
292
Patrick Williams9638afb2021-02-22 17:16:24 -0600293void UserMgr::throwForInvalidPrivilege(const std::string& priv)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530294{
295 if (!priv.empty() &&
296 (std::find(privMgr.begin(), privMgr.end(), priv) == privMgr.end()))
297 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800298 lg2::error("Invalid privilege '{PRIVILEGE}'", "PRIVILEGE", priv);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530299 elog<InvalidArgument>(Argument::ARGUMENT_NAME("Privilege"),
300 Argument::ARGUMENT_VALUE(priv.c_str()));
301 }
302}
303
Patrick Williams9638afb2021-02-22 17:16:24 -0600304void UserMgr::throwForInvalidGroups(const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530305{
Patrick Williams9638afb2021-02-22 17:16:24 -0600306 for (auto& group : groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530307 {
308 if (std::find(groupsMgr.begin(), groupsMgr.end(), group) ==
309 groupsMgr.end())
310 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800311 lg2::error("Invalid Group Name '{GROUPNAME}'", "GROUPNAME", group);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530312 elog<InvalidArgument>(Argument::ARGUMENT_NAME("GroupName"),
313 Argument::ARGUMENT_VALUE(group.c_str()));
314 }
315 }
316}
317
Nan Zhouda401fe2022-10-25 00:07:18 +0000318std::vector<std::string> UserMgr::readAllGroupsOnSystem()
319{
320 std::vector<std::string> allGroups = {predefinedGroups.begin(),
321 predefinedGroups.end()};
322 // rewinds to the beginning of the group database
323 setgrent();
324 struct group* gr = getgrent();
325 while (gr != nullptr)
326 {
327 std::string group(gr->gr_name);
328 for (std::string_view prefix : allowedGroupPrefix)
329 {
330 if (group.starts_with(prefix))
331 {
332 allGroups.push_back(gr->gr_name);
333 }
334 }
335 gr = getgrent();
336 }
337 // close the group database
338 endgrent();
339 return allGroups;
340}
341
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530342void UserMgr::createUser(std::string userName,
343 std::vector<std::string> groupNames, std::string priv,
344 bool enabled)
345{
346 throwForInvalidPrivilege(priv);
347 throwForInvalidGroups(groupNames);
348 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500349 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530350 throwForUserExists(userName);
351 throwForUserNameConstraints(userName, groupNames);
352 throwForMaxGrpUserCount(groupNames);
353
354 std::string groups = getCSVFromVector(groupNames);
355 bool sshRequested = removeStringFromCSV(groups, grpSsh);
356
357 // treat privilege as a group - This is to avoid using different file to
358 // store the same.
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530359 if (!priv.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530360 {
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530361 if (groups.size() != 0)
362 {
363 groups += ",";
364 }
365 groups += priv;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530366 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530367 try
368 {
Nan Zhou49c81362022-10-25 00:07:08 +0000369 executeUserAdd(userName.c_str(), groups.c_str(), sshRequested, enabled);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530370 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600371 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530372 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800373 lg2::error("Unable to create new user '{USERNAME}'", "USERNAME",
374 userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530375 elog<InternalFailure>();
376 }
377
378 // Add the users object before sending out the signal
P Dheeraj Srujan Kumarb01e2fe2021-12-13 09:43:28 +0530379 sdbusplus::message::object_path tempObjPath(usersObjPath);
380 tempObjPath /= userName;
381 std::string userObj(tempObjPath);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530382 std::sort(groupNames.begin(), groupNames.end());
383 usersList.emplace(
Nan Zhou78d85042022-08-29 17:50:22 +0000384 userName, std::make_unique<phosphor::user::Users>(
385 bus, userObj.c_str(), groupNames, priv, enabled, *this));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530386
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800387 lg2::info("User '{USERNAME}' created successfully", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530388 return;
389}
390
391void UserMgr::deleteUser(std::string userName)
392{
393 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500394 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530395 throwForUserDoesNotExist(userName);
396 try
397 {
Nan Zhou49c81362022-10-25 00:07:08 +0000398 executeUserDelete(userName.c_str());
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530399 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600400 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530401 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800402 lg2::error("Delete User '{USERNAME}' failed", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530403 elog<InternalFailure>();
404 }
405
406 usersList.erase(userName);
407
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800408 lg2::info("User '{USERNAME}' deleted successfully", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530409 return;
410}
411
Nan Zhouda401fe2022-10-25 00:07:18 +0000412void UserMgr::checkDeleteGroupConstraints(const std::string& groupName)
413{
414 if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) ==
415 groupsMgr.end())
416 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800417 lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000418 elog<GroupNameDoesNotExists>();
419 }
420 checkAndThrowsForGroupChangeAllowed(groupName);
421}
422
423void UserMgr::deleteGroup(std::string groupName)
424{
425 checkDeleteGroupConstraints(groupName);
426 try
427 {
428 executeGroupDeletion(groupName.c_str());
429 }
430 catch (const InternalFailure& e)
431 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800432 lg2::error("Failed to delete group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000433 elog<InternalFailure>();
434 }
435
436 groupsMgr.erase(std::find(groupsMgr.begin(), groupsMgr.end(), groupName));
437 UserMgrIface::allGroups(groupsMgr);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800438 lg2::info("Successfully deleted group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000439}
440
441void UserMgr::checkCreateGroupConstraints(const std::string& groupName)
442{
443 if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) !=
444 groupsMgr.end())
445 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800446 lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000447 elog<GroupNameExists>();
448 }
449 checkAndThrowForDisallowedGroupCreation(groupName);
450 if (groupsMgr.size() >= maxSystemGroupCount)
451 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800452 lg2::error("Group limit reached");
Nan Zhouda401fe2022-10-25 00:07:18 +0000453 elog<NoResource>(xyz::openbmc_project::User::Common::NoResource::REASON(
454 "Group limit reached"));
455 }
456}
457
458void UserMgr::createGroup(std::string groupName)
459{
460 checkCreateGroupConstraints(groupName);
461 try
462 {
463 executeGroupCreation(groupName.c_str());
464 }
465 catch (const InternalFailure& e)
466 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800467 lg2::error("Failed to create group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000468 elog<InternalFailure>();
469 }
470 groupsMgr.push_back(groupName);
471 UserMgrIface::allGroups(groupsMgr);
472}
473
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530474void UserMgr::renameUser(std::string userName, std::string newUserName)
475{
476 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500477 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530478 throwForUserDoesNotExist(userName);
479 throwForUserExists(newUserName);
480 throwForUserNameConstraints(newUserName,
481 usersList[userName].get()->userGroups());
482 try
483 {
Nan Zhouf25443e2022-10-25 00:07:11 +0000484 executeUserRename(userName.c_str(), newUserName.c_str());
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530485 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600486 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530487 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800488 lg2::error("Rename '{USERNAME}' to '{NEWUSERNAME}' failed", "USERNAME",
489 userName, "NEWUSERNAME", newUserName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530490 elog<InternalFailure>();
491 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600492 const auto& user = usersList[userName];
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530493 std::string priv = user.get()->userPrivilege();
494 std::vector<std::string> groupNames = user.get()->userGroups();
495 bool enabled = user.get()->userEnabled();
P Dheeraj Srujan Kumarb01e2fe2021-12-13 09:43:28 +0530496 sdbusplus::message::object_path tempObjPath(usersObjPath);
497 tempObjPath /= newUserName;
498 std::string newUserObj(tempObjPath);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530499 // Special group 'ipmi' needs a way to identify user renamed, in order to
500 // update encrypted password. It can't rely only on InterfacesRemoved &
501 // InterfacesAdded. So first send out userRenamed signal.
502 this->userRenamed(userName, newUserName);
503 usersList.erase(userName);
Nan Zhou78d85042022-08-29 17:50:22 +0000504 usersList.emplace(newUserName, std::make_unique<phosphor::user::Users>(
505 bus, newUserObj.c_str(), groupNames,
506 priv, enabled, *this));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530507 return;
508}
509
Patrick Williams9638afb2021-02-22 17:16:24 -0600510void UserMgr::updateGroupsAndPriv(const std::string& userName,
Nan Zhoufef63032022-10-25 00:07:12 +0000511 std::vector<std::string> groupNames,
Patrick Williams9638afb2021-02-22 17:16:24 -0600512 const std::string& priv)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530513{
514 throwForInvalidPrivilege(priv);
515 throwForInvalidGroups(groupNames);
516 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500517 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530518 throwForUserDoesNotExist(userName);
Patrick Williams9638afb2021-02-22 17:16:24 -0600519 const std::vector<std::string>& oldGroupNames =
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530520 usersList[userName].get()->userGroups();
521 std::vector<std::string> groupDiff;
522 // Note: already dealing with sorted group lists.
523 std::set_symmetric_difference(oldGroupNames.begin(), oldGroupNames.end(),
524 groupNames.begin(), groupNames.end(),
525 std::back_inserter(groupDiff));
526 if (std::find(groupDiff.begin(), groupDiff.end(), "ipmi") !=
527 groupDiff.end())
528 {
529 throwForUserNameConstraints(userName, groupNames);
530 throwForMaxGrpUserCount(groupNames);
531 }
532
533 std::string groups = getCSVFromVector(groupNames);
534 bool sshRequested = removeStringFromCSV(groups, grpSsh);
535
536 // treat privilege as a group - This is to avoid using different file to
537 // store the same.
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530538 if (!priv.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530539 {
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530540 if (groups.size() != 0)
541 {
542 groups += ",";
543 }
544 groups += priv;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530545 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530546 try
547 {
Nan Zhoufef63032022-10-25 00:07:12 +0000548 executeUserModify(userName.c_str(), groups.c_str(), sshRequested);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530549 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600550 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530551 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800552 lg2::error(
553 "Unable to modify user privilege / groups for user '{USERNAME}'",
554 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530555 elog<InternalFailure>();
556 }
557
Nan Zhoufef63032022-10-25 00:07:12 +0000558 std::sort(groupNames.begin(), groupNames.end());
559 usersList[userName]->setUserGroups(groupNames);
560 usersList[userName]->setUserPrivilege(priv);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800561 lg2::info("User '{USERNAME}' groups / privilege updated successfully",
562 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530563}
564
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530565uint8_t UserMgr::minPasswordLength(uint8_t value)
566{
567 if (value == AccountPolicyIface::minPasswordLength())
568 {
569 return value;
570 }
571 if (value < minPasswdLength)
572 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800573 lg2::error("Attempting to set minPasswordLength to {VALUE}, less than "
574 "{MINVALUE}",
575 "VALUE", value, "MINVALUE", minPasswdLength);
Paul Fertser6dc7ed92022-01-21 19:36:34 +0000576 elog<InvalidArgument>(
577 Argument::ARGUMENT_NAME("minPasswordLength"),
578 Argument::ARGUMENT_VALUE(std::to_string(value).c_str()));
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530579 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700580 if (setPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
581 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530582 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800583 lg2::error("Unable to set minPasswordLength to {VALUE}", "VALUE",
584 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530585 elog<InternalFailure>();
586 }
587 return AccountPolicyIface::minPasswordLength(value);
588}
589
590uint8_t UserMgr::rememberOldPasswordTimes(uint8_t value)
591{
592 if (value == AccountPolicyIface::rememberOldPasswordTimes())
593 {
594 return value;
595 }
596 if (setPamModuleArgValue(pamPWHistory, remOldPasswdCount,
597 std::to_string(value)) != success)
598 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800599 lg2::error("Unable to set rememberOldPasswordTimes to {VALUE}", "VALUE",
600 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530601 elog<InternalFailure>();
602 }
603 return AccountPolicyIface::rememberOldPasswordTimes(value);
604}
605
606uint16_t UserMgr::maxLoginAttemptBeforeLockout(uint16_t value)
607{
608 if (value == AccountPolicyIface::maxLoginAttemptBeforeLockout())
609 {
610 return value;
611 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700612 if (setPamModuleConfValue(faillockConfigFile, maxFailedAttempt,
613 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530614 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800615 lg2::error("Unable to set maxLoginAttemptBeforeLockout to {VALUE}",
616 "VALUE", value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530617 elog<InternalFailure>();
618 }
619 return AccountPolicyIface::maxLoginAttemptBeforeLockout(value);
620}
621
622uint32_t UserMgr::accountUnlockTimeout(uint32_t value)
623{
624 if (value == AccountPolicyIface::accountUnlockTimeout())
625 {
626 return value;
627 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700628 if (setPamModuleConfValue(faillockConfigFile, unlockTimeout,
629 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530630 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800631 lg2::error("Unable to set accountUnlockTimeout to {VALUE}", "VALUE",
632 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530633 elog<InternalFailure>();
634 }
635 return AccountPolicyIface::accountUnlockTimeout(value);
636}
637
Patrick Williams9638afb2021-02-22 17:16:24 -0600638int UserMgr::getPamModuleArgValue(const std::string& moduleName,
639 const std::string& argName,
640 std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530641{
Jason M. Bills2d042d12023-03-28 15:32:45 -0700642 std::string fileName = pamPasswdConfigFile;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530643 std::ifstream fileToRead(fileName, std::ios::in);
644 if (!fileToRead.is_open())
645 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800646 lg2::error("Failed to open pam configuration file {FILENAME}",
647 "FILENAME", fileName);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530648 return failure;
649 }
650 std::string line;
651 auto argSearch = argName + "=";
652 size_t startPos = 0;
653 size_t endPos = 0;
654 while (getline(fileToRead, line))
655 {
656 // skip comments section starting with #
657 if ((startPos = line.find('#')) != std::string::npos)
658 {
659 if (startPos == 0)
660 {
661 continue;
662 }
663 // skip comments after meaningful section and process those
664 line = line.substr(0, startPos);
665 }
666 if (line.find(moduleName) != std::string::npos)
667 {
668 if ((startPos = line.find(argSearch)) != std::string::npos)
669 {
670 if ((endPos = line.find(' ', startPos)) == std::string::npos)
671 {
672 endPos = line.size();
673 }
674 startPos += argSearch.size();
675 argValue = line.substr(startPos, endPos - startPos);
676 return success;
677 }
678 }
679 }
680 return failure;
681}
682
Jason M. Bills2d042d12023-03-28 15:32:45 -0700683int UserMgr::getPamModuleConfValue(const std::string& confFile,
684 const std::string& argName,
685 std::string& argValue)
686{
687 std::ifstream fileToRead(confFile, std::ios::in);
688 if (!fileToRead.is_open())
689 {
690 lg2::error("Failed to open pam configuration file {FILENAME}",
691 "FILENAME", confFile);
692 return failure;
693 }
694 std::string line;
695 auto argSearch = argName + "=";
696 size_t startPos = 0;
697 size_t endPos = 0;
698 while (getline(fileToRead, line))
699 {
700 // skip comments section starting with #
701 if ((startPos = line.find('#')) != std::string::npos)
702 {
703 if (startPos == 0)
704 {
705 continue;
706 }
707 // skip comments after meaningful section and process those
708 line = line.substr(0, startPos);
709 }
710 if ((startPos = line.find(argSearch)) != std::string::npos)
711 {
712 if ((endPos = line.find(' ', startPos)) == std::string::npos)
713 {
714 endPos = line.size();
715 }
716 startPos += argSearch.size();
717 argValue = line.substr(startPos, endPos - startPos);
718 return success;
719 }
720 }
721 return failure;
722}
723
Patrick Williams9638afb2021-02-22 17:16:24 -0600724int UserMgr::setPamModuleArgValue(const std::string& moduleName,
725 const std::string& argName,
726 const std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530727{
Jason M. Bills2d042d12023-03-28 15:32:45 -0700728 std::string fileName = pamPasswdConfigFile;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530729 std::string tmpFileName = fileName + "_tmp";
730 std::ifstream fileToRead(fileName, std::ios::in);
731 std::ofstream fileToWrite(tmpFileName, std::ios::out);
732 if (!fileToRead.is_open() || !fileToWrite.is_open())
733 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800734 lg2::error("Failed to open pam configuration file {FILENAME}",
735 "FILENAME", fileName);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530736 return failure;
737 }
738 std::string line;
739 auto argSearch = argName + "=";
740 size_t startPos = 0;
741 size_t endPos = 0;
742 bool found = false;
743 while (getline(fileToRead, line))
744 {
745 // skip comments section starting with #
746 if ((startPos = line.find('#')) != std::string::npos)
747 {
748 if (startPos == 0)
749 {
750 fileToWrite << line << std::endl;
751 continue;
752 }
753 // skip comments after meaningful section and process those
754 line = line.substr(0, startPos);
755 }
756 if (line.find(moduleName) != std::string::npos)
757 {
758 if ((startPos = line.find(argSearch)) != std::string::npos)
759 {
760 if ((endPos = line.find(' ', startPos)) == std::string::npos)
761 {
762 endPos = line.size();
763 }
764 startPos += argSearch.size();
765 fileToWrite << line.substr(0, startPos) << argValue
766 << line.substr(endPos, line.size() - endPos)
767 << std::endl;
768 found = true;
769 continue;
770 }
771 }
772 fileToWrite << line << std::endl;
773 }
774 fileToWrite.close();
775 fileToRead.close();
776 if (found)
777 {
778 if (std::rename(tmpFileName.c_str(), fileName.c_str()) == 0)
779 {
780 return success;
781 }
782 }
783 return failure;
784}
785
Jason M. Bills2d042d12023-03-28 15:32:45 -0700786int UserMgr::setPamModuleConfValue(const std::string& confFile,
787 const std::string& argName,
788 const std::string& argValue)
789{
790 std::string tmpConfFile = confFile + "_tmp";
791 std::ifstream fileToRead(confFile, std::ios::in);
792 std::ofstream fileToWrite(tmpConfFile, std::ios::out);
793 if (!fileToRead.is_open() || !fileToWrite.is_open())
794 {
795 lg2::error("Failed to open pam configuration file {FILENAME}",
796 "FILENAME", confFile);
797 return failure;
798 }
799 std::string line;
800 auto argSearch = argName + "=";
801 size_t startPos = 0;
802 size_t endPos = 0;
803 bool found = false;
804 while (getline(fileToRead, line))
805 {
806 // skip comments section starting with #
807 if ((startPos = line.find('#')) != std::string::npos)
808 {
809 if (startPos == 0)
810 {
811 fileToWrite << line << std::endl;
812 continue;
813 }
814 // skip comments after meaningful section and process those
815 line = line.substr(0, startPos);
816 }
817 if ((startPos = line.find(argSearch)) != std::string::npos)
818 {
819 if ((endPos = line.find(' ', startPos)) == std::string::npos)
820 {
821 endPos = line.size();
822 }
823 startPos += argSearch.size();
824 fileToWrite << line.substr(0, startPos) << argValue
825 << line.substr(endPos, line.size() - endPos)
826 << std::endl;
827 found = true;
828 continue;
829 }
830 fileToWrite << line << std::endl;
831 }
832 fileToWrite.close();
833 fileToRead.close();
834 if (found)
835 {
836 if (std::rename(tmpConfFile.c_str(), confFile.c_str()) == 0)
837 {
838 return success;
839 }
840 }
841 return failure;
842}
843
Patrick Williams9638afb2021-02-22 17:16:24 -0600844void UserMgr::userEnable(const std::string& userName, bool enabled)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530845{
846 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500847 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530848 throwForUserDoesNotExist(userName);
849 try
850 {
Nan Zhou6b6f2d82022-10-25 00:07:17 +0000851 executeUserModifyUserEnable(userName.c_str(), enabled);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530852 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600853 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530854 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800855 lg2::error("Unable to modify user enabled state for '{USERNAME}'",
856 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530857 elog<InternalFailure>();
858 }
859
Nan Zhou6b6f2d82022-10-25 00:07:17 +0000860 usersList[userName]->setUserEnabled(enabled);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800861 lg2::info("User '{USERNAME}' has been {STATUS}", "USERNAME", userName,
862 "STATUS", enabled ? "Enabled" : "Disabled");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530863}
864
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530865/**
Jason M. Bills2d042d12023-03-28 15:32:45 -0700866 * faillock app will provide the user failed login list with when the attempt
867 * was made, the type, the source, and if it's valid.
868 *
869 * Valid in this case means that the attempt was made within the fail_interval
870 * time. So, we can check this list for the number of valid entries (lines
871 * ending with 'V') compared to the maximum allowed to determine if the user is
872 * locked out.
873 *
874 * This data is only refreshed when an attempt is made, so if the user appears
875 * to be locked out, we must also check if the most recent attempt was older
876 * than the unlock_time to know if the user has since been unlocked.
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530877 **/
Jason M. Bills2d042d12023-03-28 15:32:45 -0700878bool UserMgr::parseFaillockForLockout(
879 const std::vector<std::string>& faillockOutput)
880{
881 uint16_t failAttempts = 0;
882 time_t lastFailedAttempt{};
883 for (const std::string& line : faillockOutput)
884 {
885 if (!line.ends_with("V"))
886 {
887 continue;
888 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530889
Jason M. Bills2d042d12023-03-28 15:32:45 -0700890 // Count this failed attempt
891 failAttempts++;
892
893 // Update the last attempt time
894 // First get the "when" which is the first two words (date and time)
895 size_t pos = line.find(" ");
896 if (pos == std::string::npos)
897 {
898 continue;
899 }
900 pos = line.find(" ", pos + 1);
901 if (pos == std::string::npos)
902 {
903 continue;
904 }
905 std::string failDateTime = line.substr(0, pos);
906
907 // NOTE: Cannot use std::get_time() here as the implementation of %y in
908 // libstdc++ does not match POSIX strptime() before gcc 12.1.0
909 // https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=a8d3c98746098e2784be7144c1ccc9fcc34a0888
910 std::tm tmStruct = {};
911 if (!strptime(failDateTime.c_str(), "%F %T", &tmStruct))
912 {
913 lg2::error("Failed to parse latest failure date/time");
914 elog<InternalFailure>();
915 }
916
917 time_t failTimestamp = std::mktime(&tmStruct);
918 lastFailedAttempt = std::max(failTimestamp, lastFailedAttempt);
919 }
920
921 if (failAttempts < AccountPolicyIface::maxLoginAttemptBeforeLockout())
922 {
923 return false;
924 }
925
926 if (lastFailedAttempt +
927 static_cast<time_t>(AccountPolicyIface::accountUnlockTimeout()) <=
928 std::time(NULL))
929 {
930 return false;
931 }
932
933 return true;
934}
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530935
Patrick Williams9638afb2021-02-22 17:16:24 -0600936bool UserMgr::userLockedForFailedAttempt(const std::string& userName)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530937{
938 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500939 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Jiaqing Zhaofba4bb12022-06-24 01:30:57 +0800940 if (AccountPolicyIface::maxLoginAttemptBeforeLockout() == 0)
941 {
942 return false;
943 }
944
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530945 std::vector<std::string> output;
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800946 try
947 {
Nan Zhoua2953032022-11-11 21:50:32 +0000948 output = getFailedAttempt(userName.c_str());
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800949 }
950 catch (const InternalFailure& e)
951 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800952 lg2::error("Unable to read login failure counter");
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800953 elog<InternalFailure>();
954 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530955
Jason M. Bills2d042d12023-03-28 15:32:45 -0700956 return parseFaillockForLockout(output);
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530957}
958
Patrick Williams9638afb2021-02-22 17:16:24 -0600959bool UserMgr::userLockedForFailedAttempt(const std::string& userName,
960 const bool& value)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530961{
962 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500963 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530964 if (value == true)
965 {
966 return userLockedForFailedAttempt(userName);
967 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530968
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800969 try
970 {
Jason M. Bills2d042d12023-03-28 15:32:45 -0700971 executeCmd("/usr/sbin/faillock", "--user", userName.c_str(), "--reset");
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800972 }
973 catch (const InternalFailure& e)
974 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800975 lg2::error("Unable to reset login failure counter");
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800976 elog<InternalFailure>();
977 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530978
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530979 return userLockedForFailedAttempt(userName);
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530980}
981
Patrick Williams9638afb2021-02-22 17:16:24 -0600982bool UserMgr::userPasswordExpired(const std::string& userName)
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600983{
984 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500985 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600986
987 struct spwd spwd
Patrick Williams9638afb2021-02-22 17:16:24 -0600988 {};
989 struct spwd* spwdPtr = nullptr;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600990 auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
991 if (buflen < -1)
992 {
993 // Use a default size if there is no hard limit suggested by sysconf()
994 buflen = 1024;
995 }
996 std::vector<char> buffer(buflen);
Patrick Williamsb7043042023-05-10 07:50:52 -0500997 auto status = getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen,
998 &spwdPtr);
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600999 // On success, getspnam_r() returns zero, and sets *spwdPtr to spwd.
1000 // If no matching password record was found, these functions return 0
1001 // and store NULL in *spwdPtr
1002 if ((status == 0) && (&spwd == spwdPtr))
1003 {
1004 // Determine password validity per "chage" docs, where:
1005 // spwd.sp_lstchg == 0 means password is expired, and
1006 // spwd.sp_max == -1 means the password does not expire.
Nan Zhou78d85042022-08-29 17:50:22 +00001007 constexpr long secondsPerDay = 60 * 60 * 24;
1008 long today = static_cast<long>(time(NULL)) / secondsPerDay;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001009 if ((spwd.sp_lstchg == 0) ||
1010 ((spwd.sp_max != -1) && ((spwd.sp_max + spwd.sp_lstchg) < today)))
1011 {
1012 return true;
1013 }
1014 }
1015 else
1016 {
Jayaprakash Mutyala75be4e62020-09-18 15:59:06 +00001017 // User entry is missing in /etc/shadow, indicating no SHA password.
1018 // Treat this as new user without password entry in /etc/shadow
1019 // TODO: Add property to indicate user password was not set yet
1020 // https://github.com/openbmc/phosphor-user-manager/issues/8
1021 return false;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001022 }
1023
1024 return false;
1025}
1026
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301027UserSSHLists UserMgr::getUserAndSshGrpList()
1028{
1029 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -05001030 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301031
1032 std::vector<std::string> userList;
1033 std::vector<std::string> sshUsersList;
1034 struct passwd pw, *pwp = nullptr;
1035 std::array<char, 1024> buffer{};
1036
1037 phosphor::user::File passwd(passwdFileName, "r");
1038 if ((passwd)() == NULL)
1039 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001040 lg2::error("Error opening {FILENAME}", "FILENAME", passwdFileName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301041 elog<InternalFailure>();
1042 }
1043
1044 while (true)
1045 {
1046 auto r = fgetpwent_r((passwd)(), &pw, buffer.data(), buffer.max_size(),
1047 &pwp);
1048 if ((r != 0) || (pwp == NULL))
1049 {
1050 // Any error, break the loop.
1051 break;
1052 }
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +05301053#ifdef ENABLE_ROOT_USER_MGMT
Richard Marian Thomaiyar7ba3c712018-07-31 13:41:36 +05301054 // Add all users whose UID >= 1000 and < 65534
1055 // and special UID 0.
1056 if ((pwp->pw_uid == 0) ||
1057 ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534)))
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +05301058#else
1059 // Add all users whose UID >=1000 and < 65534
1060 if ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534))
1061#endif
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301062 {
1063 std::string userName(pwp->pw_name);
1064 userList.emplace_back(userName);
1065
1066 // ssh doesn't have separate group. Check login shell entry to
1067 // get all users list which are member of ssh group.
1068 std::string loginShell(pwp->pw_shell);
1069 if (loginShell == "/bin/sh")
1070 {
1071 sshUsersList.emplace_back(userName);
1072 }
1073 }
1074 }
1075 endpwent();
1076 return std::make_pair(std::move(userList), std::move(sshUsersList));
1077}
1078
1079size_t UserMgr::getIpmiUsersCount()
1080{
1081 std::vector<std::string> userList = getUsersInGroup("ipmi");
1082 return userList.size();
1083}
1084
Nan Zhou49c81362022-10-25 00:07:08 +00001085size_t UserMgr::getNonIpmiUsersCount()
1086{
1087 std::vector<std::string> ipmiUsers = getUsersInGroup("ipmi");
1088 return usersList.size() - ipmiUsers.size();
1089}
1090
Patrick Williams9638afb2021-02-22 17:16:24 -06001091bool UserMgr::isUserEnabled(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301092{
1093 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -05001094 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301095 std::array<char, 4096> buffer{};
1096 struct spwd spwd;
Patrick Williams9638afb2021-02-22 17:16:24 -06001097 struct spwd* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301098 int status = getspnam_r(userName.c_str(), &spwd, buffer.data(),
1099 buffer.max_size(), &resultPtr);
1100 if (!status && (&spwd == resultPtr))
1101 {
1102 if (resultPtr->sp_expire >= 0)
1103 {
1104 return false; // user locked out
1105 }
1106 return true;
1107 }
1108 return false; // assume user is disabled for any error.
1109}
1110
Patrick Williams9638afb2021-02-22 17:16:24 -06001111std::vector<std::string> UserMgr::getUsersInGroup(const std::string& groupName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301112{
1113 std::vector<std::string> usersInGroup;
1114 // Should be more than enough to get the pwd structure.
1115 std::array<char, 4096> buffer{};
1116 struct group grp;
Patrick Williams9638afb2021-02-22 17:16:24 -06001117 struct group* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301118
1119 int status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1120 buffer.max_size(), &resultPtr);
1121
1122 if (!status && (&grp == resultPtr))
1123 {
1124 for (; *(grp.gr_mem) != NULL; ++(grp.gr_mem))
1125 {
1126 usersInGroup.emplace_back(*(grp.gr_mem));
1127 }
1128 }
1129 else
1130 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001131 lg2::error("Group '{GROUPNAME}' not found", "GROUPNAME", groupName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301132 // Don't throw error, just return empty userList - fallback
1133 }
1134 return usersInGroup;
1135}
1136
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001137DbusUserObj UserMgr::getPrivilegeMapperObject(void)
1138{
1139 DbusUserObj objects;
1140 try
1141 {
Ravi Teja5fe724a2019-05-07 05:14:42 -05001142 std::string basePath = "/xyz/openbmc_project/user/ldap/openldap";
1143 std::string interface = "xyz.openbmc_project.User.Ldap.Config";
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001144
Patrick Williamsb7043042023-05-10 07:50:52 -05001145 auto ldapMgmtService = getServiceName(std::move(basePath),
1146 std::move(interface));
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001147 auto method = bus.new_method_call(
1148 ldapMgmtService.c_str(), ldapMgrObjBasePath,
1149 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1150
1151 auto reply = bus.call(method);
1152 reply.read(objects);
1153 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001154 catch (const InternalFailure& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001155 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001156 lg2::error("Unable to get the User Service: {ERR}", "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001157 throw;
1158 }
Patrick Williamsb3ef4e12022-07-22 19:26:55 -05001159 catch (const sdbusplus::exception_t& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001160 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001161 lg2::error("Failed to excute GetManagedObjects at {PATH}: {ERR}",
1162 "PATH", ldapMgrObjBasePath, "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001163 throw;
1164 }
1165 return objects;
1166}
1167
Patrick Williams9638afb2021-02-22 17:16:24 -06001168std::string UserMgr::getServiceName(std::string&& path, std::string&& intf)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001169{
1170 auto mapperCall = bus.new_method_call(objMapperService, objMapperPath,
1171 objMapperInterface, "GetObject");
1172
1173 mapperCall.append(std::move(path));
1174 mapperCall.append(std::vector<std::string>({std::move(intf)}));
1175
1176 auto mapperResponseMsg = bus.call(mapperCall);
1177
1178 if (mapperResponseMsg.is_method_error())
1179 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001180 lg2::error("Error in mapper call");
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001181 elog<InternalFailure>();
1182 }
1183
1184 std::map<std::string, std::vector<std::string>> mapperResponse;
1185 mapperResponseMsg.read(mapperResponse);
1186
1187 if (mapperResponse.begin() == mapperResponse.end())
1188 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001189 lg2::error("Invalid response from mapper");
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001190 elog<InternalFailure>();
1191 }
1192
1193 return mapperResponse.begin()->first;
1194}
1195
Alexander Filippov75626582022-02-09 18:42:37 +03001196gid_t UserMgr::getPrimaryGroup(const std::string& userName) const
1197{
1198 static auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1199 if (buflen <= 0)
1200 {
1201 // Use a default size if there is no hard limit suggested by sysconf()
1202 buflen = 1024;
1203 }
1204
1205 struct passwd pwd;
1206 struct passwd* pwdPtr = nullptr;
1207 std::vector<char> buffer(buflen);
1208
1209 auto status = getpwnam_r(userName.c_str(), &pwd, buffer.data(),
1210 buffer.size(), &pwdPtr);
1211 // On success, getpwnam_r() returns zero, and set *pwdPtr to pwd.
1212 // If no matching password record was found, these functions return 0
1213 // and store NULL in *pwdPtr
1214 if (!status && (&pwd == pwdPtr))
1215 {
1216 return pwd.pw_gid;
1217 }
1218
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001219 lg2::error("User {USERNAME} does not exist", "USERNAME", userName);
Alexander Filippov75626582022-02-09 18:42:37 +03001220 elog<UserNameDoesNotExist>();
1221}
1222
1223bool UserMgr::isGroupMember(const std::string& userName, gid_t primaryGid,
1224 const std::string& groupName) const
1225{
1226 static auto buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
1227 if (buflen <= 0)
1228 {
1229 // Use a default size if there is no hard limit suggested by sysconf()
1230 buflen = 1024;
1231 }
1232
1233 struct group grp;
1234 struct group* grpPtr = nullptr;
1235 std::vector<char> buffer(buflen);
1236
1237 auto status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1238 buffer.size(), &grpPtr);
1239
1240 // Groups with a lot of members may require a buffer of bigger size than
1241 // suggested by _SC_GETGR_R_SIZE_MAX.
1242 // 32K should be enough for about 2K members.
1243 constexpr auto maxBufferLength = 32 * 1024;
1244 while (status == ERANGE && buflen < maxBufferLength)
1245 {
1246 buflen *= 2;
1247 buffer.resize(buflen);
1248
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001249 lg2::debug("Increase buffer for getgrnam_r() to {SIZE}", "SIZE",
1250 buflen);
Alexander Filippov75626582022-02-09 18:42:37 +03001251
1252 status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1253 buffer.size(), &grpPtr);
1254 }
1255
1256 // On success, getgrnam_r() returns zero, and set *grpPtr to grp.
1257 // If no matching group record was found, these functions return 0
1258 // and store NULL in *grpPtr
1259 if (!status && (&grp == grpPtr))
1260 {
1261 if (primaryGid == grp.gr_gid)
1262 {
1263 return true;
1264 }
1265
1266 for (auto i = 0; grp.gr_mem && grp.gr_mem[i]; ++i)
1267 {
1268 if (userName == grp.gr_mem[i])
1269 {
1270 return true;
1271 }
1272 }
1273 }
1274 else if (status == ERANGE)
1275 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001276 lg2::error("Group info of {GROUP} requires too much memory", "GROUP",
1277 groupName);
Alexander Filippov75626582022-02-09 18:42:37 +03001278 }
1279 else
1280 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001281 lg2::error("Group {GROUP} does not exist", "GROUP", groupName);
Alexander Filippov75626582022-02-09 18:42:37 +03001282 }
1283
1284 return false;
1285}
1286
Nan Zhouda401fe2022-10-25 00:07:18 +00001287void UserMgr::executeGroupCreation(const char* groupName)
1288{
1289 executeCmd("/usr/sbin/groupadd", groupName);
1290}
1291
1292void UserMgr::executeGroupDeletion(const char* groupName)
1293{
1294 executeCmd("/usr/sbin/groupdel", groupName);
1295}
1296
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001297UserInfoMap UserMgr::getUserInfo(std::string userName)
1298{
1299 UserInfoMap userInfo;
1300 // Check whether the given user is local user or not.
Nan Zhou8a11d992022-10-25 00:07:06 +00001301 if (isUserExist(userName))
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001302 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001303 const auto& user = usersList[userName];
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001304 userInfo.emplace("UserPrivilege", user.get()->userPrivilege());
1305 userInfo.emplace("UserGroups", user.get()->userGroups());
1306 userInfo.emplace("UserEnabled", user.get()->userEnabled());
1307 userInfo.emplace("UserLockedForFailedAttempt",
1308 user.get()->userLockedForFailedAttempt());
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001309 userInfo.emplace("UserPasswordExpired",
1310 user.get()->userPasswordExpired());
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001311 userInfo.emplace("RemoteUser", false);
1312 }
1313 else
1314 {
Alexander Filippov75626582022-02-09 18:42:37 +03001315 auto primaryGid = getPrimaryGroup(userName);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001316
1317 DbusUserObj objects = getPrivilegeMapperObject();
1318
Ravi Teja5fe724a2019-05-07 05:14:42 -05001319 std::string ldapConfigPath;
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001320 std::string userPrivilege;
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001321
1322 try
1323 {
Alexander Filippov75626582022-02-09 18:42:37 +03001324 for (const auto& [path, interfaces] : objects)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001325 {
Alexander Filippov75626582022-02-09 18:42:37 +03001326 auto it = interfaces.find("xyz.openbmc_project.Object.Enable");
1327 if (it != interfaces.end())
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001328 {
Alexander Filippov75626582022-02-09 18:42:37 +03001329 auto propIt = it->second.find("Enabled");
1330 if (propIt != it->second.end() &&
1331 std::get<bool>(propIt->second))
Ravi Teja5fe724a2019-05-07 05:14:42 -05001332 {
Alexander Filippov75626582022-02-09 18:42:37 +03001333 ldapConfigPath = path.str + '/';
1334 break;
Ravi Teja5fe724a2019-05-07 05:14:42 -05001335 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001336 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001337 }
1338
1339 if (ldapConfigPath.empty())
1340 {
1341 return userInfo;
1342 }
1343
Alexander Filippov75626582022-02-09 18:42:37 +03001344 for (const auto& [path, interfaces] : objects)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001345 {
Alexander Filippov75626582022-02-09 18:42:37 +03001346 if (!path.str.starts_with(ldapConfigPath))
Ravi Teja5fe724a2019-05-07 05:14:42 -05001347 {
Alexander Filippov75626582022-02-09 18:42:37 +03001348 continue;
1349 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001350
Alexander Filippov75626582022-02-09 18:42:37 +03001351 auto it = interfaces.find(
1352 "xyz.openbmc_project.User.PrivilegeMapperEntry");
1353 if (it != interfaces.end())
1354 {
1355 std::string privilege;
1356 std::string groupName;
1357
1358 for (const auto& [propName, propValue] : it->second)
1359 {
1360 if (propName == "GroupName")
Ravi Teja5fe724a2019-05-07 05:14:42 -05001361 {
Alexander Filippov75626582022-02-09 18:42:37 +03001362 groupName = std::get<std::string>(propValue);
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001363 }
Alexander Filippov75626582022-02-09 18:42:37 +03001364 else if (propName == "Privilege")
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001365 {
Alexander Filippov75626582022-02-09 18:42:37 +03001366 privilege = std::get<std::string>(propValue);
Ravi Teja5fe724a2019-05-07 05:14:42 -05001367 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001368 }
Alexander Filippov75626582022-02-09 18:42:37 +03001369
1370 if (!groupName.empty() && !privilege.empty() &&
1371 isGroupMember(userName, primaryGid, groupName))
1372 {
1373 userPrivilege = privilege;
1374 break;
1375 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001376 }
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001377 if (!userPrivilege.empty())
1378 {
1379 break;
1380 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001381 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001382
Jiaqing Zhao56862062022-05-31 19:16:09 +08001383 if (!userPrivilege.empty())
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001384 {
Jiaqing Zhao56862062022-05-31 19:16:09 +08001385 userInfo.emplace("UserPrivilege", userPrivilege);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001386 }
Jiaqing Zhao56862062022-05-31 19:16:09 +08001387 else
1388 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001389 lg2::warning("LDAP group privilege mapping does not exist, "
1390 "default \"priv-user\" is used");
Jiaqing Zhao56862062022-05-31 19:16:09 +08001391 userInfo.emplace("UserPrivilege", "priv-user");
1392 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001393 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001394 catch (const std::bad_variant_access& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001395 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001396 lg2::error("Error while accessing variant: {ERR}", "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001397 elog<InternalFailure>();
1398 }
1399 userInfo.emplace("RemoteUser", true);
1400 }
1401
1402 return userInfo;
1403}
1404
Nan Zhou4bc69812022-10-25 00:07:13 +00001405void UserMgr::initializeAccountPolicy()
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301406{
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301407 std::string valueStr;
1408 auto value = minPasswdLength;
1409 unsigned long tmp = 0;
Jason M. Bills2d042d12023-03-28 15:32:45 -07001410 if (getPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
1411 valueStr) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301412 {
1413 AccountPolicyIface::minPasswordLength(minPasswdLength);
1414 }
1415 else
1416 {
1417 try
1418 {
1419 tmp = std::stoul(valueStr, nullptr);
1420 if (tmp > std::numeric_limits<decltype(value)>::max())
1421 {
1422 throw std::out_of_range("Out of range");
1423 }
1424 value = static_cast<decltype(value)>(tmp);
1425 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001426 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301427 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001428 lg2::error("Exception for MinPasswordLength: {ERR}", "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001429 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301430 }
1431 AccountPolicyIface::minPasswordLength(value);
1432 }
1433 valueStr.clear();
1434 if (getPamModuleArgValue(pamPWHistory, remOldPasswdCount, valueStr) !=
1435 success)
1436 {
1437 AccountPolicyIface::rememberOldPasswordTimes(0);
1438 }
1439 else
1440 {
1441 value = 0;
1442 try
1443 {
1444 tmp = std::stoul(valueStr, nullptr);
1445 if (tmp > std::numeric_limits<decltype(value)>::max())
1446 {
1447 throw std::out_of_range("Out of range");
1448 }
1449 value = static_cast<decltype(value)>(tmp);
1450 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001451 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301452 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001453 lg2::error("Exception for RememberOldPasswordTimes: {ERR}", "ERR",
1454 e);
Patrick Venture045b1122018-10-16 15:59:29 -07001455 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301456 }
1457 AccountPolicyIface::rememberOldPasswordTimes(value);
1458 }
1459 valueStr.clear();
Jason M. Bills2d042d12023-03-28 15:32:45 -07001460 if (getPamModuleConfValue(faillockConfigFile, maxFailedAttempt, valueStr) !=
1461 success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301462 {
1463 AccountPolicyIface::maxLoginAttemptBeforeLockout(0);
1464 }
1465 else
1466 {
1467 uint16_t value16 = 0;
1468 try
1469 {
1470 tmp = std::stoul(valueStr, nullptr);
1471 if (tmp > std::numeric_limits<decltype(value16)>::max())
1472 {
1473 throw std::out_of_range("Out of range");
1474 }
1475 value16 = static_cast<decltype(value16)>(tmp);
1476 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001477 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301478 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001479 lg2::error("Exception for MaxLoginAttemptBeforLockout: {ERR}",
1480 "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001481 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301482 }
1483 AccountPolicyIface::maxLoginAttemptBeforeLockout(value16);
1484 }
1485 valueStr.clear();
Jason M. Bills2d042d12023-03-28 15:32:45 -07001486 if (getPamModuleConfValue(faillockConfigFile, unlockTimeout, valueStr) !=
1487 success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301488 {
1489 AccountPolicyIface::accountUnlockTimeout(0);
1490 }
1491 else
1492 {
1493 uint32_t value32 = 0;
1494 try
1495 {
1496 tmp = std::stoul(valueStr, nullptr);
1497 if (tmp > std::numeric_limits<decltype(value32)>::max())
1498 {
1499 throw std::out_of_range("Out of range");
1500 }
1501 value32 = static_cast<decltype(value32)>(tmp);
1502 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001503 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301504 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001505 lg2::error("Exception for AccountUnlockTimeout: {ERR}", "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001506 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301507 }
1508 AccountPolicyIface::accountUnlockTimeout(value32);
1509 }
Nan Zhou4bc69812022-10-25 00:07:13 +00001510}
1511
1512void UserMgr::initUserObjects(void)
1513{
1514 // All user management lock has to be based on /etc/shadow
1515 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1516 std::vector<std::string> userNameList;
1517 std::vector<std::string> sshGrpUsersList;
1518 UserSSHLists userSSHLists = getUserAndSshGrpList();
1519 userNameList = std::move(userSSHLists.first);
1520 sshGrpUsersList = std::move(userSSHLists.second);
1521
1522 if (!userNameList.empty())
1523 {
1524 std::map<std::string, std::vector<std::string>> groupLists;
Nan Zhouda401fe2022-10-25 00:07:18 +00001525 // We only track users that are in the |predefinedGroups|
1526 // The other groups don't contain real BMC users.
1527 for (const char* grp : predefinedGroups)
Nan Zhou4bc69812022-10-25 00:07:13 +00001528 {
1529 if (grp == grpSsh)
1530 {
1531 groupLists.emplace(grp, sshGrpUsersList);
1532 }
1533 else
1534 {
1535 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1536 groupLists.emplace(grp, grpUsersList);
1537 }
1538 }
1539 for (auto& grp : privMgr)
1540 {
1541 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1542 groupLists.emplace(grp, grpUsersList);
1543 }
1544
1545 for (auto& user : userNameList)
1546 {
1547 std::vector<std::string> userGroups;
1548 std::string userPriv;
1549 for (const auto& grp : groupLists)
1550 {
1551 std::vector<std::string> tempGrp = grp.second;
1552 if (std::find(tempGrp.begin(), tempGrp.end(), user) !=
1553 tempGrp.end())
1554 {
1555 if (std::find(privMgr.begin(), privMgr.end(), grp.first) !=
1556 privMgr.end())
1557 {
1558 userPriv = grp.first;
1559 }
1560 else
1561 {
1562 userGroups.emplace_back(grp.first);
1563 }
1564 }
1565 }
1566 // Add user objects to the Users path.
1567 sdbusplus::message::object_path tempObjPath(usersObjPath);
1568 tempObjPath /= user;
1569 std::string objPath(tempObjPath);
1570 std::sort(userGroups.begin(), userGroups.end());
1571 usersList.emplace(user, std::make_unique<phosphor::user::Users>(
1572 bus, objPath.c_str(), userGroups,
1573 userPriv, isUserEnabled(user), *this));
1574 }
1575 }
1576}
1577
1578UserMgr::UserMgr(sdbusplus::bus_t& bus, const char* path) :
1579 Ifaces(bus, path, Ifaces::action::defer_emit), bus(bus), path(path),
1580 pamPasswdConfigFile(defaultPamPasswdConfigFile),
Jason M. Bills2d042d12023-03-28 15:32:45 -07001581 faillockConfigFile(defaultFaillockConfigFile),
1582 pwQualityConfigFile(defaultPWQualityConfigFile)
Nan Zhou4bc69812022-10-25 00:07:13 +00001583{
1584 UserMgrIface::allPrivileges(privMgr);
Nan Zhouda401fe2022-10-25 00:07:18 +00001585 groupsMgr = readAllGroupsOnSystem();
Nan Zhou4bc69812022-10-25 00:07:13 +00001586 std::sort(groupsMgr.begin(), groupsMgr.end());
1587 UserMgrIface::allGroups(groupsMgr);
1588 initializeAccountPolicy();
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301589 initUserObjects();
Ratan Gupta1af12232018-11-03 00:35:38 +05301590
1591 // emit the signal
1592 this->emit_object_added();
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301593}
1594
Nan Zhou49c81362022-10-25 00:07:08 +00001595void UserMgr::executeUserAdd(const char* userName, const char* groups,
1596 bool sshRequested, bool enabled)
1597{
1598 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1599 // 1970-01-01, that's an implementation-defined behavior
1600 executeCmd("/usr/sbin/useradd", userName, "-G", groups, "-m", "-N", "-s",
Tang Yiwei75ea3e42022-04-25 10:48:15 +08001601 (sshRequested ? "/bin/sh" : "/sbin/nologin"), "-e",
Nan Zhou49c81362022-10-25 00:07:08 +00001602 (enabled ? "" : "1970-01-01"));
1603}
1604
1605void UserMgr::executeUserDelete(const char* userName)
1606{
1607 executeCmd("/usr/sbin/userdel", userName, "-r");
1608}
1609
Nan Zhouf25443e2022-10-25 00:07:11 +00001610void UserMgr::executeUserRename(const char* userName, const char* newUserName)
1611{
1612 std::string newHomeDir = "/home/";
1613 newHomeDir += newUserName;
1614 executeCmd("/usr/sbin/usermod", "-l", newUserName, userName, "-d",
1615 newHomeDir.c_str(), "-m");
1616}
1617
Nan Zhoufef63032022-10-25 00:07:12 +00001618void UserMgr::executeUserModify(const char* userName, const char* newGroups,
1619 bool sshRequested)
1620{
1621 executeCmd("/usr/sbin/usermod", userName, "-G", newGroups, "-s",
Tang Yiwei75ea3e42022-04-25 10:48:15 +08001622 (sshRequested ? "/bin/sh" : "/sbin/nologin"));
Nan Zhoufef63032022-10-25 00:07:12 +00001623}
1624
Nan Zhou6b6f2d82022-10-25 00:07:17 +00001625void UserMgr::executeUserModifyUserEnable(const char* userName, bool enabled)
1626{
1627 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1628 // 1970-01-01, that's an implementation-defined behavior
1629 executeCmd("/usr/sbin/usermod", userName, "-e",
1630 (enabled ? "" : "1970-01-01"));
1631}
1632
Nan Zhoua2953032022-11-11 21:50:32 +00001633std::vector<std::string> UserMgr::getFailedAttempt(const char* userName)
1634{
Jason M. Bills2d042d12023-03-28 15:32:45 -07001635 return executeCmd("/usr/sbin/faillock", "--user", userName);
Nan Zhoua2953032022-11-11 21:50:32 +00001636}
1637
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301638} // namespace user
1639} // namespace phosphor