blob: 6d58fa810977eb3d81735937a844569c116ab039 [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());
Jayanth Othayothac921a52023-07-21 03:48:55 -0500399
400 // Clear user fail records
401 executeUserClearFailRecords(userName.c_str());
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530402 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600403 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530404 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800405 lg2::error("Delete User '{USERNAME}' failed", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530406 elog<InternalFailure>();
407 }
408
409 usersList.erase(userName);
410
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800411 lg2::info("User '{USERNAME}' deleted successfully", "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530412 return;
413}
414
Nan Zhouda401fe2022-10-25 00:07:18 +0000415void UserMgr::checkDeleteGroupConstraints(const std::string& groupName)
416{
417 if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) ==
418 groupsMgr.end())
419 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800420 lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000421 elog<GroupNameDoesNotExists>();
422 }
423 checkAndThrowsForGroupChangeAllowed(groupName);
424}
425
426void UserMgr::deleteGroup(std::string groupName)
427{
428 checkDeleteGroupConstraints(groupName);
429 try
430 {
431 executeGroupDeletion(groupName.c_str());
432 }
433 catch (const InternalFailure& e)
434 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800435 lg2::error("Failed to delete group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000436 elog<InternalFailure>();
437 }
438
439 groupsMgr.erase(std::find(groupsMgr.begin(), groupsMgr.end(), groupName));
440 UserMgrIface::allGroups(groupsMgr);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800441 lg2::info("Successfully deleted group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000442}
443
444void UserMgr::checkCreateGroupConstraints(const std::string& groupName)
445{
446 if (std::find(groupsMgr.begin(), groupsMgr.end(), groupName) !=
447 groupsMgr.end())
448 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800449 lg2::error("Group '{GROUP}' already exists", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000450 elog<GroupNameExists>();
451 }
452 checkAndThrowForDisallowedGroupCreation(groupName);
453 if (groupsMgr.size() >= maxSystemGroupCount)
454 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800455 lg2::error("Group limit reached");
Nan Zhouda401fe2022-10-25 00:07:18 +0000456 elog<NoResource>(xyz::openbmc_project::User::Common::NoResource::REASON(
457 "Group limit reached"));
458 }
459}
460
461void UserMgr::createGroup(std::string groupName)
462{
463 checkCreateGroupConstraints(groupName);
464 try
465 {
466 executeGroupCreation(groupName.c_str());
467 }
468 catch (const InternalFailure& e)
469 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800470 lg2::error("Failed to create group '{GROUP}'", "GROUP", groupName);
Nan Zhouda401fe2022-10-25 00:07:18 +0000471 elog<InternalFailure>();
472 }
473 groupsMgr.push_back(groupName);
474 UserMgrIface::allGroups(groupsMgr);
475}
476
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530477void UserMgr::renameUser(std::string userName, std::string newUserName)
478{
479 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500480 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530481 throwForUserDoesNotExist(userName);
482 throwForUserExists(newUserName);
483 throwForUserNameConstraints(newUserName,
484 usersList[userName].get()->userGroups());
485 try
486 {
Nan Zhouf25443e2022-10-25 00:07:11 +0000487 executeUserRename(userName.c_str(), newUserName.c_str());
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530488 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600489 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530490 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800491 lg2::error("Rename '{USERNAME}' to '{NEWUSERNAME}' failed", "USERNAME",
492 userName, "NEWUSERNAME", newUserName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530493 elog<InternalFailure>();
494 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600495 const auto& user = usersList[userName];
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530496 std::string priv = user.get()->userPrivilege();
497 std::vector<std::string> groupNames = user.get()->userGroups();
498 bool enabled = user.get()->userEnabled();
P Dheeraj Srujan Kumarb01e2fe2021-12-13 09:43:28 +0530499 sdbusplus::message::object_path tempObjPath(usersObjPath);
500 tempObjPath /= newUserName;
501 std::string newUserObj(tempObjPath);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530502 // Special group 'ipmi' needs a way to identify user renamed, in order to
503 // update encrypted password. It can't rely only on InterfacesRemoved &
504 // InterfacesAdded. So first send out userRenamed signal.
505 this->userRenamed(userName, newUserName);
506 usersList.erase(userName);
Nan Zhou78d85042022-08-29 17:50:22 +0000507 usersList.emplace(newUserName, std::make_unique<phosphor::user::Users>(
508 bus, newUserObj.c_str(), groupNames,
509 priv, enabled, *this));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530510 return;
511}
512
Patrick Williams9638afb2021-02-22 17:16:24 -0600513void UserMgr::updateGroupsAndPriv(const std::string& userName,
Nan Zhoufef63032022-10-25 00:07:12 +0000514 std::vector<std::string> groupNames,
Patrick Williams9638afb2021-02-22 17:16:24 -0600515 const std::string& priv)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530516{
517 throwForInvalidPrivilege(priv);
518 throwForInvalidGroups(groupNames);
519 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500520 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530521 throwForUserDoesNotExist(userName);
Patrick Williams9638afb2021-02-22 17:16:24 -0600522 const std::vector<std::string>& oldGroupNames =
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530523 usersList[userName].get()->userGroups();
524 std::vector<std::string> groupDiff;
525 // Note: already dealing with sorted group lists.
526 std::set_symmetric_difference(oldGroupNames.begin(), oldGroupNames.end(),
527 groupNames.begin(), groupNames.end(),
528 std::back_inserter(groupDiff));
529 if (std::find(groupDiff.begin(), groupDiff.end(), "ipmi") !=
530 groupDiff.end())
531 {
532 throwForUserNameConstraints(userName, groupNames);
533 throwForMaxGrpUserCount(groupNames);
534 }
535
536 std::string groups = getCSVFromVector(groupNames);
537 bool sshRequested = removeStringFromCSV(groups, grpSsh);
538
539 // treat privilege as a group - This is to avoid using different file to
540 // store the same.
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530541 if (!priv.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530542 {
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530543 if (groups.size() != 0)
544 {
545 groups += ",";
546 }
547 groups += priv;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530548 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530549 try
550 {
Nan Zhoufef63032022-10-25 00:07:12 +0000551 executeUserModify(userName.c_str(), groups.c_str(), sshRequested);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530552 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600553 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530554 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800555 lg2::error(
556 "Unable to modify user privilege / groups for user '{USERNAME}'",
557 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530558 elog<InternalFailure>();
559 }
560
Nan Zhoufef63032022-10-25 00:07:12 +0000561 std::sort(groupNames.begin(), groupNames.end());
562 usersList[userName]->setUserGroups(groupNames);
563 usersList[userName]->setUserPrivilege(priv);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800564 lg2::info("User '{USERNAME}' groups / privilege updated successfully",
565 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530566}
567
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530568uint8_t UserMgr::minPasswordLength(uint8_t value)
569{
570 if (value == AccountPolicyIface::minPasswordLength())
571 {
572 return value;
573 }
574 if (value < minPasswdLength)
575 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800576 lg2::error("Attempting to set minPasswordLength to {VALUE}, less than "
577 "{MINVALUE}",
578 "VALUE", value, "MINVALUE", minPasswdLength);
Paul Fertser6dc7ed92022-01-21 19:36:34 +0000579 elog<InvalidArgument>(
580 Argument::ARGUMENT_NAME("minPasswordLength"),
581 Argument::ARGUMENT_VALUE(std::to_string(value).c_str()));
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530582 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700583 if (setPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
584 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530585 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800586 lg2::error("Unable to set minPasswordLength to {VALUE}", "VALUE",
587 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530588 elog<InternalFailure>();
589 }
590 return AccountPolicyIface::minPasswordLength(value);
591}
592
593uint8_t UserMgr::rememberOldPasswordTimes(uint8_t value)
594{
595 if (value == AccountPolicyIface::rememberOldPasswordTimes())
596 {
597 return value;
598 }
599 if (setPamModuleArgValue(pamPWHistory, remOldPasswdCount,
600 std::to_string(value)) != success)
601 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800602 lg2::error("Unable to set rememberOldPasswordTimes to {VALUE}", "VALUE",
603 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530604 elog<InternalFailure>();
605 }
606 return AccountPolicyIface::rememberOldPasswordTimes(value);
607}
608
609uint16_t UserMgr::maxLoginAttemptBeforeLockout(uint16_t value)
610{
611 if (value == AccountPolicyIface::maxLoginAttemptBeforeLockout())
612 {
613 return value;
614 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700615 if (setPamModuleConfValue(faillockConfigFile, maxFailedAttempt,
616 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530617 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800618 lg2::error("Unable to set maxLoginAttemptBeforeLockout to {VALUE}",
619 "VALUE", value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530620 elog<InternalFailure>();
621 }
622 return AccountPolicyIface::maxLoginAttemptBeforeLockout(value);
623}
624
625uint32_t UserMgr::accountUnlockTimeout(uint32_t value)
626{
627 if (value == AccountPolicyIface::accountUnlockTimeout())
628 {
629 return value;
630 }
Jason M. Bills2d042d12023-03-28 15:32:45 -0700631 if (setPamModuleConfValue(faillockConfigFile, unlockTimeout,
632 std::to_string(value)) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530633 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800634 lg2::error("Unable to set accountUnlockTimeout to {VALUE}", "VALUE",
635 value);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530636 elog<InternalFailure>();
637 }
638 return AccountPolicyIface::accountUnlockTimeout(value);
639}
640
Patrick Williams9638afb2021-02-22 17:16:24 -0600641int UserMgr::getPamModuleArgValue(const std::string& moduleName,
642 const std::string& argName,
643 std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530644{
Jason M. Bills2d042d12023-03-28 15:32:45 -0700645 std::string fileName = pamPasswdConfigFile;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530646 std::ifstream fileToRead(fileName, std::ios::in);
647 if (!fileToRead.is_open())
648 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800649 lg2::error("Failed to open pam configuration file {FILENAME}",
650 "FILENAME", fileName);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530651 return failure;
652 }
653 std::string line;
654 auto argSearch = argName + "=";
655 size_t startPos = 0;
656 size_t endPos = 0;
657 while (getline(fileToRead, line))
658 {
659 // skip comments section starting with #
660 if ((startPos = line.find('#')) != std::string::npos)
661 {
662 if (startPos == 0)
663 {
664 continue;
665 }
666 // skip comments after meaningful section and process those
667 line = line.substr(0, startPos);
668 }
669 if (line.find(moduleName) != std::string::npos)
670 {
671 if ((startPos = line.find(argSearch)) != std::string::npos)
672 {
673 if ((endPos = line.find(' ', startPos)) == std::string::npos)
674 {
675 endPos = line.size();
676 }
677 startPos += argSearch.size();
678 argValue = line.substr(startPos, endPos - startPos);
679 return success;
680 }
681 }
682 }
683 return failure;
684}
685
Jason M. Bills2d042d12023-03-28 15:32:45 -0700686int UserMgr::getPamModuleConfValue(const std::string& confFile,
687 const std::string& argName,
688 std::string& argValue)
689{
690 std::ifstream fileToRead(confFile, std::ios::in);
691 if (!fileToRead.is_open())
692 {
693 lg2::error("Failed to open pam configuration file {FILENAME}",
694 "FILENAME", confFile);
695 return failure;
696 }
697 std::string line;
698 auto argSearch = argName + "=";
699 size_t startPos = 0;
700 size_t endPos = 0;
701 while (getline(fileToRead, line))
702 {
703 // skip comments section starting with #
704 if ((startPos = line.find('#')) != std::string::npos)
705 {
706 if (startPos == 0)
707 {
708 continue;
709 }
710 // skip comments after meaningful section and process those
711 line = line.substr(0, startPos);
712 }
713 if ((startPos = line.find(argSearch)) != std::string::npos)
714 {
715 if ((endPos = line.find(' ', startPos)) == std::string::npos)
716 {
717 endPos = line.size();
718 }
719 startPos += argSearch.size();
720 argValue = line.substr(startPos, endPos - startPos);
721 return success;
722 }
723 }
724 return failure;
725}
726
Patrick Williams9638afb2021-02-22 17:16:24 -0600727int UserMgr::setPamModuleArgValue(const std::string& moduleName,
728 const std::string& argName,
729 const std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530730{
Jason M. Bills2d042d12023-03-28 15:32:45 -0700731 std::string fileName = pamPasswdConfigFile;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530732 std::string tmpFileName = fileName + "_tmp";
733 std::ifstream fileToRead(fileName, std::ios::in);
734 std::ofstream fileToWrite(tmpFileName, std::ios::out);
735 if (!fileToRead.is_open() || !fileToWrite.is_open())
736 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800737 lg2::error("Failed to open pam configuration file {FILENAME}",
738 "FILENAME", fileName);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530739 return failure;
740 }
741 std::string line;
742 auto argSearch = argName + "=";
743 size_t startPos = 0;
744 size_t endPos = 0;
745 bool found = false;
746 while (getline(fileToRead, line))
747 {
748 // skip comments section starting with #
749 if ((startPos = line.find('#')) != std::string::npos)
750 {
751 if (startPos == 0)
752 {
753 fileToWrite << line << std::endl;
754 continue;
755 }
756 // skip comments after meaningful section and process those
757 line = line.substr(0, startPos);
758 }
759 if (line.find(moduleName) != std::string::npos)
760 {
761 if ((startPos = line.find(argSearch)) != std::string::npos)
762 {
763 if ((endPos = line.find(' ', startPos)) == std::string::npos)
764 {
765 endPos = line.size();
766 }
767 startPos += argSearch.size();
768 fileToWrite << line.substr(0, startPos) << argValue
769 << line.substr(endPos, line.size() - endPos)
770 << std::endl;
771 found = true;
772 continue;
773 }
774 }
775 fileToWrite << line << std::endl;
776 }
777 fileToWrite.close();
778 fileToRead.close();
779 if (found)
780 {
781 if (std::rename(tmpFileName.c_str(), fileName.c_str()) == 0)
782 {
783 return success;
784 }
785 }
786 return failure;
787}
788
Jason M. Bills2d042d12023-03-28 15:32:45 -0700789int UserMgr::setPamModuleConfValue(const std::string& confFile,
790 const std::string& argName,
791 const std::string& argValue)
792{
793 std::string tmpConfFile = confFile + "_tmp";
794 std::ifstream fileToRead(confFile, std::ios::in);
795 std::ofstream fileToWrite(tmpConfFile, std::ios::out);
796 if (!fileToRead.is_open() || !fileToWrite.is_open())
797 {
798 lg2::error("Failed to open pam configuration file {FILENAME}",
799 "FILENAME", confFile);
800 return failure;
801 }
802 std::string line;
803 auto argSearch = argName + "=";
804 size_t startPos = 0;
805 size_t endPos = 0;
806 bool found = false;
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 fileToWrite << line << std::endl;
815 continue;
816 }
817 // skip comments after meaningful section and process those
818 line = line.substr(0, startPos);
819 }
820 if ((startPos = line.find(argSearch)) != std::string::npos)
821 {
822 if ((endPos = line.find(' ', startPos)) == std::string::npos)
823 {
824 endPos = line.size();
825 }
826 startPos += argSearch.size();
827 fileToWrite << line.substr(0, startPos) << argValue
828 << line.substr(endPos, line.size() - endPos)
829 << std::endl;
830 found = true;
831 continue;
832 }
833 fileToWrite << line << std::endl;
834 }
835 fileToWrite.close();
836 fileToRead.close();
837 if (found)
838 {
839 if (std::rename(tmpConfFile.c_str(), confFile.c_str()) == 0)
840 {
841 return success;
842 }
843 }
844 return failure;
845}
846
Patrick Williams9638afb2021-02-22 17:16:24 -0600847void UserMgr::userEnable(const std::string& userName, bool enabled)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530848{
849 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500850 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530851 throwForUserDoesNotExist(userName);
852 try
853 {
Nan Zhou6b6f2d82022-10-25 00:07:17 +0000854 executeUserModifyUserEnable(userName.c_str(), enabled);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530855 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600856 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530857 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800858 lg2::error("Unable to modify user enabled state for '{USERNAME}'",
859 "USERNAME", userName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530860 elog<InternalFailure>();
861 }
862
Nan Zhou6b6f2d82022-10-25 00:07:17 +0000863 usersList[userName]->setUserEnabled(enabled);
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800864 lg2::info("User '{USERNAME}' has been {STATUS}", "USERNAME", userName,
865 "STATUS", enabled ? "Enabled" : "Disabled");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530866}
867
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530868/**
Jason M. Bills2d042d12023-03-28 15:32:45 -0700869 * faillock app will provide the user failed login list with when the attempt
870 * was made, the type, the source, and if it's valid.
871 *
872 * Valid in this case means that the attempt was made within the fail_interval
873 * time. So, we can check this list for the number of valid entries (lines
874 * ending with 'V') compared to the maximum allowed to determine if the user is
875 * locked out.
876 *
877 * This data is only refreshed when an attempt is made, so if the user appears
878 * to be locked out, we must also check if the most recent attempt was older
879 * than the unlock_time to know if the user has since been unlocked.
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530880 **/
Jason M. Bills2d042d12023-03-28 15:32:45 -0700881bool UserMgr::parseFaillockForLockout(
882 const std::vector<std::string>& faillockOutput)
883{
884 uint16_t failAttempts = 0;
885 time_t lastFailedAttempt{};
886 for (const std::string& line : faillockOutput)
887 {
888 if (!line.ends_with("V"))
889 {
890 continue;
891 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530892
Jason M. Bills2d042d12023-03-28 15:32:45 -0700893 // Count this failed attempt
894 failAttempts++;
895
896 // Update the last attempt time
897 // First get the "when" which is the first two words (date and time)
898 size_t pos = line.find(" ");
899 if (pos == std::string::npos)
900 {
901 continue;
902 }
903 pos = line.find(" ", pos + 1);
904 if (pos == std::string::npos)
905 {
906 continue;
907 }
908 std::string failDateTime = line.substr(0, pos);
909
910 // NOTE: Cannot use std::get_time() here as the implementation of %y in
911 // libstdc++ does not match POSIX strptime() before gcc 12.1.0
912 // https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=a8d3c98746098e2784be7144c1ccc9fcc34a0888
913 std::tm tmStruct = {};
914 if (!strptime(failDateTime.c_str(), "%F %T", &tmStruct))
915 {
916 lg2::error("Failed to parse latest failure date/time");
917 elog<InternalFailure>();
918 }
919
920 time_t failTimestamp = std::mktime(&tmStruct);
921 lastFailedAttempt = std::max(failTimestamp, lastFailedAttempt);
922 }
923
924 if (failAttempts < AccountPolicyIface::maxLoginAttemptBeforeLockout())
925 {
926 return false;
927 }
928
929 if (lastFailedAttempt +
930 static_cast<time_t>(AccountPolicyIface::accountUnlockTimeout()) <=
931 std::time(NULL))
932 {
933 return false;
934 }
935
936 return true;
937}
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530938
Patrick Williams9638afb2021-02-22 17:16:24 -0600939bool UserMgr::userLockedForFailedAttempt(const std::string& userName)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530940{
941 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500942 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Jiaqing Zhaofba4bb12022-06-24 01:30:57 +0800943 if (AccountPolicyIface::maxLoginAttemptBeforeLockout() == 0)
944 {
945 return false;
946 }
947
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530948 std::vector<std::string> output;
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800949 try
950 {
Nan Zhoua2953032022-11-11 21:50:32 +0000951 output = getFailedAttempt(userName.c_str());
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800952 }
953 catch (const InternalFailure& e)
954 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800955 lg2::error("Unable to read login failure counter");
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800956 elog<InternalFailure>();
957 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530958
Jason M. Bills2d042d12023-03-28 15:32:45 -0700959 return parseFaillockForLockout(output);
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530960}
961
Patrick Williams9638afb2021-02-22 17:16:24 -0600962bool UserMgr::userLockedForFailedAttempt(const std::string& userName,
963 const bool& value)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530964{
965 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500966 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530967 if (value == true)
968 {
969 return userLockedForFailedAttempt(userName);
970 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530971
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800972 try
973 {
Jayanth Othayothac921a52023-07-21 03:48:55 -0500974 // Clear user fail records
975 executeUserClearFailRecords(userName.c_str());
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800976 }
977 catch (const InternalFailure& e)
978 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +0800979 lg2::error("Unable to reset login failure counter");
Jiaqing Zhao8557d322022-06-23 23:00:01 +0800980 elog<InternalFailure>();
981 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530982
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530983 return userLockedForFailedAttempt(userName);
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530984}
985
Patrick Williams9638afb2021-02-22 17:16:24 -0600986bool UserMgr::userPasswordExpired(const std::string& userName)
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600987{
988 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500989 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600990
991 struct spwd spwd
Patrick Williams9638afb2021-02-22 17:16:24 -0600992 {};
993 struct spwd* spwdPtr = nullptr;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600994 auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
995 if (buflen < -1)
996 {
997 // Use a default size if there is no hard limit suggested by sysconf()
998 buflen = 1024;
999 }
1000 std::vector<char> buffer(buflen);
Patrick Williamsb7043042023-05-10 07:50:52 -05001001 auto status = getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen,
1002 &spwdPtr);
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001003 // On success, getspnam_r() returns zero, and sets *spwdPtr to spwd.
1004 // If no matching password record was found, these functions return 0
1005 // and store NULL in *spwdPtr
1006 if ((status == 0) && (&spwd == spwdPtr))
1007 {
1008 // Determine password validity per "chage" docs, where:
1009 // spwd.sp_lstchg == 0 means password is expired, and
1010 // spwd.sp_max == -1 means the password does not expire.
Nan Zhou78d85042022-08-29 17:50:22 +00001011 constexpr long secondsPerDay = 60 * 60 * 24;
1012 long today = static_cast<long>(time(NULL)) / secondsPerDay;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001013 if ((spwd.sp_lstchg == 0) ||
1014 ((spwd.sp_max != -1) && ((spwd.sp_max + spwd.sp_lstchg) < today)))
1015 {
1016 return true;
1017 }
1018 }
1019 else
1020 {
Jayaprakash Mutyala75be4e62020-09-18 15:59:06 +00001021 // User entry is missing in /etc/shadow, indicating no SHA password.
1022 // Treat this as new user without password entry in /etc/shadow
1023 // TODO: Add property to indicate user password was not set yet
1024 // https://github.com/openbmc/phosphor-user-manager/issues/8
1025 return false;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001026 }
1027
1028 return false;
1029}
1030
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301031UserSSHLists UserMgr::getUserAndSshGrpList()
1032{
1033 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -05001034 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301035
1036 std::vector<std::string> userList;
1037 std::vector<std::string> sshUsersList;
1038 struct passwd pw, *pwp = nullptr;
1039 std::array<char, 1024> buffer{};
1040
1041 phosphor::user::File passwd(passwdFileName, "r");
1042 if ((passwd)() == NULL)
1043 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001044 lg2::error("Error opening {FILENAME}", "FILENAME", passwdFileName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301045 elog<InternalFailure>();
1046 }
1047
1048 while (true)
1049 {
1050 auto r = fgetpwent_r((passwd)(), &pw, buffer.data(), buffer.max_size(),
1051 &pwp);
1052 if ((r != 0) || (pwp == NULL))
1053 {
1054 // Any error, break the loop.
1055 break;
1056 }
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +05301057#ifdef ENABLE_ROOT_USER_MGMT
Richard Marian Thomaiyar7ba3c712018-07-31 13:41:36 +05301058 // Add all users whose UID >= 1000 and < 65534
1059 // and special UID 0.
1060 if ((pwp->pw_uid == 0) ||
1061 ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534)))
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +05301062#else
1063 // Add all users whose UID >=1000 and < 65534
1064 if ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534))
1065#endif
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301066 {
1067 std::string userName(pwp->pw_name);
1068 userList.emplace_back(userName);
1069
1070 // ssh doesn't have separate group. Check login shell entry to
1071 // get all users list which are member of ssh group.
1072 std::string loginShell(pwp->pw_shell);
1073 if (loginShell == "/bin/sh")
1074 {
1075 sshUsersList.emplace_back(userName);
1076 }
1077 }
1078 }
1079 endpwent();
1080 return std::make_pair(std::move(userList), std::move(sshUsersList));
1081}
1082
1083size_t UserMgr::getIpmiUsersCount()
1084{
1085 std::vector<std::string> userList = getUsersInGroup("ipmi");
1086 return userList.size();
1087}
1088
Nan Zhou49c81362022-10-25 00:07:08 +00001089size_t UserMgr::getNonIpmiUsersCount()
1090{
1091 std::vector<std::string> ipmiUsers = getUsersInGroup("ipmi");
1092 return usersList.size() - ipmiUsers.size();
1093}
1094
Patrick Williams9638afb2021-02-22 17:16:24 -06001095bool UserMgr::isUserEnabled(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301096{
1097 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -05001098 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301099 std::array<char, 4096> buffer{};
1100 struct spwd spwd;
Patrick Williams9638afb2021-02-22 17:16:24 -06001101 struct spwd* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301102 int status = getspnam_r(userName.c_str(), &spwd, buffer.data(),
1103 buffer.max_size(), &resultPtr);
1104 if (!status && (&spwd == resultPtr))
1105 {
1106 if (resultPtr->sp_expire >= 0)
1107 {
1108 return false; // user locked out
1109 }
1110 return true;
1111 }
1112 return false; // assume user is disabled for any error.
1113}
1114
Patrick Williams9638afb2021-02-22 17:16:24 -06001115std::vector<std::string> UserMgr::getUsersInGroup(const std::string& groupName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301116{
1117 std::vector<std::string> usersInGroup;
1118 // Should be more than enough to get the pwd structure.
1119 std::array<char, 4096> buffer{};
1120 struct group grp;
Patrick Williams9638afb2021-02-22 17:16:24 -06001121 struct group* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301122
1123 int status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1124 buffer.max_size(), &resultPtr);
1125
1126 if (!status && (&grp == resultPtr))
1127 {
1128 for (; *(grp.gr_mem) != NULL; ++(grp.gr_mem))
1129 {
1130 usersInGroup.emplace_back(*(grp.gr_mem));
1131 }
1132 }
1133 else
1134 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001135 lg2::error("Group '{GROUPNAME}' not found", "GROUPNAME", groupName);
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301136 // Don't throw error, just return empty userList - fallback
1137 }
1138 return usersInGroup;
1139}
1140
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001141DbusUserObj UserMgr::getPrivilegeMapperObject(void)
1142{
1143 DbusUserObj objects;
1144 try
1145 {
Ravi Teja5fe724a2019-05-07 05:14:42 -05001146 std::string basePath = "/xyz/openbmc_project/user/ldap/openldap";
1147 std::string interface = "xyz.openbmc_project.User.Ldap.Config";
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001148
Patrick Williamsb7043042023-05-10 07:50:52 -05001149 auto ldapMgmtService = getServiceName(std::move(basePath),
1150 std::move(interface));
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001151 auto method = bus.new_method_call(
1152 ldapMgmtService.c_str(), ldapMgrObjBasePath,
1153 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1154
1155 auto reply = bus.call(method);
1156 reply.read(objects);
1157 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001158 catch (const InternalFailure& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001159 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001160 lg2::error("Unable to get the User Service: {ERR}", "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001161 throw;
1162 }
Patrick Williamsb3ef4e12022-07-22 19:26:55 -05001163 catch (const sdbusplus::exception_t& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001164 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001165 lg2::error("Failed to excute GetManagedObjects at {PATH}: {ERR}",
1166 "PATH", ldapMgrObjBasePath, "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001167 throw;
1168 }
1169 return objects;
1170}
1171
Patrick Williams9638afb2021-02-22 17:16:24 -06001172std::string UserMgr::getServiceName(std::string&& path, std::string&& intf)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001173{
1174 auto mapperCall = bus.new_method_call(objMapperService, objMapperPath,
1175 objMapperInterface, "GetObject");
1176
1177 mapperCall.append(std::move(path));
1178 mapperCall.append(std::vector<std::string>({std::move(intf)}));
1179
1180 auto mapperResponseMsg = bus.call(mapperCall);
1181
1182 if (mapperResponseMsg.is_method_error())
1183 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001184 lg2::error("Error in mapper call");
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001185 elog<InternalFailure>();
1186 }
1187
1188 std::map<std::string, std::vector<std::string>> mapperResponse;
1189 mapperResponseMsg.read(mapperResponse);
1190
1191 if (mapperResponse.begin() == mapperResponse.end())
1192 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001193 lg2::error("Invalid response from mapper");
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001194 elog<InternalFailure>();
1195 }
1196
1197 return mapperResponse.begin()->first;
1198}
1199
Alexander Filippov75626582022-02-09 18:42:37 +03001200gid_t UserMgr::getPrimaryGroup(const std::string& userName) const
1201{
1202 static auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1203 if (buflen <= 0)
1204 {
1205 // Use a default size if there is no hard limit suggested by sysconf()
1206 buflen = 1024;
1207 }
1208
1209 struct passwd pwd;
1210 struct passwd* pwdPtr = nullptr;
1211 std::vector<char> buffer(buflen);
1212
1213 auto status = getpwnam_r(userName.c_str(), &pwd, buffer.data(),
1214 buffer.size(), &pwdPtr);
1215 // On success, getpwnam_r() returns zero, and set *pwdPtr to pwd.
1216 // If no matching password record was found, these functions return 0
1217 // and store NULL in *pwdPtr
1218 if (!status && (&pwd == pwdPtr))
1219 {
1220 return pwd.pw_gid;
1221 }
1222
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001223 lg2::error("User {USERNAME} does not exist", "USERNAME", userName);
Alexander Filippov75626582022-02-09 18:42:37 +03001224 elog<UserNameDoesNotExist>();
1225}
1226
1227bool UserMgr::isGroupMember(const std::string& userName, gid_t primaryGid,
1228 const std::string& groupName) const
1229{
1230 static auto buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
1231 if (buflen <= 0)
1232 {
1233 // Use a default size if there is no hard limit suggested by sysconf()
1234 buflen = 1024;
1235 }
1236
1237 struct group grp;
1238 struct group* grpPtr = nullptr;
1239 std::vector<char> buffer(buflen);
1240
1241 auto status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1242 buffer.size(), &grpPtr);
1243
1244 // Groups with a lot of members may require a buffer of bigger size than
1245 // suggested by _SC_GETGR_R_SIZE_MAX.
1246 // 32K should be enough for about 2K members.
1247 constexpr auto maxBufferLength = 32 * 1024;
1248 while (status == ERANGE && buflen < maxBufferLength)
1249 {
1250 buflen *= 2;
1251 buffer.resize(buflen);
1252
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001253 lg2::debug("Increase buffer for getgrnam_r() to {SIZE}", "SIZE",
1254 buflen);
Alexander Filippov75626582022-02-09 18:42:37 +03001255
1256 status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
1257 buffer.size(), &grpPtr);
1258 }
1259
1260 // On success, getgrnam_r() returns zero, and set *grpPtr to grp.
1261 // If no matching group record was found, these functions return 0
1262 // and store NULL in *grpPtr
1263 if (!status && (&grp == grpPtr))
1264 {
1265 if (primaryGid == grp.gr_gid)
1266 {
1267 return true;
1268 }
1269
1270 for (auto i = 0; grp.gr_mem && grp.gr_mem[i]; ++i)
1271 {
1272 if (userName == grp.gr_mem[i])
1273 {
1274 return true;
1275 }
1276 }
1277 }
1278 else if (status == ERANGE)
1279 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001280 lg2::error("Group info of {GROUP} requires too much memory", "GROUP",
1281 groupName);
Alexander Filippov75626582022-02-09 18:42:37 +03001282 }
1283 else
1284 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001285 lg2::error("Group {GROUP} does not exist", "GROUP", groupName);
Alexander Filippov75626582022-02-09 18:42:37 +03001286 }
1287
1288 return false;
1289}
1290
Nan Zhouda401fe2022-10-25 00:07:18 +00001291void UserMgr::executeGroupCreation(const char* groupName)
1292{
1293 executeCmd("/usr/sbin/groupadd", groupName);
1294}
1295
1296void UserMgr::executeGroupDeletion(const char* groupName)
1297{
1298 executeCmd("/usr/sbin/groupdel", groupName);
1299}
1300
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001301UserInfoMap UserMgr::getUserInfo(std::string userName)
1302{
1303 UserInfoMap userInfo;
1304 // Check whether the given user is local user or not.
Nan Zhou8a11d992022-10-25 00:07:06 +00001305 if (isUserExist(userName))
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001306 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001307 const auto& user = usersList[userName];
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001308 userInfo.emplace("UserPrivilege", user.get()->userPrivilege());
1309 userInfo.emplace("UserGroups", user.get()->userGroups());
1310 userInfo.emplace("UserEnabled", user.get()->userEnabled());
1311 userInfo.emplace("UserLockedForFailedAttempt",
1312 user.get()->userLockedForFailedAttempt());
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001313 userInfo.emplace("UserPasswordExpired",
1314 user.get()->userPasswordExpired());
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001315 userInfo.emplace("RemoteUser", false);
1316 }
1317 else
1318 {
Alexander Filippov75626582022-02-09 18:42:37 +03001319 auto primaryGid = getPrimaryGroup(userName);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001320
1321 DbusUserObj objects = getPrivilegeMapperObject();
1322
Ravi Teja5fe724a2019-05-07 05:14:42 -05001323 std::string ldapConfigPath;
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001324 std::string userPrivilege;
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001325
1326 try
1327 {
Alexander Filippov75626582022-02-09 18:42:37 +03001328 for (const auto& [path, interfaces] : objects)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001329 {
Alexander Filippov75626582022-02-09 18:42:37 +03001330 auto it = interfaces.find("xyz.openbmc_project.Object.Enable");
1331 if (it != interfaces.end())
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001332 {
Alexander Filippov75626582022-02-09 18:42:37 +03001333 auto propIt = it->second.find("Enabled");
1334 if (propIt != it->second.end() &&
1335 std::get<bool>(propIt->second))
Ravi Teja5fe724a2019-05-07 05:14:42 -05001336 {
Alexander Filippov75626582022-02-09 18:42:37 +03001337 ldapConfigPath = path.str + '/';
1338 break;
Ravi Teja5fe724a2019-05-07 05:14:42 -05001339 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001340 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001341 }
1342
1343 if (ldapConfigPath.empty())
1344 {
1345 return userInfo;
1346 }
1347
Alexander Filippov75626582022-02-09 18:42:37 +03001348 for (const auto& [path, interfaces] : objects)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001349 {
Alexander Filippov75626582022-02-09 18:42:37 +03001350 if (!path.str.starts_with(ldapConfigPath))
Ravi Teja5fe724a2019-05-07 05:14:42 -05001351 {
Alexander Filippov75626582022-02-09 18:42:37 +03001352 continue;
1353 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001354
Alexander Filippov75626582022-02-09 18:42:37 +03001355 auto it = interfaces.find(
1356 "xyz.openbmc_project.User.PrivilegeMapperEntry");
1357 if (it != interfaces.end())
1358 {
1359 std::string privilege;
1360 std::string groupName;
1361
1362 for (const auto& [propName, propValue] : it->second)
1363 {
1364 if (propName == "GroupName")
Ravi Teja5fe724a2019-05-07 05:14:42 -05001365 {
Alexander Filippov75626582022-02-09 18:42:37 +03001366 groupName = std::get<std::string>(propValue);
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001367 }
Alexander Filippov75626582022-02-09 18:42:37 +03001368 else if (propName == "Privilege")
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001369 {
Alexander Filippov75626582022-02-09 18:42:37 +03001370 privilege = std::get<std::string>(propValue);
Ravi Teja5fe724a2019-05-07 05:14:42 -05001371 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001372 }
Alexander Filippov75626582022-02-09 18:42:37 +03001373
1374 if (!groupName.empty() && !privilege.empty() &&
1375 isGroupMember(userName, primaryGid, groupName))
1376 {
1377 userPrivilege = privilege;
1378 break;
1379 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001380 }
Jiaqing Zhao745ce2e2022-05-31 17:11:31 +08001381 if (!userPrivilege.empty())
1382 {
1383 break;
1384 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001385 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001386
Jiaqing Zhao56862062022-05-31 19:16:09 +08001387 if (!userPrivilege.empty())
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001388 {
Jiaqing Zhao56862062022-05-31 19:16:09 +08001389 userInfo.emplace("UserPrivilege", userPrivilege);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001390 }
Jiaqing Zhao56862062022-05-31 19:16:09 +08001391 else
1392 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001393 lg2::warning("LDAP group privilege mapping does not exist, "
1394 "default \"priv-user\" is used");
Jiaqing Zhao56862062022-05-31 19:16:09 +08001395 userInfo.emplace("UserPrivilege", "priv-user");
1396 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001397 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001398 catch (const std::bad_variant_access& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001399 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001400 lg2::error("Error while accessing variant: {ERR}", "ERR", e);
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001401 elog<InternalFailure>();
1402 }
1403 userInfo.emplace("RemoteUser", true);
1404 }
1405
1406 return userInfo;
1407}
1408
Nan Zhou4bc69812022-10-25 00:07:13 +00001409void UserMgr::initializeAccountPolicy()
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301410{
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301411 std::string valueStr;
1412 auto value = minPasswdLength;
1413 unsigned long tmp = 0;
Jason M. Bills2d042d12023-03-28 15:32:45 -07001414 if (getPamModuleConfValue(pwQualityConfigFile, minPasswdLenProp,
1415 valueStr) != success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301416 {
1417 AccountPolicyIface::minPasswordLength(minPasswdLength);
1418 }
1419 else
1420 {
1421 try
1422 {
1423 tmp = std::stoul(valueStr, nullptr);
1424 if (tmp > std::numeric_limits<decltype(value)>::max())
1425 {
1426 throw std::out_of_range("Out of range");
1427 }
1428 value = static_cast<decltype(value)>(tmp);
1429 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001430 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301431 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001432 lg2::error("Exception for MinPasswordLength: {ERR}", "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001433 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301434 }
1435 AccountPolicyIface::minPasswordLength(value);
1436 }
1437 valueStr.clear();
1438 if (getPamModuleArgValue(pamPWHistory, remOldPasswdCount, valueStr) !=
1439 success)
1440 {
1441 AccountPolicyIface::rememberOldPasswordTimes(0);
1442 }
1443 else
1444 {
1445 value = 0;
1446 try
1447 {
1448 tmp = std::stoul(valueStr, nullptr);
1449 if (tmp > std::numeric_limits<decltype(value)>::max())
1450 {
1451 throw std::out_of_range("Out of range");
1452 }
1453 value = static_cast<decltype(value)>(tmp);
1454 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001455 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301456 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001457 lg2::error("Exception for RememberOldPasswordTimes: {ERR}", "ERR",
1458 e);
Patrick Venture045b1122018-10-16 15:59:29 -07001459 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301460 }
1461 AccountPolicyIface::rememberOldPasswordTimes(value);
1462 }
1463 valueStr.clear();
Jason M. Bills2d042d12023-03-28 15:32:45 -07001464 if (getPamModuleConfValue(faillockConfigFile, maxFailedAttempt, valueStr) !=
1465 success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301466 {
1467 AccountPolicyIface::maxLoginAttemptBeforeLockout(0);
1468 }
1469 else
1470 {
1471 uint16_t value16 = 0;
1472 try
1473 {
1474 tmp = std::stoul(valueStr, nullptr);
1475 if (tmp > std::numeric_limits<decltype(value16)>::max())
1476 {
1477 throw std::out_of_range("Out of range");
1478 }
1479 value16 = static_cast<decltype(value16)>(tmp);
1480 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001481 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301482 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001483 lg2::error("Exception for MaxLoginAttemptBeforLockout: {ERR}",
1484 "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001485 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301486 }
1487 AccountPolicyIface::maxLoginAttemptBeforeLockout(value16);
1488 }
1489 valueStr.clear();
Jason M. Bills2d042d12023-03-28 15:32:45 -07001490 if (getPamModuleConfValue(faillockConfigFile, unlockTimeout, valueStr) !=
1491 success)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301492 {
1493 AccountPolicyIface::accountUnlockTimeout(0);
1494 }
1495 else
1496 {
1497 uint32_t value32 = 0;
1498 try
1499 {
1500 tmp = std::stoul(valueStr, nullptr);
1501 if (tmp > std::numeric_limits<decltype(value32)>::max())
1502 {
1503 throw std::out_of_range("Out of range");
1504 }
1505 value32 = static_cast<decltype(value32)>(tmp);
1506 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001507 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301508 {
Jiaqing Zhao11ec6662022-07-05 20:55:34 +08001509 lg2::error("Exception for AccountUnlockTimeout: {ERR}", "ERR", e);
Patrick Venture045b1122018-10-16 15:59:29 -07001510 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301511 }
1512 AccountPolicyIface::accountUnlockTimeout(value32);
1513 }
Nan Zhou4bc69812022-10-25 00:07:13 +00001514}
1515
1516void UserMgr::initUserObjects(void)
1517{
1518 // All user management lock has to be based on /etc/shadow
1519 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
1520 std::vector<std::string> userNameList;
1521 std::vector<std::string> sshGrpUsersList;
1522 UserSSHLists userSSHLists = getUserAndSshGrpList();
1523 userNameList = std::move(userSSHLists.first);
1524 sshGrpUsersList = std::move(userSSHLists.second);
1525
1526 if (!userNameList.empty())
1527 {
1528 std::map<std::string, std::vector<std::string>> groupLists;
Nan Zhouda401fe2022-10-25 00:07:18 +00001529 // We only track users that are in the |predefinedGroups|
1530 // The other groups don't contain real BMC users.
1531 for (const char* grp : predefinedGroups)
Nan Zhou4bc69812022-10-25 00:07:13 +00001532 {
1533 if (grp == grpSsh)
1534 {
1535 groupLists.emplace(grp, sshGrpUsersList);
1536 }
1537 else
1538 {
1539 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1540 groupLists.emplace(grp, grpUsersList);
1541 }
1542 }
1543 for (auto& grp : privMgr)
1544 {
1545 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1546 groupLists.emplace(grp, grpUsersList);
1547 }
1548
1549 for (auto& user : userNameList)
1550 {
1551 std::vector<std::string> userGroups;
1552 std::string userPriv;
1553 for (const auto& grp : groupLists)
1554 {
1555 std::vector<std::string> tempGrp = grp.second;
1556 if (std::find(tempGrp.begin(), tempGrp.end(), user) !=
1557 tempGrp.end())
1558 {
1559 if (std::find(privMgr.begin(), privMgr.end(), grp.first) !=
1560 privMgr.end())
1561 {
1562 userPriv = grp.first;
1563 }
1564 else
1565 {
1566 userGroups.emplace_back(grp.first);
1567 }
1568 }
1569 }
1570 // Add user objects to the Users path.
1571 sdbusplus::message::object_path tempObjPath(usersObjPath);
1572 tempObjPath /= user;
1573 std::string objPath(tempObjPath);
1574 std::sort(userGroups.begin(), userGroups.end());
1575 usersList.emplace(user, std::make_unique<phosphor::user::Users>(
1576 bus, objPath.c_str(), userGroups,
1577 userPriv, isUserEnabled(user), *this));
1578 }
1579 }
1580}
1581
1582UserMgr::UserMgr(sdbusplus::bus_t& bus, const char* path) :
1583 Ifaces(bus, path, Ifaces::action::defer_emit), bus(bus), path(path),
1584 pamPasswdConfigFile(defaultPamPasswdConfigFile),
Jason M. Bills2d042d12023-03-28 15:32:45 -07001585 faillockConfigFile(defaultFaillockConfigFile),
1586 pwQualityConfigFile(defaultPWQualityConfigFile)
Nan Zhou4bc69812022-10-25 00:07:13 +00001587{
1588 UserMgrIface::allPrivileges(privMgr);
Nan Zhouda401fe2022-10-25 00:07:18 +00001589 groupsMgr = readAllGroupsOnSystem();
Nan Zhou4bc69812022-10-25 00:07:13 +00001590 std::sort(groupsMgr.begin(), groupsMgr.end());
1591 UserMgrIface::allGroups(groupsMgr);
1592 initializeAccountPolicy();
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301593 initUserObjects();
Ratan Gupta1af12232018-11-03 00:35:38 +05301594
1595 // emit the signal
1596 this->emit_object_added();
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301597}
1598
Nan Zhou49c81362022-10-25 00:07:08 +00001599void UserMgr::executeUserAdd(const char* userName, const char* groups,
1600 bool sshRequested, bool enabled)
1601{
1602 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1603 // 1970-01-01, that's an implementation-defined behavior
1604 executeCmd("/usr/sbin/useradd", userName, "-G", groups, "-m", "-N", "-s",
Tang Yiwei75ea3e42022-04-25 10:48:15 +08001605 (sshRequested ? "/bin/sh" : "/sbin/nologin"), "-e",
Nan Zhou49c81362022-10-25 00:07:08 +00001606 (enabled ? "" : "1970-01-01"));
1607}
1608
1609void UserMgr::executeUserDelete(const char* userName)
1610{
1611 executeCmd("/usr/sbin/userdel", userName, "-r");
1612}
1613
Jayanth Othayothac921a52023-07-21 03:48:55 -05001614void UserMgr::executeUserClearFailRecords(const char* userName)
1615{
1616 executeCmd("/usr/sbin/faillock", "--user", userName, "--reset");
1617}
1618
Nan Zhouf25443e2022-10-25 00:07:11 +00001619void UserMgr::executeUserRename(const char* userName, const char* newUserName)
1620{
1621 std::string newHomeDir = "/home/";
1622 newHomeDir += newUserName;
1623 executeCmd("/usr/sbin/usermod", "-l", newUserName, userName, "-d",
1624 newHomeDir.c_str(), "-m");
1625}
1626
Nan Zhoufef63032022-10-25 00:07:12 +00001627void UserMgr::executeUserModify(const char* userName, const char* newGroups,
1628 bool sshRequested)
1629{
1630 executeCmd("/usr/sbin/usermod", userName, "-G", newGroups, "-s",
Tang Yiwei75ea3e42022-04-25 10:48:15 +08001631 (sshRequested ? "/bin/sh" : "/sbin/nologin"));
Nan Zhoufef63032022-10-25 00:07:12 +00001632}
1633
Nan Zhou6b6f2d82022-10-25 00:07:17 +00001634void UserMgr::executeUserModifyUserEnable(const char* userName, bool enabled)
1635{
1636 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
1637 // 1970-01-01, that's an implementation-defined behavior
1638 executeCmd("/usr/sbin/usermod", userName, "-e",
1639 (enabled ? "" : "1970-01-01"));
1640}
1641
Nan Zhoua2953032022-11-11 21:50:32 +00001642std::vector<std::string> UserMgr::getFailedAttempt(const char* userName)
1643{
Jason M. Bills2d042d12023-03-28 15:32:45 -07001644 return executeCmd("/usr/sbin/faillock", "--user", userName);
Nan Zhoua2953032022-11-11 21:50:32 +00001645}
1646
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301647} // namespace user
1648} // namespace phosphor