-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathusers.cpp
390 lines (363 loc) · 10.7 KB
/
users.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
/*
// 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 "users.hpp"
#include "totp.hpp"
#include "user_mgr.hpp"
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/lg2.hpp>
#include <xyz/openbmc_project/Common/error.hpp>
#include <xyz/openbmc_project/User/Common/error.hpp>
#include <filesystem>
#include <fstream>
#include <map>
namespace phosphor
{
namespace user
{
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 NoResource =
sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
using UnsupportedRequest =
sdbusplus::xyz::openbmc_project::Common::Error::UnsupportedRequest;
using Argument = xyz::openbmc_project::Common::InvalidArgument;
static constexpr auto authAppPath = "/usr/bin/google-authenticator";
static constexpr auto secretKeyPath = "/home/{}/.google_authenticator";
static constexpr auto secretKeyTempPath =
"/home/{}/.config/phosphor-user-manager/.google_authenticator.tmp";
/** @brief Constructs UserMgr object.
*
* @param[in] bus - sdbusplus handler
* @param[in] path - D-Bus path
* @param[in] groups - users group list
* @param[in] priv - user privilege
* @param[in] enabled - user enabled state
* @param[in] parent - user manager - parent object
*/
Users::Users(sdbusplus::bus_t& bus, const char* path,
std::vector<std::string> groups, std::string priv, bool enabled,
UserMgr& parent) :
Interfaces(bus, path, Interfaces::action::defer_emit),
userName(sdbusplus::message::object_path(path).filename()), manager(parent)
{
UsersIface::userPrivilege(priv, true);
UsersIface::userGroups(groups, true);
UsersIface::userEnabled(enabled, true);
load(manager.getSerializer());
this->emit_object_added();
}
Users::~Users()
{
manager.getSerializer().erase(userName);
}
/** @brief delete user method.
* This method deletes the user as requested
*
*/
void Users::delete_(void)
{
manager.deleteUser(userName);
}
/** @brief update user privilege
*
* @param[in] value - User privilege
*/
std::string Users::userPrivilege(std::string value)
{
if (value == UsersIface::userPrivilege())
{
return value;
}
manager.updateGroupsAndPriv(userName, UsersIface::userGroups(), value);
return UsersIface::userPrivilege(value);
}
void Users::setUserPrivilege(const std::string& value)
{
UsersIface::userPrivilege(value);
}
void Users::setUserGroups(const std::vector<std::string>& groups)
{
UsersIface::userGroups(groups);
}
/** @brief list user privilege
*
*/
std::string Users::userPrivilege(void) const
{
return UsersIface::userPrivilege();
}
/** @brief update user groups
*
* @param[in] value - User groups
*/
std::vector<std::string> Users::userGroups(std::vector<std::string> value)
{
if (value == UsersIface::userGroups())
{
return value;
}
std::sort(value.begin(), value.end());
manager.updateGroupsAndPriv(userName, value, UsersIface::userPrivilege());
return UsersIface::userGroups(value);
}
/** @brief list user groups
*
*/
std::vector<std::string> Users::userGroups(void) const
{
return UsersIface::userGroups();
}
/** @brief lists user enabled state
*
*/
bool Users::userEnabled(void) const
{
return manager.isUserEnabled(userName);
}
void Users::setUserEnabled(bool value)
{
UsersIface::userEnabled(value);
}
/** @brief update user enabled state
*
* @param[in] value - bool value
*/
bool Users::userEnabled(bool value)
{
if (value == UsersIface::userEnabled())
{
return value;
}
manager.userEnable(userName, value);
return UsersIface::userEnabled(value);
}
/** @brief lists user locked state for failed attempt
*
**/
bool Users::userLockedForFailedAttempt(void) const
{
return manager.userLockedForFailedAttempt(userName);
}
/** @brief unlock user locked state for failed attempt
*
* @param[in]: value - false - unlock user account, true - no action taken
**/
bool Users::userLockedForFailedAttempt(bool value)
{
if (value != false)
{
return userLockedForFailedAttempt();
}
else
{
return manager.userLockedForFailedAttempt(userName, value);
}
}
/** @brief indicates if the user's password is expired
*
**/
bool Users::userPasswordExpired(void) const
{
return manager.userPasswordExpired(userName);
}
bool changeFileOwnership(const std::string& filePath,
const std::string& userName)
{
// Get the user ID
passwd* pwd = getpwnam(userName.c_str());
if (pwd == nullptr)
{
lg2::error("Failed to get user ID for user:{USER}", "USER", userName);
return false;
}
// Change the ownership of the file
if (chown(filePath.c_str(), pwd->pw_uid, pwd->pw_gid) != 0)
{
lg2::error("Ownership change error {PATH}", "PATH", filePath);
return false;
}
return true;
}
bool Users::checkMfaStatus() const
{
return (manager.enabled() != MultiFactorAuthType::None &&
Interfaces::bypassedProtocol() == MultiFactorAuthType::None);
}
std::string Users::createSecretKey()
{
if (!std::filesystem::exists(authAppPath))
{
lg2::error("No authenticator app found at {PATH}", "PATH", authAppPath);
throw UnsupportedRequest();
}
std::string path = std::format(secretKeyTempPath, userName);
if (!std::filesystem::exists(std::filesystem::path(path).parent_path()))
{
std::filesystem::create_directories(
std::filesystem::path(path).parent_path());
}
/*
-u no-rate-limit
-W minimal-window
-Q qr-mode (NONE, ANSI, UTF8)
-t time-based
-f force file
-d disallow-reuse
-C no-confirm no confirmation required for code provisioned
*/
executeCmd(authAppPath, "-s", path.c_str(), "-u", "-W", "-Q", "NONE", "-t",
"-f", "-d", "-C");
if (!std::filesystem::exists(path))
{
lg2::error("Failed to create secret key for user {USER}", "USER",
userName);
throw UnsupportedRequest();
}
std::ifstream file(path);
if (!file.is_open())
{
lg2::error("Failed to open secret key file {PATH}", "PATH", path);
throw UnsupportedRequest();
}
std::string secret;
std::getline(file, secret);
file.close();
if (!changeFileOwnership(path, userName))
{
throw UnsupportedRequest();
}
return secret;
}
bool Users::verifyOTP(std::string otp)
{
if (Totp::verify(getUserName(), otp) == PAM_SUCCESS)
{
// If MFA is enabled for the user register the secret key
if (checkMfaStatus())
{
try
{
std::filesystem::rename(
std::format(secretKeyTempPath, getUserName()),
std::format(secretKeyPath, getUserName()));
}
catch (const std::filesystem::filesystem_error& e)
{
lg2::error("Failed to rename file: {CODE}", "CODE", e);
return false;
}
}
else
{
std::filesystem::remove(
std::format(secretKeyTempPath, getUserName()));
}
return true;
}
return false;
}
static void clearSecretFile(const std::string& path)
{
if (std::filesystem::exists(path))
{
std::filesystem::remove(path);
}
}
static void clearGoogleAuthenticator(Users& thisp)
{
clearSecretFile(std::format(secretKeyPath, thisp.getUserName()));
clearSecretFile(std::format(secretKeyTempPath, thisp.getUserName()));
}
static std::map<MultiFactorAuthType, std::function<void(Users&)>>
mfaBypassHandlers{{MultiFactorAuthType::GoogleAuthenticator,
clearGoogleAuthenticator},
{MultiFactorAuthType::None, [](Users&) {}}};
MultiFactorAuthType Users::bypassedProtocol(MultiFactorAuthType value,
bool skipSignal)
{
auto iter = mfaBypassHandlers.find(value);
if (iter != end(mfaBypassHandlers))
{
iter->second(*this);
}
std::string path = std::format("{}/bypassedprotocol", getUserName());
manager.getSerializer().serialize(
path, MultiFactorAuthConfiguration::convertTypeToString(value));
manager.getSerializer().store();
return Interfaces::bypassedProtocol(value, skipSignal);
}
bool Users::secretKeyIsValid() const
{
std::string path = std::format(secretKeyPath, getUserName());
return std::filesystem::exists(path);
}
inline void googleAuthenticatorEnabled(Users& user, bool /*unused*/)
{
clearGoogleAuthenticator(user);
}
static std::map<MultiFactorAuthType, std::function<void(Users&, bool)>>
mfaEnableHandlers{{MultiFactorAuthType::GoogleAuthenticator,
googleAuthenticatorEnabled},
{MultiFactorAuthType::None, [](Users&, bool) {}}};
void Users::enableMultiFactorAuth(MultiFactorAuthType type, bool value)
{
auto iter = mfaEnableHandlers.find(type);
if (iter != end(mfaEnableHandlers))
{
iter->second(*this, value);
}
}
bool Users::secretKeyGenerationRequired() const
{
return checkMfaStatus() && !secretKeyIsValid();
}
void Users::clearSecretKey()
{
if (!checkMfaStatus())
{
throw UnsupportedRequest();
}
clearGoogleAuthenticator(*this);
}
void Users::load(JsonSerializer& ts)
{
std::optional<std::string> protocol;
std::string path = std::format("{}/bypassedprotocol", userName);
ts.deserialize(path, protocol);
if (protocol)
{
MultiFactorAuthType type =
MultiFactorAuthConfiguration::convertTypeFromString(*protocol);
bypassedProtocol(type, true);
return;
}
bypassedProtocol(MultiFactorAuthType::None, true);
ts.serialize(path, MultiFactorAuthConfiguration::convertTypeToString(
MultiFactorAuthType::None));
}
} // namespace user
} // namespace phosphor