blob: 307c810314ef1f4dd865ade8d64f6cf8084dc216 [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>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053034#include <boost/process/child.hpp>
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +053035#include <boost/process/io.hpp>
Patrick Williams9638afb2021-02-22 17:16:24 -060036#include <phosphor-logging/elog-errors.hpp>
37#include <phosphor-logging/elog.hpp>
38#include <phosphor-logging/log.hpp>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053039#include <xyz/openbmc_project/Common/error.hpp>
40#include <xyz/openbmc_project/User/Common/error.hpp>
Patrick Williams9638afb2021-02-22 17:16:24 -060041
42#include <algorithm>
43#include <fstream>
44#include <numeric>
45#include <regex>
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053046
47namespace phosphor
48{
49namespace user
50{
51
Patrick Williams9638afb2021-02-22 17:16:24 -060052static constexpr const char* passwdFileName = "/etc/passwd";
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053053static constexpr size_t ipmiMaxUsers = 15;
54static constexpr size_t ipmiMaxUserNameLen = 16;
55static constexpr size_t systemMaxUserNameLen = 30;
56static constexpr size_t maxSystemUsers = 30;
Patrick Williams9638afb2021-02-22 17:16:24 -060057static constexpr const char* grpSsh = "ssh";
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +053058static constexpr uint8_t minPasswdLength = 8;
59static constexpr int success = 0;
60static constexpr int failure = -1;
61
62// pam modules related
Patrick Williams9638afb2021-02-22 17:16:24 -060063static constexpr const char* pamTally2 = "pam_tally2.so";
64static constexpr const char* pamCrackLib = "pam_cracklib.so";
65static constexpr const char* pamPWHistory = "pam_pwhistory.so";
66static constexpr const char* minPasswdLenProp = "minlen";
67static constexpr const char* remOldPasswdCount = "remember";
68static constexpr const char* maxFailedAttempt = "deny";
69static constexpr const char* unlockTimeout = "unlock_time";
70static constexpr const char* pamPasswdConfigFile = "/etc/pam.d/common-password";
71static constexpr const char* pamAuthConfigFile = "/etc/pam.d/common-auth";
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053072
Ratan Guptaaeaf9412019-02-11 04:41:52 -060073// Object Manager related
Patrick Williams9638afb2021-02-22 17:16:24 -060074static constexpr const char* ldapMgrObjBasePath =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060075 "/xyz/openbmc_project/user/ldap";
76
77// Object Mapper related
Patrick Williams9638afb2021-02-22 17:16:24 -060078static constexpr const char* objMapperService =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060079 "xyz.openbmc_project.ObjectMapper";
Patrick Williams9638afb2021-02-22 17:16:24 -060080static constexpr const char* objMapperPath =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060081 "/xyz/openbmc_project/object_mapper";
Patrick Williams9638afb2021-02-22 17:16:24 -060082static constexpr const char* objMapperInterface =
Ratan Guptaaeaf9412019-02-11 04:41:52 -060083 "xyz.openbmc_project.ObjectMapper";
84
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053085using namespace phosphor::logging;
86using InsufficientPermission =
87 sdbusplus::xyz::openbmc_project::Common::Error::InsufficientPermission;
88using InternalFailure =
89 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
90using InvalidArgument =
91 sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
92using UserNameExists =
93 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameExists;
94using UserNameDoesNotExist =
95 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameDoesNotExist;
96using UserNameGroupFail =
97 sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameGroupFail;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +053098using NoResource =
99 sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
100
101using Argument = xyz::openbmc_project::Common::InvalidArgument;
102
103template <typename... ArgTypes>
Patrick Williams9638afb2021-02-22 17:16:24 -0600104static std::vector<std::string> executeCmd(const char* path,
105 ArgTypes&&... tArgs)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530106{
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530107 std::vector<std::string> stdOutput;
108 boost::process::ipstream stdOutStream;
Patrick Williams9638afb2021-02-22 17:16:24 -0600109 boost::process::child execProg(path, const_cast<char*>(tArgs)...,
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530110 boost::process::std_out > stdOutStream);
111 std::string stdOutLine;
112
113 while (stdOutStream && std::getline(stdOutStream, stdOutLine) &&
114 !stdOutLine.empty())
115 {
116 stdOutput.emplace_back(stdOutLine);
117 }
118
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530119 execProg.wait();
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530120
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530121 int retCode = execProg.exit_code();
122 if (retCode)
123 {
Jonathan Domanccd28892021-10-14 16:43:33 -0700124 log<level::ERR>("Command execution failed", entry("PATH=%s", path),
125 entry("RETURN_CODE=%d", retCode));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530126 elog<InternalFailure>();
127 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530128
129 return stdOutput;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530130}
131
132static std::string getCSVFromVector(std::vector<std::string> vec)
133{
134 switch (vec.size())
135 {
136 case 0:
137 {
138 return "";
139 }
140 break;
141
142 case 1:
143 {
144 return std::string{vec[0]};
145 }
146 break;
147
148 default:
149 {
150 return std::accumulate(
151 std::next(vec.begin()), vec.end(), vec[0],
152 [](std::string a, std::string b) { return a + ',' + b; });
153 }
154 }
155}
156
Patrick Williams9638afb2021-02-22 17:16:24 -0600157static bool removeStringFromCSV(std::string& csvStr, const std::string& delStr)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530158{
159 std::string::size_type delStrPos = csvStr.find(delStr);
160 if (delStrPos != std::string::npos)
161 {
162 // need to also delete the comma char
163 if (delStrPos == 0)
164 {
165 csvStr.erase(delStrPos, delStr.size() + 1);
166 }
167 else
168 {
169 csvStr.erase(delStrPos - 1, delStr.size() + 1);
170 }
171 return true;
172 }
173 return false;
174}
175
Patrick Williams9638afb2021-02-22 17:16:24 -0600176bool UserMgr::isUserExist(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530177{
178 if (userName.empty())
179 {
180 log<level::ERR>("User name is empty");
181 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
182 Argument::ARGUMENT_VALUE("Null"));
183 }
184 if (usersList.find(userName) == usersList.end())
185 {
186 return false;
187 }
188 return true;
189}
190
Patrick Williams9638afb2021-02-22 17:16:24 -0600191void UserMgr::throwForUserDoesNotExist(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530192{
193 if (isUserExist(userName) == false)
194 {
195 log<level::ERR>("User does not exist",
196 entry("USER_NAME=%s", userName.c_str()));
197 elog<UserNameDoesNotExist>();
198 }
199}
200
Patrick Williams9638afb2021-02-22 17:16:24 -0600201void UserMgr::throwForUserExists(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530202{
203 if (isUserExist(userName) == true)
204 {
205 log<level::ERR>("User already exists",
206 entry("USER_NAME=%s", userName.c_str()));
207 elog<UserNameExists>();
208 }
209}
210
211void UserMgr::throwForUserNameConstraints(
Patrick Williams9638afb2021-02-22 17:16:24 -0600212 const std::string& userName, const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530213{
214 if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
215 groupNames.end())
216 {
217 if (userName.length() > ipmiMaxUserNameLen)
218 {
219 log<level::ERR>("IPMI user name length limitation",
220 entry("SIZE=%d", userName.length()));
221 elog<UserNameGroupFail>(
222 xyz::openbmc_project::User::Common::UserNameGroupFail::REASON(
223 "IPMI length"));
224 }
225 }
226 if (userName.length() > systemMaxUserNameLen)
227 {
228 log<level::ERR>("User name length limitation",
229 entry("SIZE=%d", userName.length()));
230 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
231 Argument::ARGUMENT_VALUE("Invalid length"));
232 }
233 if (!std::regex_match(userName.c_str(),
234 std::regex("[a-zA-z_][a-zA-Z_0-9]*")))
235 {
236 log<level::ERR>("Invalid user name",
237 entry("USER_NAME=%s", userName.c_str()));
238 elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
239 Argument::ARGUMENT_VALUE("Invalid data"));
240 }
241}
242
243void UserMgr::throwForMaxGrpUserCount(
Patrick Williams9638afb2021-02-22 17:16:24 -0600244 const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530245{
246 if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
247 groupNames.end())
248 {
249 if (getIpmiUsersCount() >= ipmiMaxUsers)
250 {
251 log<level::ERR>("IPMI user limit reached");
252 elog<NoResource>(
253 xyz::openbmc_project::User::Common::NoResource::REASON(
254 "ipmi user count reached"));
255 }
256 }
257 else
258 {
259 if (usersList.size() > 0 && (usersList.size() - getIpmiUsersCount()) >=
260 (maxSystemUsers - ipmiMaxUsers))
261 {
262 log<level::ERR>("Non-ipmi User limit reached");
263 elog<NoResource>(
264 xyz::openbmc_project::User::Common::NoResource::REASON(
265 "Non-ipmi user count reached"));
266 }
267 }
268 return;
269}
270
Patrick Williams9638afb2021-02-22 17:16:24 -0600271void UserMgr::throwForInvalidPrivilege(const std::string& priv)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530272{
273 if (!priv.empty() &&
274 (std::find(privMgr.begin(), privMgr.end(), priv) == privMgr.end()))
275 {
276 log<level::ERR>("Invalid privilege");
277 elog<InvalidArgument>(Argument::ARGUMENT_NAME("Privilege"),
278 Argument::ARGUMENT_VALUE(priv.c_str()));
279 }
280}
281
Patrick Williams9638afb2021-02-22 17:16:24 -0600282void UserMgr::throwForInvalidGroups(const std::vector<std::string>& groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530283{
Patrick Williams9638afb2021-02-22 17:16:24 -0600284 for (auto& group : groupNames)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530285 {
286 if (std::find(groupsMgr.begin(), groupsMgr.end(), group) ==
287 groupsMgr.end())
288 {
289 log<level::ERR>("Invalid Group Name listed");
290 elog<InvalidArgument>(Argument::ARGUMENT_NAME("GroupName"),
291 Argument::ARGUMENT_VALUE(group.c_str()));
292 }
293 }
294}
295
296void UserMgr::createUser(std::string userName,
297 std::vector<std::string> groupNames, std::string priv,
298 bool enabled)
299{
300 throwForInvalidPrivilege(priv);
301 throwForInvalidGroups(groupNames);
302 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500303 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530304 throwForUserExists(userName);
305 throwForUserNameConstraints(userName, groupNames);
306 throwForMaxGrpUserCount(groupNames);
307
308 std::string groups = getCSVFromVector(groupNames);
309 bool sshRequested = removeStringFromCSV(groups, grpSsh);
310
311 // treat privilege as a group - This is to avoid using different file to
312 // store the same.
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530313 if (!priv.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530314 {
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530315 if (groups.size() != 0)
316 {
317 groups += ",";
318 }
319 groups += priv;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530320 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530321 try
322 {
Jiaqing Zhaoce89bfc2021-12-02 21:26:01 +0800323 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
324 // 1970-01-01, that's an implementation-defined behavior
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530325 executeCmd("/usr/sbin/useradd", userName.c_str(), "-G", groups.c_str(),
Richard Marian Thomaiyarf977b1a2018-07-16 23:50:51 +0530326 "-m", "-N", "-s",
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530327 (sshRequested ? "/bin/sh" : "/bin/nologin"), "-e",
Jiaqing Zhaoce89bfc2021-12-02 21:26:01 +0800328 (enabled ? "" : "1970-01-01"));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530329 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600330 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530331 {
332 log<level::ERR>("Unable to create new user");
333 elog<InternalFailure>();
334 }
335
336 // Add the users object before sending out the signal
337 std::string userObj = std::string(usersObjPath) + "/" + userName;
338 std::sort(groupNames.begin(), groupNames.end());
339 usersList.emplace(
340 userName, std::move(std::make_unique<phosphor::user::Users>(
341 bus, userObj.c_str(), groupNames, priv, enabled, *this)));
342
343 log<level::INFO>("User created successfully",
344 entry("USER_NAME=%s", userName.c_str()));
345 return;
346}
347
348void UserMgr::deleteUser(std::string userName)
349{
350 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500351 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530352 throwForUserDoesNotExist(userName);
353 try
354 {
Richard Marian Thomaiyarf977b1a2018-07-16 23:50:51 +0530355 executeCmd("/usr/sbin/userdel", userName.c_str(), "-r");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530356 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600357 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530358 {
359 log<level::ERR>("User delete failed",
360 entry("USER_NAME=%s", userName.c_str()));
361 elog<InternalFailure>();
362 }
363
364 usersList.erase(userName);
365
366 log<level::INFO>("User deleted successfully",
367 entry("USER_NAME=%s", userName.c_str()));
368 return;
369}
370
371void UserMgr::renameUser(std::string userName, std::string newUserName)
372{
373 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500374 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530375 throwForUserDoesNotExist(userName);
376 throwForUserExists(newUserName);
377 throwForUserNameConstraints(newUserName,
378 usersList[userName].get()->userGroups());
379 try
380 {
Richard Marian Thomaiyarf977b1a2018-07-16 23:50:51 +0530381 std::string newHomeDir = "/home/" + newUserName;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530382 executeCmd("/usr/sbin/usermod", "-l", newUserName.c_str(),
Richard Marian Thomaiyarf977b1a2018-07-16 23:50:51 +0530383 userName.c_str(), "-d", newHomeDir.c_str(), "-m");
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530384 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600385 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530386 {
387 log<level::ERR>("User rename failed",
388 entry("USER_NAME=%s", userName.c_str()));
389 elog<InternalFailure>();
390 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600391 const auto& user = usersList[userName];
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530392 std::string priv = user.get()->userPrivilege();
393 std::vector<std::string> groupNames = user.get()->userGroups();
394 bool enabled = user.get()->userEnabled();
395 std::string newUserObj = std::string(usersObjPath) + "/" + newUserName;
396 // Special group 'ipmi' needs a way to identify user renamed, in order to
397 // update encrypted password. It can't rely only on InterfacesRemoved &
398 // InterfacesAdded. So first send out userRenamed signal.
399 this->userRenamed(userName, newUserName);
400 usersList.erase(userName);
401 usersList.emplace(
402 newUserName,
403 std::move(std::make_unique<phosphor::user::Users>(
404 bus, newUserObj.c_str(), groupNames, priv, enabled, *this)));
405 return;
406}
407
Patrick Williams9638afb2021-02-22 17:16:24 -0600408void UserMgr::updateGroupsAndPriv(const std::string& userName,
409 const std::vector<std::string>& groupNames,
410 const std::string& priv)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530411{
412 throwForInvalidPrivilege(priv);
413 throwForInvalidGroups(groupNames);
414 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500415 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530416 throwForUserDoesNotExist(userName);
Patrick Williams9638afb2021-02-22 17:16:24 -0600417 const std::vector<std::string>& oldGroupNames =
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530418 usersList[userName].get()->userGroups();
419 std::vector<std::string> groupDiff;
420 // Note: already dealing with sorted group lists.
421 std::set_symmetric_difference(oldGroupNames.begin(), oldGroupNames.end(),
422 groupNames.begin(), groupNames.end(),
423 std::back_inserter(groupDiff));
424 if (std::find(groupDiff.begin(), groupDiff.end(), "ipmi") !=
425 groupDiff.end())
426 {
427 throwForUserNameConstraints(userName, groupNames);
428 throwForMaxGrpUserCount(groupNames);
429 }
430
431 std::string groups = getCSVFromVector(groupNames);
432 bool sshRequested = removeStringFromCSV(groups, grpSsh);
433
434 // treat privilege as a group - This is to avoid using different file to
435 // store the same.
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530436 if (!priv.empty())
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530437 {
Richard Marian Thomaiyar2cb2e722018-09-27 14:22:42 +0530438 if (groups.size() != 0)
439 {
440 groups += ",";
441 }
442 groups += priv;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530443 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530444 try
445 {
446 executeCmd("/usr/sbin/usermod", userName.c_str(), "-G", groups.c_str(),
447 "-s", (sshRequested ? "/bin/sh" : "/bin/nologin"));
448 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600449 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530450 {
451 log<level::ERR>("Unable to modify user privilege / groups");
452 elog<InternalFailure>();
453 }
454
455 log<level::INFO>("User groups / privilege updated successfully",
456 entry("USER_NAME=%s", userName.c_str()));
457 return;
458}
459
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530460uint8_t UserMgr::minPasswordLength(uint8_t value)
461{
462 if (value == AccountPolicyIface::minPasswordLength())
463 {
464 return value;
465 }
466 if (value < minPasswdLength)
467 {
468 return value;
469 }
470 if (setPamModuleArgValue(pamCrackLib, minPasswdLenProp,
471 std::to_string(value)) != success)
472 {
473 log<level::ERR>("Unable to set minPasswordLength");
474 elog<InternalFailure>();
475 }
476 return AccountPolicyIface::minPasswordLength(value);
477}
478
479uint8_t UserMgr::rememberOldPasswordTimes(uint8_t value)
480{
481 if (value == AccountPolicyIface::rememberOldPasswordTimes())
482 {
483 return value;
484 }
485 if (setPamModuleArgValue(pamPWHistory, remOldPasswdCount,
486 std::to_string(value)) != success)
487 {
488 log<level::ERR>("Unable to set rememberOldPasswordTimes");
489 elog<InternalFailure>();
490 }
491 return AccountPolicyIface::rememberOldPasswordTimes(value);
492}
493
494uint16_t UserMgr::maxLoginAttemptBeforeLockout(uint16_t value)
495{
496 if (value == AccountPolicyIface::maxLoginAttemptBeforeLockout())
497 {
498 return value;
499 }
500 if (setPamModuleArgValue(pamTally2, maxFailedAttempt,
501 std::to_string(value)) != success)
502 {
503 log<level::ERR>("Unable to set maxLoginAttemptBeforeLockout");
504 elog<InternalFailure>();
505 }
506 return AccountPolicyIface::maxLoginAttemptBeforeLockout(value);
507}
508
509uint32_t UserMgr::accountUnlockTimeout(uint32_t value)
510{
511 if (value == AccountPolicyIface::accountUnlockTimeout())
512 {
513 return value;
514 }
515 if (setPamModuleArgValue(pamTally2, unlockTimeout, std::to_string(value)) !=
516 success)
517 {
518 log<level::ERR>("Unable to set accountUnlockTimeout");
519 elog<InternalFailure>();
520 }
521 return AccountPolicyIface::accountUnlockTimeout(value);
522}
523
Patrick Williams9638afb2021-02-22 17:16:24 -0600524int UserMgr::getPamModuleArgValue(const std::string& moduleName,
525 const std::string& argName,
526 std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530527{
528 std::string fileName;
529 if (moduleName == pamTally2)
530 {
531 fileName = pamAuthConfigFile;
532 }
533 else
534 {
535 fileName = pamPasswdConfigFile;
536 }
537 std::ifstream fileToRead(fileName, std::ios::in);
538 if (!fileToRead.is_open())
539 {
540 log<level::ERR>("Failed to open pam configuration file",
541 entry("FILE_NAME=%s", fileName.c_str()));
542 return failure;
543 }
544 std::string line;
545 auto argSearch = argName + "=";
546 size_t startPos = 0;
547 size_t endPos = 0;
548 while (getline(fileToRead, line))
549 {
550 // skip comments section starting with #
551 if ((startPos = line.find('#')) != std::string::npos)
552 {
553 if (startPos == 0)
554 {
555 continue;
556 }
557 // skip comments after meaningful section and process those
558 line = line.substr(0, startPos);
559 }
560 if (line.find(moduleName) != std::string::npos)
561 {
562 if ((startPos = line.find(argSearch)) != std::string::npos)
563 {
564 if ((endPos = line.find(' ', startPos)) == std::string::npos)
565 {
566 endPos = line.size();
567 }
568 startPos += argSearch.size();
569 argValue = line.substr(startPos, endPos - startPos);
570 return success;
571 }
572 }
573 }
574 return failure;
575}
576
Patrick Williams9638afb2021-02-22 17:16:24 -0600577int UserMgr::setPamModuleArgValue(const std::string& moduleName,
578 const std::string& argName,
579 const std::string& argValue)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +0530580{
581 std::string fileName;
582 if (moduleName == pamTally2)
583 {
584 fileName = pamAuthConfigFile;
585 }
586 else
587 {
588 fileName = pamPasswdConfigFile;
589 }
590 std::string tmpFileName = fileName + "_tmp";
591 std::ifstream fileToRead(fileName, std::ios::in);
592 std::ofstream fileToWrite(tmpFileName, std::ios::out);
593 if (!fileToRead.is_open() || !fileToWrite.is_open())
594 {
595 log<level::ERR>("Failed to open pam configuration /tmp file",
596 entry("FILE_NAME=%s", fileName.c_str()));
597 return failure;
598 }
599 std::string line;
600 auto argSearch = argName + "=";
601 size_t startPos = 0;
602 size_t endPos = 0;
603 bool found = false;
604 while (getline(fileToRead, line))
605 {
606 // skip comments section starting with #
607 if ((startPos = line.find('#')) != std::string::npos)
608 {
609 if (startPos == 0)
610 {
611 fileToWrite << line << std::endl;
612 continue;
613 }
614 // skip comments after meaningful section and process those
615 line = line.substr(0, startPos);
616 }
617 if (line.find(moduleName) != std::string::npos)
618 {
619 if ((startPos = line.find(argSearch)) != std::string::npos)
620 {
621 if ((endPos = line.find(' ', startPos)) == std::string::npos)
622 {
623 endPos = line.size();
624 }
625 startPos += argSearch.size();
626 fileToWrite << line.substr(0, startPos) << argValue
627 << line.substr(endPos, line.size() - endPos)
628 << std::endl;
629 found = true;
630 continue;
631 }
632 }
633 fileToWrite << line << std::endl;
634 }
635 fileToWrite.close();
636 fileToRead.close();
637 if (found)
638 {
639 if (std::rename(tmpFileName.c_str(), fileName.c_str()) == 0)
640 {
641 return success;
642 }
643 }
644 return failure;
645}
646
Patrick Williams9638afb2021-02-22 17:16:24 -0600647void UserMgr::userEnable(const std::string& userName, bool enabled)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530648{
649 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500650 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530651 throwForUserDoesNotExist(userName);
652 try
653 {
Jiaqing Zhaoce89bfc2021-12-02 21:26:01 +0800654 // set EXPIRE_DATE to 0 to disable user, PAM takes 0 as expire on
655 // 1970-01-01, that's an implementation-defined behavior
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530656 executeCmd("/usr/sbin/usermod", userName.c_str(), "-e",
Jiaqing Zhaoce89bfc2021-12-02 21:26:01 +0800657 (enabled ? "" : "1970-01-01"));
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530658 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600659 catch (const InternalFailure& e)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530660 {
661 log<level::ERR>("Unable to modify user enabled state");
662 elog<InternalFailure>();
663 }
664
665 log<level::INFO>("User enabled/disabled state updated successfully",
666 entry("USER_NAME=%s", userName.c_str()),
667 entry("ENABLED=%d", enabled));
668 return;
669}
670
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530671/**
672 * pam_tally2 app will provide the user failure count and failure status
673 * in second line of output with words position [0] - user name,
674 * [1] - failure count, [2] - latest timestamp, [3] - failure timestamp
675 * [4] - failure app
676 **/
677
678static constexpr size_t t2UserIdx = 0;
679static constexpr size_t t2FailCntIdx = 1;
680static constexpr size_t t2OutputIndex = 1;
681
Patrick Williams9638afb2021-02-22 17:16:24 -0600682bool UserMgr::userLockedForFailedAttempt(const std::string& userName)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530683{
684 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500685 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530686 std::vector<std::string> output;
687
688 output = executeCmd("/usr/sbin/pam_tally2", "-u", userName.c_str());
689
690 std::vector<std::string> splitWords;
691 boost::algorithm::split(splitWords, output[t2OutputIndex],
692 boost::algorithm::is_any_of("\t "),
693 boost::token_compress_on);
694
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530695 try
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530696 {
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530697 unsigned long tmp = std::stoul(splitWords[t2FailCntIdx], nullptr);
698 uint16_t value16 = 0;
699 if (tmp > std::numeric_limits<decltype(value16)>::max())
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530700 {
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530701 throw std::out_of_range("Out of range");
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530702 }
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530703 value16 = static_cast<decltype(value16)>(tmp);
704 if (AccountPolicyIface::maxLoginAttemptBeforeLockout() != 0 &&
705 value16 >= AccountPolicyIface::maxLoginAttemptBeforeLockout())
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530706 {
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530707 return true; // User account is locked out
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530708 }
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530709 return false; // User account is un-locked
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530710 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600711 catch (const std::exception& e)
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530712 {
713 log<level::ERR>("Exception for userLockedForFailedAttempt",
714 entry("WHAT=%s", e.what()));
715 throw;
716 }
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530717}
718
Patrick Williams9638afb2021-02-22 17:16:24 -0600719bool UserMgr::userLockedForFailedAttempt(const std::string& userName,
720 const bool& value)
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530721{
722 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500723 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530724 std::vector<std::string> output;
725 if (value == true)
726 {
727 return userLockedForFailedAttempt(userName);
728 }
729 output = executeCmd("/usr/sbin/pam_tally2", "-u", userName.c_str(), "-r");
730
731 std::vector<std::string> splitWords;
732 boost::algorithm::split(splitWords, output[t2OutputIndex],
733 boost::algorithm::is_any_of("\t "),
734 boost::token_compress_on);
735
Richard Marian Thomaiyarf5c2df52018-11-22 23:24:25 +0530736 return userLockedForFailedAttempt(userName);
Richard Marian Thomaiyarc7045192018-06-13 16:51:00 +0530737}
738
Patrick Williams9638afb2021-02-22 17:16:24 -0600739bool UserMgr::userPasswordExpired(const std::string& userName)
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600740{
741 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500742 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600743
744 struct spwd spwd
Patrick Williams9638afb2021-02-22 17:16:24 -0600745 {};
746 struct spwd* spwdPtr = nullptr;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600747 auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
748 if (buflen < -1)
749 {
750 // Use a default size if there is no hard limit suggested by sysconf()
751 buflen = 1024;
752 }
753 std::vector<char> buffer(buflen);
754 auto status =
755 getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen, &spwdPtr);
756 // On success, getspnam_r() returns zero, and sets *spwdPtr to spwd.
757 // If no matching password record was found, these functions return 0
758 // and store NULL in *spwdPtr
759 if ((status == 0) && (&spwd == spwdPtr))
760 {
761 // Determine password validity per "chage" docs, where:
762 // spwd.sp_lstchg == 0 means password is expired, and
763 // spwd.sp_max == -1 means the password does not expire.
764 constexpr long seconds_per_day = 60 * 60 * 24;
765 long today = static_cast<long>(time(NULL)) / seconds_per_day;
766 if ((spwd.sp_lstchg == 0) ||
767 ((spwd.sp_max != -1) && ((spwd.sp_max + spwd.sp_lstchg) < today)))
768 {
769 return true;
770 }
771 }
772 else
773 {
Jayaprakash Mutyala75be4e62020-09-18 15:59:06 +0000774 // User entry is missing in /etc/shadow, indicating no SHA password.
775 // Treat this as new user without password entry in /etc/shadow
776 // TODO: Add property to indicate user password was not set yet
777 // https://github.com/openbmc/phosphor-user-manager/issues/8
778 return false;
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -0600779 }
780
781 return false;
782}
783
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530784UserSSHLists UserMgr::getUserAndSshGrpList()
785{
786 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500787 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530788
789 std::vector<std::string> userList;
790 std::vector<std::string> sshUsersList;
791 struct passwd pw, *pwp = nullptr;
792 std::array<char, 1024> buffer{};
793
794 phosphor::user::File passwd(passwdFileName, "r");
795 if ((passwd)() == NULL)
796 {
797 log<level::ERR>("Error opening the passwd file");
798 elog<InternalFailure>();
799 }
800
801 while (true)
802 {
803 auto r = fgetpwent_r((passwd)(), &pw, buffer.data(), buffer.max_size(),
804 &pwp);
805 if ((r != 0) || (pwp == NULL))
806 {
807 // Any error, break the loop.
808 break;
809 }
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +0530810#ifdef ENABLE_ROOT_USER_MGMT
Richard Marian Thomaiyar7ba3c712018-07-31 13:41:36 +0530811 // Add all users whose UID >= 1000 and < 65534
812 // and special UID 0.
813 if ((pwp->pw_uid == 0) ||
814 ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534)))
Richard Marian Thomaiyard4d65502019-11-02 21:02:03 +0530815#else
816 // Add all users whose UID >=1000 and < 65534
817 if ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534))
818#endif
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530819 {
820 std::string userName(pwp->pw_name);
821 userList.emplace_back(userName);
822
823 // ssh doesn't have separate group. Check login shell entry to
824 // get all users list which are member of ssh group.
825 std::string loginShell(pwp->pw_shell);
826 if (loginShell == "/bin/sh")
827 {
828 sshUsersList.emplace_back(userName);
829 }
830 }
831 }
832 endpwent();
833 return std::make_pair(std::move(userList), std::move(sshUsersList));
834}
835
836size_t UserMgr::getIpmiUsersCount()
837{
838 std::vector<std::string> userList = getUsersInGroup("ipmi");
839 return userList.size();
840}
841
Patrick Williams9638afb2021-02-22 17:16:24 -0600842bool UserMgr::isUserEnabled(const std::string& userName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530843{
844 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -0500845 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530846 std::array<char, 4096> buffer{};
847 struct spwd spwd;
Patrick Williams9638afb2021-02-22 17:16:24 -0600848 struct spwd* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530849 int status = getspnam_r(userName.c_str(), &spwd, buffer.data(),
850 buffer.max_size(), &resultPtr);
851 if (!status && (&spwd == resultPtr))
852 {
853 if (resultPtr->sp_expire >= 0)
854 {
855 return false; // user locked out
856 }
857 return true;
858 }
859 return false; // assume user is disabled for any error.
860}
861
Patrick Williams9638afb2021-02-22 17:16:24 -0600862std::vector<std::string> UserMgr::getUsersInGroup(const std::string& groupName)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530863{
864 std::vector<std::string> usersInGroup;
865 // Should be more than enough to get the pwd structure.
866 std::array<char, 4096> buffer{};
867 struct group grp;
Patrick Williams9638afb2021-02-22 17:16:24 -0600868 struct group* resultPtr = nullptr;
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +0530869
870 int status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
871 buffer.max_size(), &resultPtr);
872
873 if (!status && (&grp == resultPtr))
874 {
875 for (; *(grp.gr_mem) != NULL; ++(grp.gr_mem))
876 {
877 usersInGroup.emplace_back(*(grp.gr_mem));
878 }
879 }
880 else
881 {
882 log<level::ERR>("Group not found",
883 entry("GROUP=%s", groupName.c_str()));
884 // Don't throw error, just return empty userList - fallback
885 }
886 return usersInGroup;
887}
888
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600889DbusUserObj UserMgr::getPrivilegeMapperObject(void)
890{
891 DbusUserObj objects;
892 try
893 {
Ravi Teja5fe724a2019-05-07 05:14:42 -0500894 std::string basePath = "/xyz/openbmc_project/user/ldap/openldap";
895 std::string interface = "xyz.openbmc_project.User.Ldap.Config";
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600896
897 auto ldapMgmtService =
898 getServiceName(std::move(basePath), std::move(interface));
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600899 auto method = bus.new_method_call(
900 ldapMgmtService.c_str(), ldapMgrObjBasePath,
901 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
902
903 auto reply = bus.call(method);
904 reply.read(objects);
905 }
Patrick Williams9638afb2021-02-22 17:16:24 -0600906 catch (const InternalFailure& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600907 {
908 log<level::ERR>("Unable to get the User Service",
909 entry("WHAT=%s", e.what()));
910 throw;
911 }
Patrick Williams178c3f62021-09-02 09:50:31 -0500912 catch (const sdbusplus::exception::exception& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600913 {
914 log<level::ERR>(
915 "Failed to excute method", entry("METHOD=%s", "GetManagedObjects"),
916 entry("PATH=%s", ldapMgrObjBasePath), entry("WHAT=%s", e.what()));
917 throw;
918 }
919 return objects;
920}
921
Patrick Williams9638afb2021-02-22 17:16:24 -0600922std::string UserMgr::getLdapGroupName(const std::string& userName)
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600923{
924 struct passwd pwd
Patrick Williams9638afb2021-02-22 17:16:24 -0600925 {};
926 struct passwd* pwdPtr = nullptr;
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600927 auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
928 if (buflen < -1)
929 {
930 // Use a default size if there is no hard limit suggested by sysconf()
931 buflen = 1024;
932 }
933 std::vector<char> buffer(buflen);
934 gid_t gid = 0;
935
936 auto status =
937 getpwnam_r(userName.c_str(), &pwd, buffer.data(), buflen, &pwdPtr);
938 // On success, getpwnam_r() returns zero, and set *pwdPtr to pwd.
939 // If no matching password record was found, these functions return 0
940 // and store NULL in *pwdPtr
941 if (!status && (&pwd == pwdPtr))
942 {
943 gid = pwd.pw_gid;
944 }
945 else
946 {
947 log<level::ERR>("User does not exist",
948 entry("USER_NAME=%s", userName.c_str()));
949 elog<UserNameDoesNotExist>();
950 }
951
Patrick Williams9638afb2021-02-22 17:16:24 -0600952 struct group* groups = nullptr;
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600953 std::string ldapGroupName;
954
955 while ((groups = getgrent()) != NULL)
956 {
957 if (groups->gr_gid == gid)
958 {
959 ldapGroupName = groups->gr_name;
960 break;
961 }
962 }
963 // Call endgrent() to close the group database.
964 endgrent();
965
966 return ldapGroupName;
967}
968
Patrick Williams9638afb2021-02-22 17:16:24 -0600969std::string UserMgr::getServiceName(std::string&& path, std::string&& intf)
Ratan Guptaaeaf9412019-02-11 04:41:52 -0600970{
971 auto mapperCall = bus.new_method_call(objMapperService, objMapperPath,
972 objMapperInterface, "GetObject");
973
974 mapperCall.append(std::move(path));
975 mapperCall.append(std::vector<std::string>({std::move(intf)}));
976
977 auto mapperResponseMsg = bus.call(mapperCall);
978
979 if (mapperResponseMsg.is_method_error())
980 {
981 log<level::ERR>("Error in mapper call");
982 elog<InternalFailure>();
983 }
984
985 std::map<std::string, std::vector<std::string>> mapperResponse;
986 mapperResponseMsg.read(mapperResponse);
987
988 if (mapperResponse.begin() == mapperResponse.end())
989 {
990 log<level::ERR>("Invalid response from mapper");
991 elog<InternalFailure>();
992 }
993
994 return mapperResponse.begin()->first;
995}
996
997UserInfoMap UserMgr::getUserInfo(std::string userName)
998{
999 UserInfoMap userInfo;
1000 // Check whether the given user is local user or not.
1001 if (isUserExist(userName) == true)
1002 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001003 const auto& user = usersList[userName];
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001004 userInfo.emplace("UserPrivilege", user.get()->userPrivilege());
1005 userInfo.emplace("UserGroups", user.get()->userGroups());
1006 userInfo.emplace("UserEnabled", user.get()->userEnabled());
1007 userInfo.emplace("UserLockedForFailedAttempt",
1008 user.get()->userLockedForFailedAttempt());
Joseph Reynolds3ab6cc22020-03-03 14:09:03 -06001009 userInfo.emplace("UserPasswordExpired",
1010 user.get()->userPasswordExpired());
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001011 userInfo.emplace("RemoteUser", false);
1012 }
1013 else
1014 {
1015 std::string ldapGroupName = getLdapGroupName(userName);
1016 if (ldapGroupName.empty())
1017 {
1018 log<level::ERR>("Unable to get group name",
1019 entry("USER_NAME=%s", userName.c_str()));
1020 elog<InternalFailure>();
1021 }
1022
1023 DbusUserObj objects = getPrivilegeMapperObject();
1024
1025 std::string privilege;
1026 std::string groupName;
Ravi Teja5fe724a2019-05-07 05:14:42 -05001027 std::string ldapConfigPath;
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001028
1029 try
1030 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001031 for (const auto& obj : objects)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001032 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001033 for (const auto& interface : obj.second)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001034 {
Ravi Teja5fe724a2019-05-07 05:14:42 -05001035 if ((interface.first ==
1036 "xyz.openbmc_project.Object.Enable"))
1037 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001038 for (const auto& property : interface.second)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001039 {
Patrick Williams8f8fc232020-05-13 12:25:51 -05001040 auto value = std::get<bool>(property.second);
Ravi Teja5fe724a2019-05-07 05:14:42 -05001041 if ((property.first == "Enabled") &&
1042 (value == true))
1043 {
1044 ldapConfigPath = obj.first;
1045 break;
1046 }
1047 }
1048 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001049 }
Ravi Teja5fe724a2019-05-07 05:14:42 -05001050 if (!ldapConfigPath.empty())
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001051 {
Ravi Teja5fe724a2019-05-07 05:14:42 -05001052 break;
1053 }
1054 }
1055
1056 if (ldapConfigPath.empty())
1057 {
1058 return userInfo;
1059 }
1060
Patrick Williams9638afb2021-02-22 17:16:24 -06001061 for (const auto& obj : objects)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001062 {
Patrick Williams9638afb2021-02-22 17:16:24 -06001063 for (const auto& interface : obj.second)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001064 {
1065 if ((interface.first ==
1066 "xyz.openbmc_project.User.PrivilegeMapperEntry") &&
1067 (obj.first.str.find(ldapConfigPath) !=
1068 std::string::npos))
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001069 {
Ravi Teja5fe724a2019-05-07 05:14:42 -05001070
Patrick Williams9638afb2021-02-22 17:16:24 -06001071 for (const auto& property : interface.second)
Ravi Teja5fe724a2019-05-07 05:14:42 -05001072 {
Patrick Williams8f8fc232020-05-13 12:25:51 -05001073 auto value = std::get<std::string>(property.second);
Ravi Teja5fe724a2019-05-07 05:14:42 -05001074 if (property.first == "GroupName")
1075 {
1076 groupName = value;
1077 }
1078 else if (property.first == "Privilege")
1079 {
1080 privilege = value;
1081 }
1082 if (groupName == ldapGroupName)
1083 {
1084 userInfo["UserPrivilege"] = privilege;
1085 }
1086 }
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001087 }
1088 }
1089 }
1090 auto priv = std::get<std::string>(userInfo["UserPrivilege"]);
Ravi Teja5fe724a2019-05-07 05:14:42 -05001091
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001092 if (priv.empty())
1093 {
1094 log<level::ERR>("LDAP group privilege mapping does not exist");
1095 }
1096 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001097 catch (const std::bad_variant_access& e)
Ratan Guptaaeaf9412019-02-11 04:41:52 -06001098 {
1099 log<level::ERR>("Error while accessing variant",
1100 entry("WHAT=%s", e.what()));
1101 elog<InternalFailure>();
1102 }
1103 userInfo.emplace("RemoteUser", true);
1104 }
1105
1106 return userInfo;
1107}
1108
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301109void UserMgr::initUserObjects(void)
1110{
1111 // All user management lock has to be based on /etc/shadow
Andrew Geisslera260f182021-05-14 12:20:12 -05001112 // TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301113 std::vector<std::string> userNameList;
1114 std::vector<std::string> sshGrpUsersList;
1115 UserSSHLists userSSHLists = getUserAndSshGrpList();
1116 userNameList = std::move(userSSHLists.first);
1117 sshGrpUsersList = std::move(userSSHLists.second);
1118
1119 if (!userNameList.empty())
1120 {
1121 std::map<std::string, std::vector<std::string>> groupLists;
Patrick Williams9638afb2021-02-22 17:16:24 -06001122 for (auto& grp : groupsMgr)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301123 {
1124 if (grp == grpSsh)
1125 {
1126 groupLists.emplace(grp, sshGrpUsersList);
1127 }
1128 else
1129 {
1130 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1131 groupLists.emplace(grp, grpUsersList);
1132 }
1133 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001134 for (auto& grp : privMgr)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301135 {
1136 std::vector<std::string> grpUsersList = getUsersInGroup(grp);
1137 groupLists.emplace(grp, grpUsersList);
1138 }
1139
Patrick Williams9638afb2021-02-22 17:16:24 -06001140 for (auto& user : userNameList)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301141 {
1142 std::vector<std::string> userGroups;
1143 std::string userPriv;
Patrick Williams9638afb2021-02-22 17:16:24 -06001144 for (const auto& grp : groupLists)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301145 {
1146 std::vector<std::string> tempGrp = grp.second;
1147 if (std::find(tempGrp.begin(), tempGrp.end(), user) !=
1148 tempGrp.end())
1149 {
1150 if (std::find(privMgr.begin(), privMgr.end(), grp.first) !=
1151 privMgr.end())
1152 {
1153 userPriv = grp.first;
1154 }
1155 else
1156 {
1157 userGroups.emplace_back(grp.first);
1158 }
1159 }
1160 }
1161 // Add user objects to the Users path.
1162 auto objPath = std::string(usersObjPath) + "/" + user;
1163 std::sort(userGroups.begin(), userGroups.end());
1164 usersList.emplace(user,
1165 std::move(std::make_unique<phosphor::user::Users>(
1166 bus, objPath.c_str(), userGroups, userPriv,
1167 isUserEnabled(user), *this)));
1168 }
1169 }
1170}
1171
Patrick Williams9638afb2021-02-22 17:16:24 -06001172UserMgr::UserMgr(sdbusplus::bus::bus& bus, const char* path) :
Ratan Gupta1af12232018-11-03 00:35:38 +05301173 Ifaces(bus, path, true), bus(bus), path(path)
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301174{
1175 UserMgrIface::allPrivileges(privMgr);
1176 std::sort(groupsMgr.begin(), groupsMgr.end());
1177 UserMgrIface::allGroups(groupsMgr);
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301178 std::string valueStr;
1179 auto value = minPasswdLength;
1180 unsigned long tmp = 0;
1181 if (getPamModuleArgValue(pamCrackLib, minPasswdLenProp, valueStr) !=
1182 success)
1183 {
1184 AccountPolicyIface::minPasswordLength(minPasswdLength);
1185 }
1186 else
1187 {
1188 try
1189 {
1190 tmp = std::stoul(valueStr, nullptr);
1191 if (tmp > std::numeric_limits<decltype(value)>::max())
1192 {
1193 throw std::out_of_range("Out of range");
1194 }
1195 value = static_cast<decltype(value)>(tmp);
1196 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001197 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301198 {
1199 log<level::ERR>("Exception for MinPasswordLength",
1200 entry("WHAT=%s", e.what()));
Patrick Venture045b1122018-10-16 15:59:29 -07001201 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301202 }
1203 AccountPolicyIface::minPasswordLength(value);
1204 }
1205 valueStr.clear();
1206 if (getPamModuleArgValue(pamPWHistory, remOldPasswdCount, valueStr) !=
1207 success)
1208 {
1209 AccountPolicyIface::rememberOldPasswordTimes(0);
1210 }
1211 else
1212 {
1213 value = 0;
1214 try
1215 {
1216 tmp = std::stoul(valueStr, nullptr);
1217 if (tmp > std::numeric_limits<decltype(value)>::max())
1218 {
1219 throw std::out_of_range("Out of range");
1220 }
1221 value = static_cast<decltype(value)>(tmp);
1222 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001223 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301224 {
1225 log<level::ERR>("Exception for RememberOldPasswordTimes",
1226 entry("WHAT=%s", e.what()));
Patrick Venture045b1122018-10-16 15:59:29 -07001227 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301228 }
1229 AccountPolicyIface::rememberOldPasswordTimes(value);
1230 }
1231 valueStr.clear();
1232 if (getPamModuleArgValue(pamTally2, maxFailedAttempt, valueStr) != success)
1233 {
1234 AccountPolicyIface::maxLoginAttemptBeforeLockout(0);
1235 }
1236 else
1237 {
1238 uint16_t value16 = 0;
1239 try
1240 {
1241 tmp = std::stoul(valueStr, nullptr);
1242 if (tmp > std::numeric_limits<decltype(value16)>::max())
1243 {
1244 throw std::out_of_range("Out of range");
1245 }
1246 value16 = static_cast<decltype(value16)>(tmp);
1247 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001248 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301249 {
1250 log<level::ERR>("Exception for MaxLoginAttemptBeforLockout",
1251 entry("WHAT=%s", e.what()));
Patrick Venture045b1122018-10-16 15:59:29 -07001252 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301253 }
1254 AccountPolicyIface::maxLoginAttemptBeforeLockout(value16);
1255 }
1256 valueStr.clear();
1257 if (getPamModuleArgValue(pamTally2, unlockTimeout, valueStr) != success)
1258 {
1259 AccountPolicyIface::accountUnlockTimeout(0);
1260 }
1261 else
1262 {
1263 uint32_t value32 = 0;
1264 try
1265 {
1266 tmp = std::stoul(valueStr, nullptr);
1267 if (tmp > std::numeric_limits<decltype(value32)>::max())
1268 {
1269 throw std::out_of_range("Out of range");
1270 }
1271 value32 = static_cast<decltype(value32)>(tmp);
1272 }
Patrick Williams9638afb2021-02-22 17:16:24 -06001273 catch (const std::exception& e)
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301274 {
1275 log<level::ERR>("Exception for AccountUnlockTimeout",
1276 entry("WHAT=%s", e.what()));
Patrick Venture045b1122018-10-16 15:59:29 -07001277 throw;
Richard Marian Thomaiyar9164fd92018-06-13 16:51:00 +05301278 }
1279 AccountPolicyIface::accountUnlockTimeout(value32);
1280 }
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301281 initUserObjects();
Ratan Gupta1af12232018-11-03 00:35:38 +05301282
1283 // emit the signal
1284 this->emit_object_added();
Richard Marian Thomaiyar9f630d92018-05-24 10:49:10 +05301285}
1286
1287} // namespace user
1288} // namespace phosphor