-
Notifications
You must be signed in to change notification settings - Fork 12
/
user_mgr.cpp
1405 lines (1303 loc) · 45.9 KB
/
user_mgr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include "config.h"
#include "user_mgr.hpp"
#include "file.hpp"
#include "shadowlock.hpp"
#include "users.hpp"
#include <grp.h>
#include <pwd.h>
#include <shadow.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/process/child.hpp>
#include <boost/process/io.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/Common/error.hpp>
#include <xyz/openbmc_project/User/Common/error.hpp>
#include <algorithm>
#include <fstream>
#include <numeric>
#include <regex>
namespace phosphor
{
namespace user
{
static constexpr const char* passwdFileName = "/etc/passwd";
static constexpr size_t ipmiMaxUsers = 15;
static constexpr size_t ipmiMaxUserNameLen = 16;
static constexpr size_t systemMaxUserNameLen = 30;
static constexpr size_t maxSystemUsers = 30;
static constexpr const char* grpSsh = "ssh";
static constexpr uint8_t minPasswdLength = 8;
static constexpr int success = 0;
static constexpr int failure = -1;
// pam modules related
static constexpr const char* pamFaillock = "pam_faillock.so";
static constexpr const char* pamPWQuality = "pam_pwquality.so";
static constexpr const char* pamPWHistory = "pam_pwhistory.so";
static constexpr const char* minPasswdLenProp = "minlen";
static constexpr const char* remOldPasswdCount = "remember";
static constexpr const char* maxFailedAttempt = "deny";
static constexpr const char* unlockTimeout = "unlock_time";
static constexpr const char* pamPasswdConfigFile = "/etc/pam.d/common-password";
static constexpr const char* faillockConfigFile = "/etc/security/faillock.conf";
static constexpr const char* pwQualityConfigFile =
"/etc/security/pwquality.conf";
// Object Manager related
static constexpr const char* ldapMgrObjBasePath =
"/xyz/openbmc_project/user/ldap";
// Object Mapper related
static constexpr const char* objMapperService =
"xyz.openbmc_project.ObjectMapper";
static constexpr const char* objMapperPath =
"/xyz/openbmc_project/object_mapper";
static constexpr const char* objMapperInterface =
"xyz.openbmc_project.ObjectMapper";
using namespace phosphor::logging;
using InsufficientPermission =
sdbusplus::xyz::openbmc_project::Common::Error::InsufficientPermission;
using InternalFailure =
sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
using InvalidArgument =
sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
using UserNameExists =
sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameExists;
using UserNameDoesNotExist =
sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameDoesNotExist;
using UserNameGroupFail =
sdbusplus::xyz::openbmc_project::User::Common::Error::UserNameGroupFail;
using NoResource =
sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
using Argument = xyz::openbmc_project::Common::InvalidArgument;
template <typename... ArgTypes>
static std::vector<std::string> executeCmd(const char* path,
ArgTypes&&... tArgs)
{
std::vector<std::string> stdOutput;
boost::process::ipstream stdOutStream;
boost::process::child execProg(path, const_cast<char*>(tArgs)...,
boost::process::std_out > stdOutStream);
std::string stdOutLine;
while (stdOutStream && std::getline(stdOutStream, stdOutLine) &&
!stdOutLine.empty())
{
stdOutput.emplace_back(stdOutLine);
}
execProg.wait();
int retCode = execProg.exit_code();
if (retCode)
{
log<level::ERR>("Command execution failed", entry("PATH=%d", path),
entry("RETURN_CODE:%d", retCode));
elog<InternalFailure>();
}
return stdOutput;
}
static std::string getCSVFromVector(std::vector<std::string> vec)
{
switch (vec.size())
{
case 0:
{
return "";
}
break;
case 1:
{
return std::string{vec[0]};
}
break;
default:
{
return std::accumulate(
std::next(vec.begin()), vec.end(), vec[0],
[](std::string a, std::string b) { return a + ',' + b; });
}
}
}
static bool removeStringFromCSV(std::string& csvStr, const std::string& delStr)
{
std::string::size_type delStrPos = csvStr.find(delStr);
if (delStrPos != std::string::npos)
{
// need to also delete the comma char
if (delStrPos == 0)
{
csvStr.erase(delStrPos, delStr.size() + 1);
}
else
{
csvStr.erase(delStrPos - 1, delStr.size() + 1);
}
return true;
}
return false;
}
bool UserMgr::isUserExist(const std::string& userName)
{
if (userName.empty())
{
log<level::ERR>("User name is empty");
elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
Argument::ARGUMENT_VALUE("Null"));
}
if (usersList.find(userName) == usersList.end())
{
return false;
}
return true;
}
void UserMgr::throwForUserDoesNotExist(const std::string& userName)
{
if (isUserExist(userName) == false)
{
log<level::ERR>("User does not exist",
entry("USER_NAME=%s", userName.c_str()));
elog<UserNameDoesNotExist>();
}
}
void UserMgr::throwForUserExists(const std::string& userName)
{
if (isUserExist(userName) == true)
{
log<level::ERR>("User already exists",
entry("USER_NAME=%s", userName.c_str()));
elog<UserNameExists>();
}
}
void UserMgr::throwForUserNameConstraints(
const std::string& userName, const std::vector<std::string>& groupNames)
{
if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
groupNames.end())
{
if (userName.length() > ipmiMaxUserNameLen)
{
log<level::ERR>("IPMI user name length limitation",
entry("SIZE=%d", userName.length()));
elog<UserNameGroupFail>(
xyz::openbmc_project::User::Common::UserNameGroupFail::REASON(
"IPMI length"));
}
}
if (userName.length() > systemMaxUserNameLen)
{
log<level::ERR>("User name length limitation",
entry("SIZE=%d", userName.length()));
elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
Argument::ARGUMENT_VALUE("Invalid length"));
}
if (!std::regex_match(userName.c_str(),
std::regex("[a-zA-z_][a-zA-Z_0-9]*")))
{
log<level::ERR>("Invalid user name",
entry("USER_NAME=%s", userName.c_str()));
elog<InvalidArgument>(Argument::ARGUMENT_NAME("User name"),
Argument::ARGUMENT_VALUE("Invalid data"));
}
}
void UserMgr::throwForMaxGrpUserCount(
const std::vector<std::string>& groupNames)
{
if (std::find(groupNames.begin(), groupNames.end(), "ipmi") !=
groupNames.end())
{
if (getIpmiUsersCount() >= ipmiMaxUsers)
{
log<level::ERR>("IPMI user limit reached");
elog<NoResource>(
xyz::openbmc_project::User::Common::NoResource::REASON(
"ipmi user count reached"));
}
}
else
{
if (usersList.size() > 0 && (usersList.size() >= maxSystemUsers))
{
log<level::ERR>("Non-ipmi User limit reached");
elog<NoResource>(
xyz::openbmc_project::User::Common::NoResource::REASON(
"Non-ipmi user count reached"));
}
}
return;
}
void UserMgr::throwForInvalidPrivilege(const std::string& priv)
{
if (!priv.empty() &&
(std::find(privMgr.begin(), privMgr.end(), priv) == privMgr.end()))
{
log<level::ERR>("Invalid privilege");
elog<InvalidArgument>(Argument::ARGUMENT_NAME("Privilege"),
Argument::ARGUMENT_VALUE(priv.c_str()));
}
}
void UserMgr::throwForInvalidGroups(const std::vector<std::string>& groupNames)
{
for (auto& group : groupNames)
{
if (std::find(groupsMgr.begin(), groupsMgr.end(), group) ==
groupsMgr.end())
{
log<level::ERR>("Invalid Group Name listed");
elog<InvalidArgument>(Argument::ARGUMENT_NAME("GroupName"),
Argument::ARGUMENT_VALUE(group.c_str()));
}
}
}
/* Notes for restricted priv-operator role:
*
* The priv-operator role is restricted so you cannot create an operator user
* or change an existing user to have the operator role. However, if there
* happens to be a user with the operator role, you are allowed to rename or
* delete that user, or change them away from the operator role.
*/
void UserMgr::throwForRestrictedPrivilegeRole(const std::string& priv)
{
if ((priv == "priv-oemibmserviceagent") || (priv == "priv-operator"))
{
log<level::ERR>("Restricted role");
elog<InternalFailure>();
}
}
void UserMgr::throwForRestrictedUserPrivilegeRole(const std::string& userName)
{
const std::string priv = usersList[userName].get()->userPrivilege();
if (priv == "priv-oemibmserviceagent")
{
log<level::ERR>("User has restricted role");
elog<InternalFailure>();
}
}
void UserMgr::createUser(std::string userName,
std::vector<std::string> groupNames, std::string priv,
bool enabled)
{
throwForInvalidPrivilege(priv);
throwForRestrictedPrivilegeRole(priv);
throwForInvalidGroups(groupNames);
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
throwForUserExists(userName);
throwForUserNameConstraints(userName, groupNames);
throwForMaxGrpUserCount(groupNames);
std::string groups = getCSVFromVector(groupNames);
// The "ssh" phosphor-privilege group controls access to the host console
// via SSH port 2200 and has a special implementation.
// In the OpenBMC community project:
// A. It allows access to the BMC's SSH interfaces
// - SSH port 22 reaches the BMC's command shell.
// - SSH port 2200 reaches the host console.
// B. It is enforced by two mechanisms:
// 1. The SSH dropbear server command uses the -G priv-admin argument
// to restrict SSH access to users who are in the priv-admin Linux
// group.
// 2. The Linux user's login shell was set to /bin/sh (when "ssh" was
// specified) or /bin/nologin (when "ssh" is not specified).
// Having loginShell=/bin/sh is required to be able to get in
// through the SSH interface. The condition (loginShell==/bin/sh)
// is equivalent to being in the "ssh" privilege-group.
// Note there is no "ssh" Linux group.
// For p10bmc:
// A. Additionally:
// - SSH port 2201 to reaches the hypervisor console (PHYP).
// B. We created three new Linux groups to control access to the SSH
// destinations:
// - SSH port 22 is controlled by membership in "bmcshellaccess".
// Only the special service user should be in this group.
// - SSH port 2200 is controlled by membership in "hostconsoleaccess"
// All users (including the service user) should be in this group.
// - SSH port 2201 is controlled by membership in the
// "hypervisorconsoleaccess" group.
// Only the special service user should be in this group.
//
// The BMC administrator is not allowed to independently control which
// users have "ssh" access. That access is tied to the user account's
// role, described here.
// The special handling in this code for the "ssh" group:
// 1. Ignore the "ssh" value as input.
// 2. For admin and operator users, act as if the "ssh" group was given.
// 2a. Put the user into the hostconsoleaccess Linux group.
// 2b. Set the user's login shell to /bin/sh.
// For readonly accounts, act as if the "ssh" group was not given.
// 2a. Do not put the user into the hostconsoleaccess Linux group
// (meaning the user will not be in that group).
// 2b. Set the user's login shell to /bin/nologin.
// Note: No special code is needed to handle the special "service" user
// because priv-oemibmserviceagent is a restricted role which means
// the service agent's groups cannot be changed.
removeStringFromCSV(groups, grpSsh);
bool sshRequested = (priv != "priv-user");
if (sshRequested)
{
if (groups.size() != 0)
{
groups += ",";
}
groups += "hostconsoleaccess";
}
// treat privilege as a group - This is to avoid using different file to
// store the same.
if (!priv.empty())
{
if (groups.size() != 0)
{
groups += ",";
}
groups += priv;
}
try
{
executeCmd("/usr/sbin/useradd", userName.c_str(), "-G", groups.c_str(),
"-m", "-N", "-s",
(sshRequested ? "/bin/sh" : "/bin/nologin"), "-e",
(enabled ? "" : "1970-01-02"));
}
catch (const InternalFailure& e)
{
log<level::ERR>("Unable to create new user");
elog<InternalFailure>();
}
// Add the users object before sending out the signal
std::string userObj = std::string(usersObjPath) + "/" + userName;
std::sort(groupNames.begin(), groupNames.end());
usersList.emplace(
userName, std::move(std::make_unique<phosphor::user::Users>(
bus, userObj.c_str(), groupNames, priv, enabled, *this)));
log<level::INFO>("User created successfully",
entry("USER_NAME=%s", userName.c_str()));
return;
}
void UserMgr::deleteUser(std::string userName)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
throwForUserDoesNotExist(userName);
throwForRestrictedUserPrivilegeRole(userName);
try
{
executeCmd("/usr/sbin/userdel", userName.c_str(), "-r");
}
catch (const InternalFailure& e)
{
log<level::ERR>("User delete failed",
entry("USER_NAME=%s", userName.c_str()));
elog<InternalFailure>();
}
usersList.erase(userName);
log<level::INFO>("User deleted successfully",
entry("USER_NAME=%s", userName.c_str()));
return;
}
void UserMgr::renameUser(std::string userName, std::string newUserName)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
throwForUserDoesNotExist(userName);
throwForUserExists(newUserName);
throwForUserNameConstraints(newUserName,
usersList[userName].get()->userGroups());
throwForRestrictedUserPrivilegeRole(userName);
try
{
std::string newHomeDir = "/home/" + newUserName;
executeCmd("/usr/sbin/usermod", "-l", newUserName.c_str(),
userName.c_str(), "-d", newHomeDir.c_str(), "-m");
}
catch (const InternalFailure& e)
{
log<level::ERR>("User rename failed",
entry("USER_NAME=%s", userName.c_str()));
elog<InternalFailure>();
}
const auto& user = usersList[userName];
std::string priv = user.get()->userPrivilege();
std::vector<std::string> groupNames = user.get()->userGroups();
bool enabled = user.get()->userEnabled();
std::string newUserObj = std::string(usersObjPath) + "/" + newUserName;
// Special group 'ipmi' needs a way to identify user renamed, in order to
// update encrypted password. It can't rely only on InterfacesRemoved &
// InterfacesAdded. So first send out userRenamed signal.
this->userRenamed(userName, newUserName);
usersList.erase(userName);
usersList.emplace(
newUserName,
std::move(std::make_unique<phosphor::user::Users>(
bus, newUserObj.c_str(), groupNames, priv, enabled, *this)));
return;
}
void UserMgr::updateGroupsAndPriv(const std::string& userName,
const std::vector<std::string>& groupNames,
const std::string& priv)
{
throwForInvalidPrivilege(priv);
throwForRestrictedPrivilegeRole(priv);
throwForInvalidGroups(groupNames);
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
throwForUserDoesNotExist(userName);
throwForRestrictedUserPrivilegeRole(userName);
const std::vector<std::string>& oldGroupNames =
usersList[userName].get()->userGroups();
std::vector<std::string> groupDiff;
// Note: already dealing with sorted group lists.
std::set_symmetric_difference(oldGroupNames.begin(), oldGroupNames.end(),
groupNames.begin(), groupNames.end(),
std::back_inserter(groupDiff));
if (std::find(groupDiff.begin(), groupDiff.end(), "ipmi") !=
groupDiff.end())
{
throwForUserNameConstraints(userName, groupNames);
throwForMaxGrpUserCount(groupNames);
}
std::string groups = getCSVFromVector(groupNames);
// The "ssh" phosphor privilege group is handled specially
removeStringFromCSV(groups, grpSsh);
bool sshRequested = (priv != "priv-user");
if (sshRequested)
{
if (groups.size() != 0)
{
groups += ",";
}
groups += "hostconsoleaccess";
}
// treat privilege as a group - This is to avoid using different file to
// store the same.
if (!priv.empty())
{
if (groups.size() != 0)
{
groups += ",";
}
groups += priv;
}
try
{
executeCmd("/usr/sbin/usermod", userName.c_str(), "-G", groups.c_str(),
"-s", (sshRequested ? "/bin/sh" : "/bin/nologin"));
}
catch (const InternalFailure& e)
{
log<level::ERR>("Unable to modify user privilege / groups");
elog<InternalFailure>();
}
log<level::INFO>("User groups / privilege updated successfully",
entry("USER_NAME=%s", userName.c_str()));
return;
}
uint8_t UserMgr::minPasswordLength(uint8_t value)
{
if (value == AccountPolicyIface::minPasswordLength())
{
return value;
}
if (value < minPasswdLength)
{
return value;
}
if (setPamModuleArgValue(pamPWQuality, minPasswdLenProp,
std::to_string(value)) != success)
{
log<level::ERR>("Unable to set minPasswordLength");
elog<InternalFailure>();
}
return AccountPolicyIface::minPasswordLength(value);
}
uint8_t UserMgr::rememberOldPasswordTimes(uint8_t value)
{
if (value == AccountPolicyIface::rememberOldPasswordTimes())
{
return value;
}
if (setPamModuleArgValue(pamPWHistory, remOldPasswdCount,
std::to_string(value)) != success)
{
log<level::ERR>("Unable to set rememberOldPasswordTimes");
elog<InternalFailure>();
}
return AccountPolicyIface::rememberOldPasswordTimes(value);
}
uint16_t UserMgr::maxLoginAttemptBeforeLockout(uint16_t value)
{
if (value == AccountPolicyIface::maxLoginAttemptBeforeLockout())
{
return value;
}
if (setPamModuleArgValue(pamFaillock, maxFailedAttempt,
std::to_string(value)) != success)
{
log<level::ERR>("Unable to set maxLoginAttemptBeforeLockout");
elog<InternalFailure>();
}
return AccountPolicyIface::maxLoginAttemptBeforeLockout(value);
}
uint32_t UserMgr::accountUnlockTimeout(uint32_t value)
{
if (value == AccountPolicyIface::accountUnlockTimeout())
{
return value;
}
if (setPamModuleArgValue(pamFaillock, unlockTimeout,
std::to_string(value)) != success)
{
log<level::ERR>("Unable to set accountUnlockTimeout");
elog<InternalFailure>();
}
return AccountPolicyIface::accountUnlockTimeout(value);
}
int UserMgr::getPamModuleArgValue(const std::string& moduleName,
const std::string& argName,
std::string& argValue)
{
std::string fileName;
bool simpleConfigFile = false;
if (moduleName == pamFaillock)
{
fileName = faillockConfigFile;
simpleConfigFile = true;
}
else if (moduleName == pamPWQuality)
{
fileName = pwQualityConfigFile;
simpleConfigFile = true;
}
else
{
fileName = pamPasswdConfigFile;
}
std::ifstream fileToRead(fileName, std::ios::in);
if (!fileToRead.is_open())
{
log<level::ERR>("Failed to open pam configuration file",
entry("FILE_NAME=%s", fileName.c_str()));
return failure;
}
std::string line;
auto argSearch = argName + "=";
size_t startPos = 0;
size_t endPos = 0;
while (getline(fileToRead, line))
{
// skip comments section starting with #
if ((startPos = line.find('#')) != std::string::npos)
{
if (startPos == 0)
{
continue;
}
// skip comments after meaningful section and process those
line = line.substr(0, startPos);
}
if (simpleConfigFile || (line.find(moduleName) != std::string::npos))
{
if ((startPos = line.find(argSearch)) != std::string::npos)
{
if ((endPos = line.find(' ', startPos)) == std::string::npos)
{
endPos = line.size();
}
startPos += argSearch.size();
argValue = line.substr(startPos, endPos - startPos);
return success;
}
}
}
return failure;
}
int UserMgr::setPamModuleArgValue(const std::string& moduleName,
const std::string& argName,
const std::string& argValue)
{
std::string fileName;
bool simpleConfigFile = false;
if (moduleName == pamFaillock)
{
fileName = faillockConfigFile;
simpleConfigFile = true;
}
else if (moduleName == pamPWQuality)
{
fileName = pwQualityConfigFile;
simpleConfigFile = true;
}
else
{
fileName = pamPasswdConfigFile;
}
std::string tmpFileName = fileName + "_tmp";
std::ifstream fileToRead(fileName, std::ios::in);
std::ofstream fileToWrite(tmpFileName, std::ios::out);
if (!fileToRead.is_open() || !fileToWrite.is_open())
{
log<level::ERR>("Failed to open pam configuration /tmp file",
entry("FILE_NAME=%s", fileName.c_str()));
return failure;
}
std::string line;
auto argSearch = argName + "=";
size_t startPos = 0;
size_t endPos = 0;
bool found = false;
while (getline(fileToRead, line))
{
// skip comments section starting with #
if ((startPos = line.find('#')) != std::string::npos)
{
if (startPos == 0)
{
fileToWrite << line << std::endl;
continue;
}
// skip comments after meaningful section and process those
line = line.substr(0, startPos);
}
if (simpleConfigFile || (line.find(moduleName) != std::string::npos))
{
if ((startPos = line.find(argSearch)) != std::string::npos)
{
if ((endPos = line.find(' ', startPos)) == std::string::npos)
{
endPos = line.size();
}
startPos += argSearch.size();
fileToWrite << line.substr(0, startPos) << argValue
<< line.substr(endPos, line.size() - endPos)
<< std::endl;
found = true;
continue;
}
}
fileToWrite << line << std::endl;
}
fileToWrite.close();
fileToRead.close();
if (found)
{
if (std::rename(tmpFileName.c_str(), fileName.c_str()) == 0)
{
return success;
}
}
return failure;
}
void UserMgr::userEnable(const std::string& userName, bool enabled)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
throwForUserDoesNotExist(userName);
// Note: Allowed to enable and disable users with restricted role
try
{
executeCmd("/usr/sbin/usermod", userName.c_str(), "-e",
(enabled ? "" : "1970-01-02"));
}
catch (const InternalFailure& e)
{
log<level::ERR>("Unable to modify user enabled state");
elog<InternalFailure>();
}
log<level::INFO>("User enabled/disabled state updated successfully",
entry("USER_NAME=%s", userName.c_str()),
entry("ENABLED=%d", enabled));
return;
}
bool UserMgr::userLockedForFailedAttempt(const std::string& userName)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
// Emulate the behavior of pam_faillock.so authsucc: get the number of
// failed attempts and compare with the deny= value
// See https://github.com/linux-pam/linux-pam/issues/327
std::vector<std::string> output;
output = executeCmd("/usr/sbin/faillock", "--user", userName.c_str());
// Expected output:
// If user is not known to faillock, output is empty.
// If user is known to faillock, output is two header lines followed by zero
// or more records:
// > {userName}:
// > "When Type Source Valid"
// > ${timestamp} ${type} {RHOST,TTY,SVC} {V,I}
//
// If there is an error, the output is a single line like this:
// /usr/sbin/faillock: Error clearing the tally file for {user}:{output from
// perror}
// Example: /usr/sbin/faillock: Error opening the tally file for admin:Not
// a directory
int failedAttempts = 0;
if (output.empty())
{
failedAttempts = 0;
}
else if (output.size() < 2)
{
log<level::ERR>("faillock resulted in error",
entry("USER=%s", userName.c_str()));
if (output.size() >= 1)
{
log<level::ERR>("faillock error message",
entry("ERROR=%s", output[0].c_str()));
}
elog<InternalFailure>();
}
else
{
failedAttempts = output.size() - 2;
}
if (AccountPolicyIface::maxLoginAttemptBeforeLockout() != 0 &&
failedAttempts >= AccountPolicyIface::maxLoginAttemptBeforeLockout())
{
return true; // User account password is locked
}
return false; // User account password is un-locked
}
bool UserMgr::userLockedForFailedAttempt(const std::string& userName,
const bool& value)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
// Note: Allowed to unlock password of users with restricted role
std::vector<std::string> output;
if (value == true)
{
return userLockedForFailedAttempt(userName);
}
output =
executeCmd("/usr/sbin/faillock", "--user", userName.c_str(), "--reset");
if (!output.empty() && output[0].find("Error") != std::string::npos)
{
log<level::ERR>("faillock reset resulted in error",
entry("USER=%s", userName.c_str()),
entry("OUTPUT=%s", output[0].c_str()));
elog<InternalFailure>();
}
return userLockedForFailedAttempt(userName);
}
bool UserMgr::userPasswordExpired(const std::string& userName)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
struct spwd spwd
{};
struct spwd* spwdPtr = nullptr;
auto buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
if (buflen < -1)
{
// Use a default size if there is no hard limit suggested by sysconf()
buflen = 1024;
}
std::vector<char> buffer(buflen);
auto status =
getspnam_r(userName.c_str(), &spwd, buffer.data(), buflen, &spwdPtr);
// On success, getspnam_r() returns zero, and sets *spwdPtr to spwd.
// If no matching password record was found, these functions return 0
// and store NULL in *spwdPtr
if ((status == 0) && (&spwd == spwdPtr))
{
// Determine password validity per "chage" docs, where:
// spwd.sp_lstchg == 0 means password is expired, and
// spwd.sp_max == -1 means the password does not expire.
constexpr long seconds_per_day = 60 * 60 * 24;
long today = static_cast<long>(time(NULL)) / seconds_per_day;
if ((spwd.sp_lstchg == 0) ||
((spwd.sp_max != -1) && ((spwd.sp_max + spwd.sp_lstchg) < today)))
{
return true;
}
}
else
{
// User entry is missing in /etc/shadow, indicating no SHA password.
// Treat this as new user without password entry in /etc/shadow
// TODO: Add property to indicate user password was not set yet
// https://github.com/openbmc/phosphor-user-manager/issues/8
return false;
}
return false;
}
UserSSHLists UserMgr::getUserAndSshGrpList()
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
std::vector<std::string> userList;
std::vector<std::string> sshUsersList;
struct passwd pw, *pwp = nullptr;
std::array<char, 1024> buffer{};
phosphor::user::File passwd(passwdFileName, "r");
if ((passwd)() == NULL)
{
log<level::ERR>("Error opening the passwd file");
elog<InternalFailure>();
}
while (true)
{
auto r = fgetpwent_r((passwd)(), &pw, buffer.data(), buffer.max_size(),
&pwp);
if ((r != 0) || (pwp == NULL))
{
// Any error, break the loop.
break;
}
#ifdef ENABLE_ROOT_USER_MGMT
// Add all users whose UID >= 1000 and < 65534
// and special UID 0.
if ((pwp->pw_uid == 0) ||
((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534)))
#else
// Add all users whose UID >=1000 and < 65534
if ((pwp->pw_uid >= 1000) && (pwp->pw_uid < 65534))
#endif
{
std::string userName(pwp->pw_name);
userList.emplace_back(userName);
// ssh doesn't have separate group. Check login shell entry to
// get all users list which are member of ssh group.
std::string loginShell(pwp->pw_shell);
if (loginShell == "/bin/sh")
{
sshUsersList.emplace_back(userName);
}
}
}
endpwent();
return std::make_pair(std::move(userList), std::move(sshUsersList));
}
size_t UserMgr::getIpmiUsersCount()
{
std::vector<std::string> userList = getUsersInGroup("ipmi");
return userList.size();
}
bool UserMgr::isUserEnabled(const std::string& userName)
{
// All user management lock has to be based on /etc/shadow
// TODO phosphor-user-manager#10 phosphor::user::shadow::Lock lock{};
std::array<char, 4096> buffer{};
struct spwd spwd;
struct spwd* resultPtr = nullptr;
int status = getspnam_r(userName.c_str(), &spwd, buffer.data(),
buffer.max_size(), &resultPtr);
if (!status && (&spwd == resultPtr))
{
if (resultPtr->sp_expire >= 0)
{
return false; // user locked out
}
return true;
}
return false; // assume user is disabled for any error.
}
std::vector<std::string> UserMgr::getUsersInGroup(const std::string& groupName)
{
std::vector<std::string> usersInGroup;
// Should be more than enough to get the pwd structure.
std::array<char, 4096> buffer{};
struct group grp;
struct group* resultPtr = nullptr;
int status = getgrnam_r(groupName.c_str(), &grp, buffer.data(),
buffer.max_size(), &resultPtr);
if (!status && (&grp == resultPtr))
{
for (; *(grp.gr_mem) != NULL; ++(grp.gr_mem))
{
usersInGroup.emplace_back(*(grp.gr_mem));
}
}
else
{
log<level::ERR>("Group not found",
entry("GROUP=%s", groupName.c_str()));
// Don't throw error, just return empty userList - fallback
}