blob: c205fea6c5a8f34bbb65ceacbeae1e96a1b15321 [file] [log] [blame]
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +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#include "user_mgmt.hpp"
17
18#include "apphandler.hpp"
Saravanan Palanisamy77381f12019-05-15 22:33:17 +000019#include "channel_layer.hpp"
Johnathan Manteyfd61fc32021-04-08 11:05:38 -070020#include "channel_mgmt.hpp"
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053021
Suryakanth Sekar90b00c72019-01-16 10:37:57 +053022#include <security/pam_appl.h>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053023#include <sys/stat.h>
24#include <unistd.h>
25
26#include <boost/interprocess/sync/named_recursive_mutex.hpp>
27#include <boost/interprocess/sync/scoped_lock.hpp>
28#include <cerrno>
29#include <fstream>
Snehalatha Venkatesh745164c2021-06-25 10:02:25 +000030#include <ipmid/types.hpp>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053031#include <nlohmann/json.hpp>
32#include <phosphor-logging/elog-errors.hpp>
33#include <phosphor-logging/log.hpp>
34#include <regex>
35#include <sdbusplus/bus/match.hpp>
36#include <sdbusplus/server/object.hpp>
Vernon Mauery16b86932019-05-01 08:36:11 -070037#include <variant>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053038#include <xyz/openbmc_project/Common/error.hpp>
39#include <xyz/openbmc_project/User/Common/error.hpp>
40
41namespace ipmi
42{
43
44// TODO: Move D-Bus & Object Manager related stuff, to common files
45// D-Bus property related
46static constexpr const char* dBusPropertiesInterface =
47 "org.freedesktop.DBus.Properties";
48static constexpr const char* getAllPropertiesMethod = "GetAll";
49static constexpr const char* propertiesChangedSignal = "PropertiesChanged";
50static constexpr const char* setPropertiesMethod = "Set";
51
52// Object Manager related
53static constexpr const char* dBusObjManager =
54 "org.freedesktop.DBus.ObjectManager";
55static constexpr const char* getManagedObjectsMethod = "GetManagedObjects";
56// Object Manager signals
57static constexpr const char* intfAddedSignal = "InterfacesAdded";
58static constexpr const char* intfRemovedSignal = "InterfacesRemoved";
59
60// Object Mapper related
61static constexpr const char* objMapperService =
62 "xyz.openbmc_project.ObjectMapper";
63static constexpr const char* objMapperPath =
64 "/xyz/openbmc_project/object_mapper";
65static constexpr const char* objMapperInterface =
66 "xyz.openbmc_project.ObjectMapper";
67static constexpr const char* getSubTreeMethod = "GetSubTree";
68static constexpr const char* getObjectMethod = "GetObject";
69
70static constexpr const char* ipmiUserMutex = "ipmi_usr_mutex";
71static constexpr const char* ipmiMutexCleanupLockFile =
72 "/var/lib/ipmi/ipmi_usr_mutex_cleanup";
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +000073static constexpr const char* ipmiUserSignalLockFile =
74 "/var/lib/ipmi/ipmi_usr_signal_mutex";
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053075static constexpr const char* ipmiUserDataFile = "/var/lib/ipmi/ipmi_user.json";
76static constexpr const char* ipmiGrpName = "ipmi";
77static constexpr size_t privNoAccess = 0xF;
78static constexpr size_t privMask = 0xF;
79
80// User manager related
81static constexpr const char* userMgrObjBasePath = "/xyz/openbmc_project/user";
82static constexpr const char* userObjBasePath = "/xyz/openbmc_project/user";
83static constexpr const char* userMgrInterface =
84 "xyz.openbmc_project.User.Manager";
85static constexpr const char* usersInterface =
86 "xyz.openbmc_project.User.Attributes";
87static constexpr const char* deleteUserInterface =
88 "xyz.openbmc_project.Object.Delete";
89
90static constexpr const char* createUserMethod = "CreateUser";
91static constexpr const char* deleteUserMethod = "Delete";
92static constexpr const char* renameUserMethod = "RenameUser";
93// User manager signal memebers
94static constexpr const char* userRenamedSignal = "UserRenamed";
95// Mgr interface properties
96static constexpr const char* allPrivProperty = "AllPrivileges";
97static constexpr const char* allGrpProperty = "AllGroups";
98// User interface properties
99static constexpr const char* userPrivProperty = "UserPrivilege";
100static constexpr const char* userGrpProperty = "UserGroups";
101static constexpr const char* userEnabledProperty = "UserEnabled";
102
103static std::array<std::string, (PRIVILEGE_OEM + 1)> ipmiPrivIndex = {
104 "priv-reserved", // PRIVILEGE_RESERVED - 0
105 "priv-callback", // PRIVILEGE_CALLBACK - 1
106 "priv-user", // PRIVILEGE_USER - 2
107 "priv-operator", // PRIVILEGE_OPERATOR - 3
108 "priv-admin", // PRIVILEGE_ADMIN - 4
109 "priv-custom" // PRIVILEGE_OEM - 5
110};
111
112using namespace phosphor::logging;
113using Json = nlohmann::json;
114
Vernon Mauery16b86932019-05-01 08:36:11 -0700115using PrivAndGroupType = std::variant<std::string, std::vector<std::string>>;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530116
117using NoResource =
118 sdbusplus::xyz::openbmc_project::User::Common::Error::NoResource;
119
120using InternalFailure =
121 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
122
Lei YU4b0ddb62019-01-25 16:43:50 +0800123std::unique_ptr<sdbusplus::bus::match_t> userUpdatedSignal
124 __attribute__((init_priority(101)));
125std::unique_ptr<sdbusplus::bus::match_t> userMgrRenamedSignal
126 __attribute__((init_priority(101)));
127std::unique_ptr<sdbusplus::bus::match_t> userPropertiesSignal
128 __attribute__((init_priority(101)));
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530129
130// TODO: Below code can be removed once it is moved to common layer libmiscutil
131std::string getUserService(sdbusplus::bus::bus& bus, const std::string& intf,
132 const std::string& path)
133{
134 auto mapperCall = bus.new_method_call(objMapperService, objMapperPath,
135 objMapperInterface, getObjectMethod);
136
137 mapperCall.append(path);
138 mapperCall.append(std::vector<std::string>({intf}));
139
140 auto mapperResponseMsg = bus.call(mapperCall);
141
142 std::map<std::string, std::vector<std::string>> mapperResponse;
143 mapperResponseMsg.read(mapperResponse);
144
145 if (mapperResponse.begin() == mapperResponse.end())
146 {
147 throw sdbusplus::exception::SdBusError(
148 -EIO, "ERROR in reading the mapper response");
149 }
150
151 return mapperResponse.begin()->first;
152}
153
154void setDbusProperty(sdbusplus::bus::bus& bus, const std::string& service,
155 const std::string& objPath, const std::string& interface,
156 const std::string& property,
157 const DbusUserPropVariant& value)
158{
159 try
160 {
161 auto method =
162 bus.new_method_call(service.c_str(), objPath.c_str(),
163 dBusPropertiesInterface, setPropertiesMethod);
164 method.append(interface, property, value);
165 bus.call(method);
166 }
Patrick Williamsef1259b2021-09-02 09:12:33 -0500167 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530168 {
169 log<level::ERR>("Failed to set property",
170 entry("PROPERTY=%s", property.c_str()),
171 entry("PATH=%s", objPath.c_str()),
172 entry("INTERFACE=%s", interface.c_str()));
173 throw;
174 }
175}
176
177static std::string getUserServiceName()
178{
179 static sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
180 static std::string userMgmtService;
181 if (userMgmtService.empty())
182 {
183 try
184 {
185 userMgmtService =
186 ipmi::getUserService(bus, userMgrInterface, userMgrObjBasePath);
187 }
Patrick Williamsef1259b2021-09-02 09:12:33 -0500188 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530189 {
190 userMgmtService.clear();
191 }
192 }
193 return userMgmtService;
194}
195
196UserAccess& getUserAccessObject()
197{
198 static UserAccess userAccess;
199 return userAccess;
200}
201
202int getUserNameFromPath(const std::string& path, std::string& userName)
203{
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530204 sdbusplus::message::object_path objPath(path);
205 userName.assign(objPath.filename());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530206 return 0;
207}
208
209void userUpdateHelper(UserAccess& usrAccess, const UserUpdateEvent& userEvent,
210 const std::string& userName, const std::string& priv,
211 const bool& enabled, const std::string& newUserName)
212{
213 UsersTbl* userData = usrAccess.getUsersTblPtr();
214 if (userEvent == UserUpdateEvent::userCreated)
215 {
216 if (usrAccess.addUserEntry(userName, priv, enabled) == false)
217 {
218 return;
219 }
220 }
221 else
222 {
223 // user index 0 is reserved, starts with 1
224 size_t usrIndex = 1;
225 for (; usrIndex <= ipmiMaxUsers; ++usrIndex)
226 {
227 std::string curName(
228 reinterpret_cast<char*>(userData->user[usrIndex].userName), 0,
229 ipmiMaxUserName);
230 if (userName == curName)
231 {
232 break; // found the entry
233 }
234 }
235 if (usrIndex > ipmiMaxUsers)
236 {
237 log<level::DEBUG>("User not found for signal",
238 entry("USER_NAME=%s", userName.c_str()),
239 entry("USER_EVENT=%d", userEvent));
240 return;
241 }
242 switch (userEvent)
243 {
244 case UserUpdateEvent::userDeleted:
245 {
246 usrAccess.deleteUserIndex(usrIndex);
247 break;
248 }
249 case UserUpdateEvent::userPrivUpdated:
250 {
251 uint8_t userPriv =
252 static_cast<uint8_t>(
253 UserAccess::convertToIPMIPrivilege(priv)) &
254 privMask;
255 // Update all channels privileges, only if it is not equivalent
256 // to getUsrMgmtSyncIndex()
257 if (userData->user[usrIndex]
258 .userPrivAccess[UserAccess::getUsrMgmtSyncIndex()]
259 .privilege != userPriv)
260 {
261 for (size_t chIndex = 0; chIndex < ipmiMaxChannels;
262 ++chIndex)
263 {
264 userData->user[usrIndex]
265 .userPrivAccess[chIndex]
266 .privilege = userPriv;
267 }
268 }
269 break;
270 }
271 case UserUpdateEvent::userRenamed:
272 {
273 std::fill(
274 static_cast<uint8_t*>(userData->user[usrIndex].userName),
275 static_cast<uint8_t*>(userData->user[usrIndex].userName) +
276 sizeof(userData->user[usrIndex].userName),
277 0);
278 std::strncpy(
279 reinterpret_cast<char*>(userData->user[usrIndex].userName),
280 newUserName.c_str(), ipmiMaxUserName);
281 ipmiRenameUserEntryPassword(userName, newUserName);
282 break;
283 }
284 case UserUpdateEvent::userStateUpdated:
285 {
286 userData->user[usrIndex].userEnabled = enabled;
287 break;
288 }
289 default:
290 {
291 log<level::ERR>("Unhandled user event",
292 entry("USER_EVENT=%d", userEvent));
293 return;
294 }
295 }
296 }
297 usrAccess.writeUserData();
298 log<level::DEBUG>("User event handled successfully",
299 entry("USER_NAME=%s", userName.c_str()),
300 entry("USER_EVENT=%d", userEvent));
301
302 return;
303}
304
305void userUpdatedSignalHandler(UserAccess& usrAccess,
306 sdbusplus::message::message& msg)
307{
308 static sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
309 std::string signal = msg.get_member();
Patrick Venture3a697ad2019-08-19 11:12:05 -0700310 std::string userName, priv, newUserName;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530311 std::vector<std::string> groups;
312 bool enabled = false;
313 UserUpdateEvent userEvent = UserUpdateEvent::reservedEvent;
314 if (signal == intfAddedSignal)
315 {
316 DbusUserObjPath objPath;
317 DbusUserObjValue objValue;
318 msg.read(objPath, objValue);
319 getUserNameFromPath(objPath.str, userName);
320 if (usrAccess.getUserObjProperties(objValue, groups, priv, enabled) !=
321 0)
322 {
323 return;
324 }
325 if (std::find(groups.begin(), groups.end(), ipmiGrpName) ==
326 groups.end())
327 {
328 return;
329 }
330 userEvent = UserUpdateEvent::userCreated;
331 }
332 else if (signal == intfRemovedSignal)
333 {
334 DbusUserObjPath objPath;
335 std::vector<std::string> interfaces;
336 msg.read(objPath, interfaces);
337 getUserNameFromPath(objPath.str, userName);
338 userEvent = UserUpdateEvent::userDeleted;
339 }
340 else if (signal == userRenamedSignal)
341 {
342 msg.read(userName, newUserName);
343 userEvent = UserUpdateEvent::userRenamed;
344 }
345 else if (signal == propertiesChangedSignal)
346 {
347 getUserNameFromPath(msg.get_path(), userName);
348 }
349 else
350 {
351 log<level::ERR>("Unknown user update signal",
352 entry("SIGNAL=%s", signal.c_str()));
353 return;
354 }
355
356 if (signal.empty() || userName.empty() ||
357 (signal == userRenamedSignal && newUserName.empty()))
358 {
359 log<level::ERR>("Invalid inputs received");
360 return;
361 }
362
363 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
364 userLock{*(usrAccess.userMutex)};
365 usrAccess.checkAndReloadUserData();
366
367 if (signal == propertiesChangedSignal)
368 {
369 std::string intfName;
370 DbusUserObjProperties chProperties;
371 msg.read(intfName, chProperties); // skip reading 3rd argument.
372 for (const auto& prop : chProperties)
373 {
374 userEvent = UserUpdateEvent::reservedEvent;
375 std::string member = prop.first;
376 if (member == userPrivProperty)
377 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700378 priv = std::get<std::string>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530379 userEvent = UserUpdateEvent::userPrivUpdated;
380 }
381 else if (member == userGrpProperty)
382 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700383 groups = std::get<std::vector<std::string>>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530384 userEvent = UserUpdateEvent::userGrpUpdated;
385 }
386 else if (member == userEnabledProperty)
387 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700388 enabled = std::get<bool>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530389 userEvent = UserUpdateEvent::userStateUpdated;
390 }
391 // Process based on event type.
392 if (userEvent == UserUpdateEvent::userGrpUpdated)
393 {
394 if (std::find(groups.begin(), groups.end(), ipmiGrpName) ==
395 groups.end())
396 {
397 // remove user from ipmi user list.
398 userUpdateHelper(usrAccess, UserUpdateEvent::userDeleted,
399 userName, priv, enabled, newUserName);
400 }
401 else
402 {
403 DbusUserObjProperties properties;
404 try
405 {
406 auto method = bus.new_method_call(
407 getUserServiceName().c_str(), msg.get_path(),
408 dBusPropertiesInterface, getAllPropertiesMethod);
409 method.append(usersInterface);
410 auto reply = bus.call(method);
411 reply.read(properties);
412 }
Patrick Williamsef1259b2021-09-02 09:12:33 -0500413 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530414 {
415 log<level::DEBUG>(
416 "Failed to excute method",
417 entry("METHOD=%s", getAllPropertiesMethod),
418 entry("PATH=%s", msg.get_path()));
419 return;
420 }
421 usrAccess.getUserProperties(properties, groups, priv,
422 enabled);
423 // add user to ipmi user list.
424 userUpdateHelper(usrAccess, UserUpdateEvent::userCreated,
425 userName, priv, enabled, newUserName);
426 }
427 }
428 else if (userEvent != UserUpdateEvent::reservedEvent)
429 {
430 userUpdateHelper(usrAccess, userEvent, userName, priv, enabled,
431 newUserName);
432 }
433 }
434 }
435 else if (userEvent != UserUpdateEvent::reservedEvent)
436 {
437 userUpdateHelper(usrAccess, userEvent, userName, priv, enabled,
438 newUserName);
439 }
440 return;
441}
442
443UserAccess::~UserAccess()
444{
445 if (signalHndlrObject)
446 {
447 userUpdatedSignal.reset();
448 userMgrRenamedSignal.reset();
449 userPropertiesSignal.reset();
450 sigHndlrLock.unlock();
451 }
452}
453
454UserAccess::UserAccess() : bus(ipmid_get_sd_bus_connection())
455{
456 std::ofstream mutexCleanUpFile;
457 mutexCleanUpFile.open(ipmiMutexCleanupLockFile,
458 std::ofstream::out | std::ofstream::app);
459 if (!mutexCleanUpFile.good())
460 {
461 log<level::DEBUG>("Unable to open mutex cleanup file");
462 return;
463 }
464 mutexCleanUpFile.close();
465 mutexCleanupLock = boost::interprocess::file_lock(ipmiMutexCleanupLockFile);
466 if (mutexCleanupLock.try_lock())
467 {
468 boost::interprocess::named_recursive_mutex::remove(ipmiUserMutex);
469 }
470 mutexCleanupLock.lock_sharable();
471 userMutex = std::make_unique<boost::interprocess::named_recursive_mutex>(
472 boost::interprocess::open_or_create, ipmiUserMutex);
473
arun-pmbbe728c2020-01-10 15:18:04 +0530474 cacheUserDataFile();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530475 getSystemPrivAndGroups();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530476}
477
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530478UserInfo* UserAccess::getUserInfo(const uint8_t userId)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530479{
480 checkAndReloadUserData();
481 return &usersTbl.user[userId];
482}
483
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530484void UserAccess::setUserInfo(const uint8_t userId, UserInfo* userInfo)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530485{
486 checkAndReloadUserData();
487 std::copy(reinterpret_cast<uint8_t*>(userInfo),
488 reinterpret_cast<uint8_t*>(userInfo) + sizeof(*userInfo),
489 reinterpret_cast<uint8_t*>(&usersTbl.user[userId]));
490 writeUserData();
491}
492
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530493bool UserAccess::isValidChannel(const uint8_t chNum)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530494{
495 return (chNum < ipmiMaxChannels);
496}
497
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530498bool UserAccess::isValidUserId(const uint8_t userId)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530499{
500 return ((userId <= ipmiMaxUsers) && (userId != reservedUserId));
501}
502
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530503bool UserAccess::isValidPrivilege(const uint8_t priv)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530504{
jayaprakash Mutyala0e2dbee2019-12-26 13:03:04 +0000505 // Callback privilege is deprecated in OpenBMC
506 return (isValidPrivLimit(priv) || priv == privNoAccess);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530507}
508
509uint8_t UserAccess::getUsrMgmtSyncIndex()
510{
Johnathan Manteyfd61fc32021-04-08 11:05:38 -0700511 // Identify the IPMI channel used to assign system user privilege levels
512 // in phosphor-user-manager. The default value is IPMI Channel 1. To
513 // assign a different channel add:
514 // "is_management_nic" : true
515 // into the channel_config.json file describing the assignment of the IPMI
516 // channels. It is only necessary to add the string above to ONE record in
517 // the channel_config.json file. All other records will be automatically
518 // assigned a "false" value.
519 return getChannelConfigObject().getManagementNICID();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530520}
521
522CommandPrivilege UserAccess::convertToIPMIPrivilege(const std::string& value)
523{
524 auto iter = std::find(ipmiPrivIndex.begin(), ipmiPrivIndex.end(), value);
525 if (iter == ipmiPrivIndex.end())
526 {
527 if (value == "")
528 {
529 return static_cast<CommandPrivilege>(privNoAccess);
530 }
531 log<level::ERR>("Error in converting to IPMI privilege",
532 entry("PRIV=%s", value.c_str()));
533 throw std::out_of_range("Out of range - convertToIPMIPrivilege");
534 }
535 else
536 {
537 return static_cast<CommandPrivilege>(
538 std::distance(ipmiPrivIndex.begin(), iter));
539 }
540}
541
542std::string UserAccess::convertToSystemPrivilege(const CommandPrivilege& value)
543{
544 if (value == static_cast<CommandPrivilege>(privNoAccess))
545 {
546 return "";
547 }
548 try
549 {
550 return ipmiPrivIndex.at(value);
551 }
552 catch (const std::out_of_range& e)
553 {
554 log<level::ERR>("Error in converting to system privilege",
555 entry("PRIV=%d", static_cast<uint8_t>(value)));
556 throw std::out_of_range("Out of range - convertToSystemPrivilege");
557 }
558}
559
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000560bool UserAccess::isValidUserName(const std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530561{
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000562 if (userName.empty())
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530563 {
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000564 log<level::ERR>("userName is empty");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530565 return false;
566 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530567 if (!std::regex_match(userName.c_str(),
568 std::regex("[a-zA-z_][a-zA-Z_0-9]*")))
569 {
570 log<level::ERR>("Unsupported characters in user name");
571 return false;
572 }
573 if (userName == "root")
574 {
575 log<level::ERR>("Invalid user name - root");
576 return false;
577 }
578 std::map<DbusUserObjPath, DbusUserObjValue> properties;
579 try
580 {
581 auto method = bus.new_method_call(getUserServiceName().c_str(),
582 userMgrObjBasePath, dBusObjManager,
583 getManagedObjectsMethod);
584 auto reply = bus.call(method);
585 reply.read(properties);
586 }
Patrick Williamsef1259b2021-09-02 09:12:33 -0500587 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530588 {
589 log<level::ERR>("Failed to excute method",
590 entry("METHOD=%s", getSubTreeMethod),
591 entry("PATH=%s", userMgrObjBasePath));
592 return false;
593 }
594
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530595 sdbusplus::message::object_path tempUserPath(userObjBasePath);
596 tempUserPath /= userName;
597 std::string usersPath(tempUserPath);
598
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530599 if (properties.find(usersPath) != properties.end())
600 {
601 log<level::DEBUG>("User name already exists",
602 entry("USER_NAME=%s", userName.c_str()));
603 return false;
604 }
605
606 return true;
607}
608
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530609/** @brief Information exchanged by pam module and application.
610 *
611 * @param[in] numMsg - length of the array of pointers,msg.
612 *
613 * @param[in] msg - pointer to an array of pointers to pam_message structure
614 *
615 * @param[out] resp - struct pam response array
616 *
617 * @param[in] appdataPtr - member of pam_conv structure
618 *
619 * @return the response in pam response structure.
620 */
621
622static int pamFunctionConversation(int numMsg, const struct pam_message** msg,
623 struct pam_response** resp, void* appdataPtr)
624{
625 if (appdataPtr == nullptr)
626 {
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530627 return PAM_CONV_ERR;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530628 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530629
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530630 if (numMsg <= 0 || numMsg >= PAM_MAX_NUM_MSG)
631 {
632 return PAM_CONV_ERR;
633 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530634
635 for (int i = 0; i < numMsg; ++i)
636 {
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530637 /* Ignore all PAM messages except prompting for hidden input */
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530638 if (msg[i]->msg_style != PAM_PROMPT_ECHO_OFF)
639 {
640 continue;
641 }
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530642
643 /* Assume PAM is only prompting for the password as hidden input */
644 /* Allocate memory only when PAM_PROMPT_ECHO_OFF is encounterred */
645
646 char* appPass = reinterpret_cast<char*>(appdataPtr);
647 size_t appPassSize = std::strlen(appPass);
648
649 if (appPassSize >= PAM_MAX_RESP_SIZE)
650 {
651 return PAM_CONV_ERR;
652 }
653
654 char* pass = reinterpret_cast<char*>(malloc(appPassSize + 1));
655 if (pass == nullptr)
656 {
657 return PAM_BUF_ERR;
658 }
659
660 void* ptr =
661 calloc(static_cast<size_t>(numMsg), sizeof(struct pam_response));
662 if (ptr == nullptr)
663 {
664 free(pass);
665 return PAM_BUF_ERR;
666 }
667
668 std::strncpy(pass, appPass, appPassSize + 1);
669
670 *resp = reinterpret_cast<pam_response*>(ptr);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530671 resp[i]->resp = pass;
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530672
673 return PAM_SUCCESS;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530674 }
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530675
676 return PAM_CONV_ERR;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530677}
678
679/** @brief Updating the PAM password
680 *
681 * @param[in] username - username in string
682 *
683 * @param[in] password - new password in string
684 *
685 * @return status
686 */
687
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000688int pamUpdatePasswd(const char* username, const char* password)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530689{
690 const struct pam_conv localConversation = {pamFunctionConversation,
691 const_cast<char*>(password)};
692 pam_handle_t* localAuthHandle = NULL; // this gets set by pam_start
693
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000694 int retval =
695 pam_start("passwd", username, &localConversation, &localAuthHandle);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530696
697 if (retval != PAM_SUCCESS)
698 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000699 return retval;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530700 }
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000701
702 retval = pam_chauthtok(localAuthHandle, PAM_SILENT);
703 if (retval != PAM_SUCCESS)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530704 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000705 pam_end(localAuthHandle, retval);
706 return retval;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530707 }
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000708
709 return pam_end(localAuthHandle, PAM_SUCCESS);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530710}
711
Ayushi Smriti02650d52019-05-15 11:59:09 +0000712bool pamUserCheckAuthenticate(std::string_view username,
713 std::string_view password)
714{
715 const struct pam_conv localConversation = {
716 pamFunctionConversation, const_cast<char*>(password.data())};
717
718 pam_handle_t* localAuthHandle = NULL; // this gets set by pam_start
719
720 if (pam_start("dropbear", username.data(), &localConversation,
721 &localAuthHandle) != PAM_SUCCESS)
722 {
723 log<level::ERR>("User Authentication Failure");
724 return false;
725 }
726
727 int retval = pam_authenticate(localAuthHandle,
728 PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK);
729
730 if (retval != PAM_SUCCESS)
731 {
732 log<level::DEBUG>("pam_authenticate returned failure",
733 entry("ERROR=%d", retval));
734
735 pam_end(localAuthHandle, retval);
736 return false;
737 }
738
739 if (pam_acct_mgmt(localAuthHandle, PAM_DISALLOW_NULL_AUTHTOK) !=
740 PAM_SUCCESS)
741 {
742 pam_end(localAuthHandle, PAM_SUCCESS);
743 return false;
744 }
745
746 if (pam_end(localAuthHandle, PAM_SUCCESS) != PAM_SUCCESS)
747 {
748 return false;
749 }
750 return true;
751}
752
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000753Cc UserAccess::setSpecialUserPassword(const std::string& userName,
Vernon Mauery1e22a0f2021-07-30 13:36:54 -0700754 const SecureString& userPassword)
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530755{
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000756 if (pamUpdatePasswd(userName.c_str(), userPassword.c_str()) != PAM_SUCCESS)
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530757 {
758 log<level::DEBUG>("Failed to update password");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000759 return ccUnspecifiedError;
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530760 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000761 return ccSuccess;
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530762}
763
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000764Cc UserAccess::setUserPassword(const uint8_t userId, const char* userPassword)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530765{
766 std::string userName;
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000767 if (ipmiUserGetUserName(userId, userName) != ccSuccess)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530768 {
769 log<level::DEBUG>("User Name not found",
Ayushi Smriti05ad3412019-10-16 16:10:18 +0530770 entry("USER-ID=%d", (uint8_t)userId));
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000771 return ccParmOutOfRange;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530772 }
Snehalatha Venkatesh61024d72021-04-08 16:24:39 +0000773
774 ipmi::SecureString passwd;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530775 passwd.assign(reinterpret_cast<const char*>(userPassword), 0,
776 maxIpmi20PasswordSize);
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000777 int retval = pamUpdatePasswd(userName.c_str(), passwd.c_str());
778
779 switch (retval)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530780 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000781 case PAM_SUCCESS:
782 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000783 return ccSuccess;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000784 }
785 case PAM_AUTHTOK_ERR:
786 {
787 log<level::DEBUG>("Bad authentication token");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000788 return ccInvalidFieldRequest;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000789 }
790 default:
791 {
792 log<level::DEBUG>("Failed to update password",
793 entry("USER-ID=%d", (uint8_t)userId));
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000794 return ccUnspecifiedError;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000795 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530796 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530797}
798
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000799Cc UserAccess::setUserEnabledState(const uint8_t userId,
800 const bool& enabledState)
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530801{
802 if (!isValidUserId(userId))
803 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000804 return ccParmOutOfRange;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530805 }
806 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
807 userLock{*userMutex};
808 UserInfo* userInfo = getUserInfo(userId);
809 std::string userName;
810 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
811 ipmiMaxUserName);
812 if (userName.empty())
813 {
814 log<level::DEBUG>("User name not set / invalid");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000815 return ccUnspecifiedError;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530816 }
817 if (userInfo->userEnabled != enabledState)
818 {
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530819 sdbusplus::message::object_path tempUserPath(userObjBasePath);
820 tempUserPath /= userName;
821 std::string userPath(tempUserPath);
Patrick Venture99d1ba02019-02-21 15:11:24 -0800822 setDbusProperty(bus, getUserServiceName(), userPath, usersInterface,
823 userEnabledProperty, enabledState);
Richard Marian Thomaiyar2fe92822019-03-02 22:07:03 +0530824 userInfo->userEnabled = enabledState;
825 try
826 {
827 writeUserData();
828 }
829 catch (const std::exception& e)
830 {
831 log<level::DEBUG>("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000832 return ccUnspecifiedError;
Richard Marian Thomaiyar2fe92822019-03-02 22:07:03 +0530833 }
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530834 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000835 return ccSuccess;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530836}
837
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000838Cc UserAccess::setUserPayloadAccess(const uint8_t chNum,
839 const uint8_t operation,
840 const uint8_t userId,
841 const PayloadAccess& payloadAccess)
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000842{
843 constexpr uint8_t enable = 0x0;
844 constexpr uint8_t disable = 0x1;
845
846 if (!isValidChannel(chNum))
847 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000848 return ccInvalidFieldRequest;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000849 }
850 if (!isValidUserId(userId))
851 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000852 return ccParmOutOfRange;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000853 }
854 if (operation != enable && operation != disable)
855 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000856 return ccInvalidFieldRequest;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000857 }
858 // Check operation & payloadAccess if required.
859 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
860 userLock{*userMutex};
861 UserInfo* userInfo = getUserInfo(userId);
862
863 if (operation == enable)
864 {
865 userInfo->payloadAccess[chNum].stdPayloadEnables1 |=
866 payloadAccess.stdPayloadEnables1;
867
868 userInfo->payloadAccess[chNum].oemPayloadEnables1 |=
869 payloadAccess.oemPayloadEnables1;
870 }
871 else
872 {
873 userInfo->payloadAccess[chNum].stdPayloadEnables1 &=
874 ~(payloadAccess.stdPayloadEnables1);
875
876 userInfo->payloadAccess[chNum].oemPayloadEnables1 &=
877 ~(payloadAccess.oemPayloadEnables1);
878 }
879
880 try
881 {
882 writeUserData();
883 }
884 catch (const std::exception& e)
885 {
886 log<level::ERR>("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000887 return ccUnspecifiedError;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000888 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000889 return ccSuccess;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000890}
891
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000892Cc UserAccess::setUserPrivilegeAccess(const uint8_t userId, const uint8_t chNum,
893 const UserPrivAccess& privAccess,
894 const bool& otherPrivUpdates)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530895{
896 if (!isValidChannel(chNum))
897 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000898 return ccInvalidFieldRequest;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530899 }
900 if (!isValidUserId(userId))
901 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000902 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530903 }
904 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
905 userLock{*userMutex};
906 UserInfo* userInfo = getUserInfo(userId);
907 std::string userName;
908 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
909 ipmiMaxUserName);
910 if (userName.empty())
911 {
912 log<level::DEBUG>("User name not set / invalid");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000913 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530914 }
915 std::string priv = convertToSystemPrivilege(
916 static_cast<CommandPrivilege>(privAccess.privilege));
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530917 uint8_t syncIndex = getUsrMgmtSyncIndex();
918 if (chNum == syncIndex &&
919 privAccess.privilege != userInfo->userPrivAccess[syncIndex].privilege)
920 {
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530921 sdbusplus::message::object_path tempUserPath(userObjBasePath);
922 tempUserPath /= userName;
923 std::string userPath(tempUserPath);
Patrick Venture99d1ba02019-02-21 15:11:24 -0800924 setDbusProperty(bus, getUserServiceName(), userPath, usersInterface,
925 userPrivProperty, priv);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530926 }
927 userInfo->userPrivAccess[chNum].privilege = privAccess.privilege;
928
929 if (otherPrivUpdates)
930 {
931 userInfo->userPrivAccess[chNum].ipmiEnabled = privAccess.ipmiEnabled;
932 userInfo->userPrivAccess[chNum].linkAuthEnabled =
933 privAccess.linkAuthEnabled;
934 userInfo->userPrivAccess[chNum].accessCallback =
935 privAccess.accessCallback;
936 }
937 try
938 {
939 writeUserData();
940 }
941 catch (const std::exception& e)
942 {
943 log<level::DEBUG>("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000944 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530945 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000946 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530947}
948
949uint8_t UserAccess::getUserId(const std::string& userName)
950{
951 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
952 userLock{*userMutex};
953 checkAndReloadUserData();
954 // user index 0 is reserved, starts with 1
955 size_t usrIndex = 1;
956 for (; usrIndex <= ipmiMaxUsers; ++usrIndex)
957 {
958 std::string curName(
959 reinterpret_cast<char*>(usersTbl.user[usrIndex].userName), 0,
960 ipmiMaxUserName);
961 if (userName == curName)
962 {
963 break; // found the entry
964 }
965 }
966 if (usrIndex > ipmiMaxUsers)
967 {
968 log<level::DEBUG>("User not found",
969 entry("USER_NAME=%s", userName.c_str()));
970 return invalidUserId;
971 }
972
973 return usrIndex;
974}
975
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000976Cc UserAccess::getUserName(const uint8_t userId, std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530977{
978 if (!isValidUserId(userId))
979 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000980 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530981 }
982 UserInfo* userInfo = getUserInfo(userId);
983 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
984 ipmiMaxUserName);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000985 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530986}
987
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +0530988bool UserAccess::isIpmiInAvailableGroupList()
989{
990 if (std::find(availableGroups.begin(), availableGroups.end(),
991 ipmiGrpName) != availableGroups.end())
992 {
993 return true;
994 }
995 if (availableGroups.empty())
996 {
997 // available groups shouldn't be empty, re-query
998 getSystemPrivAndGroups();
999 if (std::find(availableGroups.begin(), availableGroups.end(),
1000 ipmiGrpName) != availableGroups.end())
1001 {
1002 return true;
1003 }
1004 }
1005 return false;
1006}
1007
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001008Cc UserAccess::setUserName(const uint8_t userId, const std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301009{
1010 if (!isValidUserId(userId))
1011 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001012 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301013 }
1014
1015 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1016 userLock{*userMutex};
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301017 std::string oldUser;
1018 getUserName(userId, oldUser);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301019
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001020 if (oldUser == userName)
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +05301021 {
1022 // requesting to set the same user name, return success.
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001023 return ccSuccess;
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +05301024 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001025
1026 bool validUser = isValidUserName(userName);
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +05301027 UserInfo* userInfo = getUserInfo(userId);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001028 if (userName.empty() && !oldUser.empty())
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301029 {
1030 // Delete existing user
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +05301031 sdbusplus::message::object_path tempUserPath(userObjBasePath);
1032 tempUserPath /= oldUser;
1033 std::string userPath(tempUserPath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301034 try
1035 {
1036 auto method = bus.new_method_call(
1037 getUserServiceName().c_str(), userPath.c_str(),
1038 deleteUserInterface, deleteUserMethod);
1039 auto reply = bus.call(method);
1040 }
Patrick Williamsef1259b2021-09-02 09:12:33 -05001041 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301042 {
1043 log<level::DEBUG>("Failed to excute method",
1044 entry("METHOD=%s", deleteUserMethod),
1045 entry("PATH=%s", userPath.c_str()));
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001046 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301047 }
Richard Marian Thomaiyar02710bb2018-11-28 20:42:25 +05301048 deleteUserIndex(userId);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301049 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001050 else if (oldUser.empty() && !userName.empty() && validUser)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301051 {
1052 try
1053 {
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +05301054 if (!isIpmiInAvailableGroupList())
1055 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001056 return ccUnspecifiedError;
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +05301057 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301058 // Create new user
1059 auto method = bus.new_method_call(
1060 getUserServiceName().c_str(), userMgrObjBasePath,
1061 userMgrInterface, createUserMethod);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001062 method.append(userName.c_str(), availableGroups, "", false);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301063 auto reply = bus.call(method);
1064 }
Patrick Williamsef1259b2021-09-02 09:12:33 -05001065 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301066 {
1067 log<level::DEBUG>("Failed to excute method",
1068 entry("METHOD=%s", createUserMethod),
1069 entry("PATH=%s", userMgrObjBasePath));
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001070 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301071 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001072
1073 std::memset(userInfo->userName, 0, sizeof(userInfo->userName));
1074 std::memcpy(userInfo->userName,
1075 static_cast<const void*>(userName.data()), userName.size());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301076 userInfo->userInSystem = true;
1077 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001078 else if (oldUser != userName && validUser)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301079 {
1080 try
1081 {
1082 // User rename
1083 auto method = bus.new_method_call(
1084 getUserServiceName().c_str(), userMgrObjBasePath,
1085 userMgrInterface, renameUserMethod);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001086 method.append(oldUser.c_str(), userName.c_str());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301087 auto reply = bus.call(method);
1088 }
Patrick Williamsef1259b2021-09-02 09:12:33 -05001089 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301090 {
1091 log<level::DEBUG>("Failed to excute method",
1092 entry("METHOD=%s", renameUserMethod),
1093 entry("PATH=%s", userMgrObjBasePath));
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001094 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301095 }
1096 std::fill(static_cast<uint8_t*>(userInfo->userName),
1097 static_cast<uint8_t*>(userInfo->userName) +
1098 sizeof(userInfo->userName),
1099 0);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001100
1101 std::memset(userInfo->userName, 0, sizeof(userInfo->userName));
1102 std::memcpy(userInfo->userName,
1103 static_cast<const void*>(userName.data()), userName.size());
1104
1105 ipmiRenameUserEntryPassword(oldUser, userName);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301106 userInfo->userInSystem = true;
1107 }
1108 else if (!validUser)
1109 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001110 return ccInvalidFieldRequest;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301111 }
1112 try
1113 {
1114 writeUserData();
1115 }
1116 catch (const std::exception& e)
1117 {
1118 log<level::DEBUG>("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001119 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301120 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001121 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301122}
1123
1124static constexpr const char* jsonUserName = "user_name";
1125static constexpr const char* jsonPriv = "privilege";
1126static constexpr const char* jsonIpmiEnabled = "ipmi_enabled";
1127static constexpr const char* jsonLinkAuthEnabled = "link_auth_enabled";
1128static constexpr const char* jsonAccCallbk = "access_callback";
1129static constexpr const char* jsonUserEnabled = "user_enabled";
1130static constexpr const char* jsonUserInSys = "user_in_system";
1131static constexpr const char* jsonFixedUser = "fixed_user_name";
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001132static constexpr const char* payloadEnabledStr = "payload_enabled";
1133static constexpr const char* stdPayloadStr = "std_payload";
1134static constexpr const char* oemPayloadStr = "OEM_payload";
1135
1136/** @brief to construct a JSON object from the given payload access details.
1137 *
1138 * @param[in] stdPayload - stdPayloadEnables1 in a 2D-array. (input)
1139 * @param[in] oemPayload - oemPayloadEnables1 in a 2D-array. (input)
1140 *
1141 * @details Sample output JSON object format :
1142 * "payload_enabled":{
1143 * "OEM_payload0":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1144 * "OEM_payload1":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1145 * "OEM_payload2":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1146 * "OEM_payload3":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1147 * "OEM_payload4":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1148 * "OEM_payload5":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1149 * "OEM_payload6":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1150 * "OEM_payload7":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1151 * "std_payload0":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1152 * "std_payload1":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1153 * "std_payload2":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1154 * "std_payload3":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1155 * "std_payload4":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1156 * "std_payload5":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1157 * "std_payload6":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1158 * "std_payload7":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1159 * }
1160 */
1161static const Json constructJsonPayloadEnables(
1162 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1163 stdPayload,
1164 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1165 oemPayload)
1166{
1167 Json jsonPayloadEnabled;
1168
1169 for (auto payloadNum = 0; payloadNum < payloadsPerByte; payloadNum++)
1170 {
1171 std::ostringstream stdPayloadStream;
1172 std::ostringstream oemPayloadStream;
1173
1174 stdPayloadStream << stdPayloadStr << payloadNum;
1175 oemPayloadStream << oemPayloadStr << payloadNum;
1176
1177 jsonPayloadEnabled.push_back(Json::object_t::value_type(
1178 stdPayloadStream.str(), stdPayload[payloadNum]));
1179
1180 jsonPayloadEnabled.push_back(Json::object_t::value_type(
1181 oemPayloadStream.str(), oemPayload[payloadNum]));
1182 }
1183 return jsonPayloadEnabled;
1184}
1185
1186void UserAccess::readPayloadAccessFromUserInfo(
1187 const UserInfo& userInfo,
1188 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>& stdPayload,
1189 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>& oemPayload)
1190{
1191 for (auto payloadNum = 0; payloadNum < payloadsPerByte; payloadNum++)
1192 {
1193 for (auto chIndex = 0; chIndex < ipmiMaxChannels; chIndex++)
1194 {
1195 stdPayload[payloadNum][chIndex] =
1196 userInfo.payloadAccess[chIndex].stdPayloadEnables1[payloadNum];
1197
1198 oemPayload[payloadNum][chIndex] =
1199 userInfo.payloadAccess[chIndex].oemPayloadEnables1[payloadNum];
1200 }
1201 }
1202}
1203
1204void UserAccess::updatePayloadAccessInUserInfo(
1205 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1206 stdPayload,
Willy Tu11d68892022-01-20 10:37:34 -08001207 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&,
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001208 UserInfo& userInfo)
1209{
1210 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1211 {
1212 // Ensure that reserved/unsupported payloads are marked to zero.
1213 userInfo.payloadAccess[chIndex].stdPayloadEnables1.reset();
1214 userInfo.payloadAccess[chIndex].oemPayloadEnables1.reset();
1215 userInfo.payloadAccess[chIndex].stdPayloadEnables2Reserved.reset();
1216 userInfo.payloadAccess[chIndex].oemPayloadEnables2Reserved.reset();
1217 // Update SOL status as it is the only supported payload currently.
1218 userInfo.payloadAccess[chIndex]
1219 .stdPayloadEnables1[static_cast<uint8_t>(ipmi::PayloadType::SOL)] =
1220 stdPayload[static_cast<uint8_t>(ipmi::PayloadType::SOL)][chIndex];
1221 }
1222}
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301223
1224void UserAccess::readUserData()
1225{
1226 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1227 userLock{*userMutex};
1228
1229 std::ifstream iUsrData(ipmiUserDataFile, std::ios::in | std::ios::binary);
1230 if (!iUsrData.good())
1231 {
1232 log<level::ERR>("Error in reading IPMI user data file");
1233 throw std::ios_base::failure("Error opening IPMI user data file");
1234 }
1235
1236 Json jsonUsersTbl = Json::array();
1237 jsonUsersTbl = Json::parse(iUsrData, nullptr, false);
1238
1239 if (jsonUsersTbl.size() != ipmiMaxUsers)
1240 {
1241 log<level::ERR>(
1242 "Error in reading IPMI user data file - User count issues");
1243 throw std::runtime_error(
1244 "Corrupted IPMI user data file - invalid user count");
1245 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001246
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301247 // user index 0 is reserved, starts with 1
1248 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1249 {
1250 Json userInfo = jsonUsersTbl[usrIndex - 1]; // json array starts with 0.
1251 if (userInfo.is_null())
1252 {
1253 log<level::ERR>("Error in reading IPMI user data file - "
1254 "user info corrupted");
1255 throw std::runtime_error(
1256 "Corrupted IPMI user data file - invalid user info");
1257 }
1258 std::string userName = userInfo[jsonUserName].get<std::string>();
1259 std::strncpy(reinterpret_cast<char*>(usersTbl.user[usrIndex].userName),
1260 userName.c_str(), ipmiMaxUserName);
1261
1262 std::vector<std::string> privilege =
1263 userInfo[jsonPriv].get<std::vector<std::string>>();
1264 std::vector<bool> ipmiEnabled =
1265 userInfo[jsonIpmiEnabled].get<std::vector<bool>>();
1266 std::vector<bool> linkAuthEnabled =
1267 userInfo[jsonLinkAuthEnabled].get<std::vector<bool>>();
1268 std::vector<bool> accessCallback =
1269 userInfo[jsonAccCallbk].get<std::vector<bool>>();
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001270
1271 // Payload Enables Processing.
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001272 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1273 stdPayload = {};
1274 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1275 oemPayload = {};
1276 try
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001277 {
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001278 const auto jsonPayloadEnabled = userInfo.at(payloadEnabledStr);
1279 for (auto payloadNum = 0; payloadNum < payloadsPerByte;
1280 payloadNum++)
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001281 {
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001282 std::ostringstream stdPayloadStream;
1283 std::ostringstream oemPayloadStream;
1284
1285 stdPayloadStream << stdPayloadStr << payloadNum;
1286 oemPayloadStream << oemPayloadStr << payloadNum;
1287
1288 stdPayload[payloadNum] =
1289 jsonPayloadEnabled[stdPayloadStream.str()]
1290 .get<std::array<bool, ipmiMaxChannels>>();
1291 oemPayload[payloadNum] =
1292 jsonPayloadEnabled[oemPayloadStream.str()]
1293 .get<std::array<bool, ipmiMaxChannels>>();
1294
1295 if (stdPayload[payloadNum].size() != ipmiMaxChannels ||
1296 oemPayload[payloadNum].size() != ipmiMaxChannels)
1297 {
1298 log<level::ERR>("Error in reading IPMI user data file - "
1299 "payload properties corrupted");
1300 throw std::runtime_error(
1301 "Corrupted IPMI user data file - payload properties");
1302 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001303 }
1304 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -05001305 catch (const Json::out_of_range& e)
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001306 {
1307 // Key not found in 'userInfo'; possibly an old JSON file. Use
1308 // default values for all payloads, and SOL payload default is true.
1309 stdPayload[static_cast<uint8_t>(ipmi::PayloadType::SOL)].fill(true);
1310 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001311
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301312 if (privilege.size() != ipmiMaxChannels ||
1313 ipmiEnabled.size() != ipmiMaxChannels ||
1314 linkAuthEnabled.size() != ipmiMaxChannels ||
1315 accessCallback.size() != ipmiMaxChannels)
1316 {
1317 log<level::ERR>("Error in reading IPMI user data file - "
1318 "properties corrupted");
1319 throw std::runtime_error(
1320 "Corrupted IPMI user data file - properties");
1321 }
1322 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1323 {
1324 usersTbl.user[usrIndex].userPrivAccess[chIndex].privilege =
1325 static_cast<uint8_t>(
1326 convertToIPMIPrivilege(privilege[chIndex]));
1327 usersTbl.user[usrIndex].userPrivAccess[chIndex].ipmiEnabled =
1328 ipmiEnabled[chIndex];
1329 usersTbl.user[usrIndex].userPrivAccess[chIndex].linkAuthEnabled =
1330 linkAuthEnabled[chIndex];
1331 usersTbl.user[usrIndex].userPrivAccess[chIndex].accessCallback =
1332 accessCallback[chIndex];
1333 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001334 updatePayloadAccessInUserInfo(stdPayload, oemPayload,
1335 usersTbl.user[usrIndex]);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301336 usersTbl.user[usrIndex].userEnabled =
1337 userInfo[jsonUserEnabled].get<bool>();
1338 usersTbl.user[usrIndex].userInSystem =
1339 userInfo[jsonUserInSys].get<bool>();
1340 usersTbl.user[usrIndex].fixedUserName =
1341 userInfo[jsonFixedUser].get<bool>();
1342 }
1343
1344 log<level::DEBUG>("User data read from IPMI data file");
1345 iUsrData.close();
1346 // Update the timestamp
1347 fileLastUpdatedTime = getUpdatedFileTime();
1348 return;
1349}
1350
1351void UserAccess::writeUserData()
1352{
1353 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1354 userLock{*userMutex};
1355
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301356 Json jsonUsersTbl = Json::array();
1357 // user index 0 is reserved, starts with 1
1358 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1359 {
1360 Json jsonUserInfo;
1361 jsonUserInfo[jsonUserName] = std::string(
1362 reinterpret_cast<char*>(usersTbl.user[usrIndex].userName), 0,
1363 ipmiMaxUserName);
1364 std::vector<std::string> privilege(ipmiMaxChannels);
1365 std::vector<bool> ipmiEnabled(ipmiMaxChannels);
1366 std::vector<bool> linkAuthEnabled(ipmiMaxChannels);
1367 std::vector<bool> accessCallback(ipmiMaxChannels);
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001368
1369 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1370 stdPayload;
1371 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1372 oemPayload;
1373
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301374 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; chIndex++)
1375 {
1376 privilege[chIndex] =
1377 convertToSystemPrivilege(static_cast<CommandPrivilege>(
1378 usersTbl.user[usrIndex].userPrivAccess[chIndex].privilege));
1379 ipmiEnabled[chIndex] =
1380 usersTbl.user[usrIndex].userPrivAccess[chIndex].ipmiEnabled;
1381 linkAuthEnabled[chIndex] =
1382 usersTbl.user[usrIndex].userPrivAccess[chIndex].linkAuthEnabled;
1383 accessCallback[chIndex] =
1384 usersTbl.user[usrIndex].userPrivAccess[chIndex].accessCallback;
1385 }
1386 jsonUserInfo[jsonPriv] = privilege;
1387 jsonUserInfo[jsonIpmiEnabled] = ipmiEnabled;
1388 jsonUserInfo[jsonLinkAuthEnabled] = linkAuthEnabled;
1389 jsonUserInfo[jsonAccCallbk] = accessCallback;
1390 jsonUserInfo[jsonUserEnabled] = usersTbl.user[usrIndex].userEnabled;
1391 jsonUserInfo[jsonUserInSys] = usersTbl.user[usrIndex].userInSystem;
1392 jsonUserInfo[jsonFixedUser] = usersTbl.user[usrIndex].fixedUserName;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001393
1394 readPayloadAccessFromUserInfo(usersTbl.user[usrIndex], stdPayload,
1395 oemPayload);
1396 Json jsonPayloadEnabledInfo =
1397 constructJsonPayloadEnables(stdPayload, oemPayload);
1398 jsonUserInfo[payloadEnabledStr] = jsonPayloadEnabledInfo;
1399
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301400 jsonUsersTbl.push_back(jsonUserInfo);
1401 }
1402
Richard Marian Thomaiyar687df402019-05-09 00:16:53 +05301403 static std::string tmpFile{std::string(ipmiUserDataFile) + "_tmp"};
1404 int fd = open(tmpFile.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_SYNC,
1405 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
1406 if (fd < 0)
1407 {
1408 log<level::ERR>("Error in creating temporary IPMI user data file");
1409 throw std::ios_base::failure(
1410 "Error in creating temporary IPMI user data file");
1411 }
1412 const auto& writeStr = jsonUsersTbl.dump();
1413 if (write(fd, writeStr.c_str(), writeStr.size()) !=
1414 static_cast<ssize_t>(writeStr.size()))
1415 {
1416 close(fd);
1417 log<level::ERR>("Error in writing temporary IPMI user data file");
1418 throw std::ios_base::failure(
1419 "Error in writing temporary IPMI user data file");
1420 }
1421 close(fd);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301422
1423 if (std::rename(tmpFile.c_str(), ipmiUserDataFile) != 0)
1424 {
1425 log<level::ERR>("Error in renaming temporary IPMI user data file");
1426 throw std::runtime_error("Error in renaming IPMI user data file");
1427 }
1428 // Update the timestamp
1429 fileLastUpdatedTime = getUpdatedFileTime();
1430 return;
1431}
1432
1433bool UserAccess::addUserEntry(const std::string& userName,
1434 const std::string& sysPriv, const bool& enabled)
1435{
1436 UsersTbl* userData = getUsersTblPtr();
1437 size_t freeIndex = 0xFF;
1438 // user index 0 is reserved, starts with 1
1439 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1440 {
1441 std::string curName(
1442 reinterpret_cast<char*>(userData->user[usrIndex].userName), 0,
1443 ipmiMaxUserName);
1444 if (userName == curName)
1445 {
1446 log<level::DEBUG>("User name exists",
1447 entry("USER_NAME=%s", userName.c_str()));
1448 return false; // user name exists.
1449 }
1450
1451 if ((!userData->user[usrIndex].userInSystem) &&
1452 (userData->user[usrIndex].userName[0] == '\0') &&
1453 (freeIndex == 0xFF))
1454 {
1455 freeIndex = usrIndex;
1456 }
1457 }
1458 if (freeIndex == 0xFF)
1459 {
1460 log<level::ERR>("No empty slots found");
1461 return false;
1462 }
1463 std::strncpy(reinterpret_cast<char*>(userData->user[freeIndex].userName),
1464 userName.c_str(), ipmiMaxUserName);
1465 uint8_t priv =
1466 static_cast<uint8_t>(UserAccess::convertToIPMIPrivilege(sysPriv)) &
1467 privMask;
1468 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1469 {
1470 userData->user[freeIndex].userPrivAccess[chIndex].privilege = priv;
1471 userData->user[freeIndex].userPrivAccess[chIndex].ipmiEnabled = true;
1472 userData->user[freeIndex].userPrivAccess[chIndex].linkAuthEnabled =
1473 true;
1474 userData->user[freeIndex].userPrivAccess[chIndex].accessCallback = true;
1475 }
1476 userData->user[freeIndex].userInSystem = true;
1477 userData->user[freeIndex].userEnabled = enabled;
1478
1479 return true;
1480}
1481
1482void UserAccess::deleteUserIndex(const size_t& usrIdx)
1483{
1484 UsersTbl* userData = getUsersTblPtr();
1485
1486 std::string userName(
1487 reinterpret_cast<char*>(userData->user[usrIdx].userName), 0,
1488 ipmiMaxUserName);
1489 ipmiClearUserEntryPassword(userName);
1490 std::fill(static_cast<uint8_t*>(userData->user[usrIdx].userName),
1491 static_cast<uint8_t*>(userData->user[usrIdx].userName) +
1492 sizeof(userData->user[usrIdx].userName),
1493 0);
1494 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1495 {
1496 userData->user[usrIdx].userPrivAccess[chIndex].privilege = privNoAccess;
1497 userData->user[usrIdx].userPrivAccess[chIndex].ipmiEnabled = false;
1498 userData->user[usrIdx].userPrivAccess[chIndex].linkAuthEnabled = false;
1499 userData->user[usrIdx].userPrivAccess[chIndex].accessCallback = false;
1500 }
1501 userData->user[usrIdx].userInSystem = false;
1502 userData->user[usrIdx].userEnabled = false;
1503 return;
1504}
1505
1506void UserAccess::checkAndReloadUserData()
1507{
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001508 std::timespec updateTime = getUpdatedFileTime();
1509 if ((updateTime.tv_sec != fileLastUpdatedTime.tv_sec ||
1510 updateTime.tv_nsec != fileLastUpdatedTime.tv_nsec) ||
1511 (updateTime.tv_sec == 0 && updateTime.tv_nsec == 0))
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301512 {
1513 std::fill(reinterpret_cast<uint8_t*>(&usersTbl),
1514 reinterpret_cast<uint8_t*>(&usersTbl) + sizeof(usersTbl), 0);
1515 readUserData();
1516 }
1517 return;
1518}
1519
1520UsersTbl* UserAccess::getUsersTblPtr()
1521{
1522 // reload data before using it.
1523 checkAndReloadUserData();
1524 return &usersTbl;
1525}
1526
1527void UserAccess::getSystemPrivAndGroups()
1528{
1529 std::map<std::string, PrivAndGroupType> properties;
1530 try
1531 {
1532 auto method = bus.new_method_call(
1533 getUserServiceName().c_str(), userMgrObjBasePath,
1534 dBusPropertiesInterface, getAllPropertiesMethod);
1535 method.append(userMgrInterface);
1536
1537 auto reply = bus.call(method);
1538 reply.read(properties);
1539 }
Patrick Williamsef1259b2021-09-02 09:12:33 -05001540 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301541 {
1542 log<level::DEBUG>("Failed to excute method",
1543 entry("METHOD=%s", getAllPropertiesMethod),
1544 entry("PATH=%s", userMgrObjBasePath));
1545 return;
1546 }
1547 for (const auto& t : properties)
1548 {
1549 auto key = t.first;
1550 if (key == allPrivProperty)
1551 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001552 availablePrivileges = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301553 }
1554 else if (key == allGrpProperty)
1555 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001556 availableGroups = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301557 }
1558 }
1559 // TODO: Implement Supported Privilege & Groups verification logic
1560 return;
1561}
1562
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001563std::timespec UserAccess::getUpdatedFileTime()
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301564{
1565 struct stat fileStat;
1566 if (stat(ipmiUserDataFile, &fileStat) != 0)
1567 {
1568 log<level::DEBUG>("Error in getting last updated time stamp");
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001569 return std::timespec{0, 0};
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301570 }
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001571 return fileStat.st_mtim;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301572}
1573
1574void UserAccess::getUserProperties(const DbusUserObjProperties& properties,
1575 std::vector<std::string>& usrGrps,
1576 std::string& usrPriv, bool& usrEnabled)
1577{
1578 for (const auto& t : properties)
1579 {
1580 std::string key = t.first;
1581 if (key == userPrivProperty)
1582 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001583 usrPriv = std::get<std::string>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301584 }
1585 else if (key == userGrpProperty)
1586 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001587 usrGrps = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301588 }
1589 else if (key == userEnabledProperty)
1590 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001591 usrEnabled = std::get<bool>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301592 }
1593 }
1594 return;
1595}
1596
1597int UserAccess::getUserObjProperties(const DbusUserObjValue& userObjs,
1598 std::vector<std::string>& usrGrps,
1599 std::string& usrPriv, bool& usrEnabled)
1600{
1601 auto usrObj = userObjs.find(usersInterface);
1602 if (usrObj != userObjs.end())
1603 {
1604 getUserProperties(usrObj->second, usrGrps, usrPriv, usrEnabled);
1605 return 0;
1606 }
1607 return -EIO;
1608}
1609
arun-pmbbe728c2020-01-10 15:18:04 +05301610void UserAccess::cacheUserDataFile()
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301611{
1612 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1613 userLock{*userMutex};
1614 try
1615 {
1616 readUserData();
1617 }
1618 catch (const std::ios_base::failure& e)
1619 { // File is empty, create it for the first time
1620 std::fill(reinterpret_cast<uint8_t*>(&usersTbl),
1621 reinterpret_cast<uint8_t*>(&usersTbl) + sizeof(usersTbl), 0);
1622 // user index 0 is reserved, starts with 1
1623 for (size_t userIndex = 1; userIndex <= ipmiMaxUsers; ++userIndex)
1624 {
1625 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1626 {
1627 usersTbl.user[userIndex].userPrivAccess[chIndex].privilege =
1628 privNoAccess;
Saravanan Palanisamy92d81192019-08-07 18:00:04 +00001629 usersTbl.user[userIndex]
1630 .payloadAccess[chIndex]
1631 .stdPayloadEnables1[static_cast<uint8_t>(
1632 ipmi::PayloadType::SOL)] = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301633 }
1634 }
1635 writeUserData();
1636 }
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001637 // Create lock file if it does not exist
1638 int fd = open(ipmiUserSignalLockFile, O_CREAT | O_TRUNC | O_SYNC,
1639 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
1640 if (fd < 0)
1641 {
1642 log<level::ERR>("Error in creating IPMI user signal lock file");
1643 throw std::ios_base::failure(
1644 "Error in creating temporary IPMI user signal lock file");
1645 }
1646 close(fd);
1647
1648 sigHndlrLock = boost::interprocess::file_lock(ipmiUserSignalLockFile);
arun-pmbbe728c2020-01-10 15:18:04 +05301649 // Register it for single object and single process either netipimd /
1650 // host-ipmid
1651 if (userUpdatedSignal == nullptr && sigHndlrLock.try_lock())
1652 {
1653 log<level::DEBUG>("Registering signal handler");
1654 userUpdatedSignal = std::make_unique<sdbusplus::bus::match_t>(
1655 bus,
1656 sdbusplus::bus::match::rules::type::signal() +
1657 sdbusplus::bus::match::rules::interface(dBusObjManager) +
1658 sdbusplus::bus::match::rules::path(userMgrObjBasePath),
1659 [&](sdbusplus::message::message& msg) {
1660 userUpdatedSignalHandler(*this, msg);
1661 });
1662 userMgrRenamedSignal = std::make_unique<sdbusplus::bus::match_t>(
1663 bus,
1664 sdbusplus::bus::match::rules::type::signal() +
1665 sdbusplus::bus::match::rules::interface(userMgrInterface) +
1666 sdbusplus::bus::match::rules::path(userMgrObjBasePath),
1667 [&](sdbusplus::message::message& msg) {
1668 userUpdatedSignalHandler(*this, msg);
1669 });
1670 userPropertiesSignal = std::make_unique<sdbusplus::bus::match_t>(
1671 bus,
1672 sdbusplus::bus::match::rules::type::signal() +
1673 sdbusplus::bus::match::rules::path_namespace(userObjBasePath) +
1674 sdbusplus::bus::match::rules::interface(
1675 dBusPropertiesInterface) +
1676 sdbusplus::bus::match::rules::member(propertiesChangedSignal) +
1677 sdbusplus::bus::match::rules::argN(0, usersInterface),
1678 [&](sdbusplus::message::message& msg) {
1679 userUpdatedSignalHandler(*this, msg);
1680 });
1681 signalHndlrObject = true;
1682 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301683 std::map<DbusUserObjPath, DbusUserObjValue> managedObjs;
1684 try
1685 {
1686 auto method = bus.new_method_call(getUserServiceName().c_str(),
1687 userMgrObjBasePath, dBusObjManager,
1688 getManagedObjectsMethod);
1689 auto reply = bus.call(method);
1690 reply.read(managedObjs);
1691 }
Patrick Williamsef1259b2021-09-02 09:12:33 -05001692 catch (const sdbusplus::exception::exception& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301693 {
1694 log<level::DEBUG>("Failed to excute method",
1695 entry("METHOD=%s", getSubTreeMethod),
1696 entry("PATH=%s", userMgrObjBasePath));
1697 return;
1698 }
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301699 bool updateRequired = false;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301700 UsersTbl* userData = &usersTbl;
1701 // user index 0 is reserved, starts with 1
1702 for (size_t usrIdx = 1; usrIdx <= ipmiMaxUsers; ++usrIdx)
1703 {
1704 if ((userData->user[usrIdx].userInSystem) &&
1705 (userData->user[usrIdx].userName[0] != '\0'))
1706 {
1707 std::vector<std::string> usrGrps;
1708 std::string usrPriv;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301709
1710 std::string userName(
1711 reinterpret_cast<char*>(userData->user[usrIdx].userName), 0,
1712 ipmiMaxUserName);
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +05301713 sdbusplus::message::object_path tempUserPath(userObjBasePath);
1714 tempUserPath /= userName;
1715 std::string usersPath(tempUserPath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301716
1717 auto usrObj = managedObjs.find(usersPath);
1718 if (usrObj != managedObjs.end())
1719 {
Chen,Yugang0e862fa2019-09-06 11:03:05 +08001720 bool usrEnabled = false;
Patrick Venture3a697ad2019-08-19 11:12:05 -07001721
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301722 // User exist. Lets check and update other fileds
1723 getUserObjProperties(usrObj->second, usrGrps, usrPriv,
1724 usrEnabled);
1725 if (std::find(usrGrps.begin(), usrGrps.end(), ipmiGrpName) ==
1726 usrGrps.end())
1727 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301728 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301729 // Group "ipmi" is removed so lets remove user in IPMI
1730 deleteUserIndex(usrIdx);
1731 }
1732 else
1733 {
1734 // Group "ipmi" is present so lets update other properties
1735 // in IPMI
1736 uint8_t priv =
1737 UserAccess::convertToIPMIPrivilege(usrPriv) & privMask;
1738 // Update all channels priv, only if it is not equivalent to
1739 // getUsrMgmtSyncIndex()
1740 if (userData->user[usrIdx]
1741 .userPrivAccess[getUsrMgmtSyncIndex()]
1742 .privilege != priv)
1743 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301744 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301745 for (size_t chIndex = 0; chIndex < ipmiMaxChannels;
1746 ++chIndex)
1747 {
1748 userData->user[usrIdx]
1749 .userPrivAccess[chIndex]
1750 .privilege = priv;
1751 }
1752 }
1753 if (userData->user[usrIdx].userEnabled != usrEnabled)
1754 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301755 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301756 userData->user[usrIdx].userEnabled = usrEnabled;
1757 }
1758 }
1759
1760 // We are done with this obj. lets delete from MAP
1761 managedObjs.erase(usrObj);
1762 }
1763 else
1764 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301765 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301766 deleteUserIndex(usrIdx);
1767 }
1768 }
1769 }
1770
1771 // Walk through remnaining managedObj users list
1772 // Add them to ipmi data base
1773 for (const auto& usrObj : managedObjs)
1774 {
1775 std::vector<std::string> usrGrps;
1776 std::string usrPriv, userName;
Chen,Yugang0e862fa2019-09-06 11:03:05 +08001777 bool usrEnabled = false;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301778 std::string usrObjPath = std::string(usrObj.first);
1779 if (getUserNameFromPath(usrObj.first.str, userName) != 0)
1780 {
1781 log<level::ERR>("Error in user object path");
1782 continue;
1783 }
1784 getUserObjProperties(usrObj.second, usrGrps, usrPriv, usrEnabled);
1785 // Add 'ipmi' group users
1786 if (std::find(usrGrps.begin(), usrGrps.end(), ipmiGrpName) !=
1787 usrGrps.end())
1788 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301789 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301790 // CREATE NEW USER
1791 if (true != addUserEntry(userName, usrPriv, usrEnabled))
1792 {
1793 break;
1794 }
1795 }
1796 }
1797
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301798 if (updateRequired)
1799 {
1800 // All userData slots update done. Lets write the data
1801 writeUserData();
1802 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301803
1804 return;
1805}
1806} // namespace ipmi