blob: c04133229f902dcf5ccc31276e445b0da8f3c997 [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
Saravanan Palanisamy77381f12019-05-15 22:33:17 +000018#include "channel_layer.hpp"
Johnathan Manteyfd61fc32021-04-08 11:05:38 -070019#include "channel_mgmt.hpp"
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053020
Suryakanth Sekar90b00c72019-01-16 10:37:57 +053021#include <security/pam_appl.h>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053022#include <sys/stat.h>
23#include <unistd.h>
24
25#include <boost/interprocess/sync/named_recursive_mutex.hpp>
26#include <boost/interprocess/sync/scoped_lock.hpp>
Snehalatha Venkatesh745164c2021-06-25 10:02:25 +000027#include <ipmid/types.hpp>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053028#include <nlohmann/json.hpp>
29#include <phosphor-logging/elog-errors.hpp>
George Liu82844ef2024-07-17 17:03:56 +080030#include <phosphor-logging/lg2.hpp>
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053031#include <sdbusplus/bus/match.hpp>
32#include <sdbusplus/server/object.hpp>
33#include <xyz/openbmc_project/Common/error.hpp>
34#include <xyz/openbmc_project/User/Common/error.hpp>
35
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050036#include <cerrno>
37#include <fstream>
38#include <regex>
39#include <variant>
40
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053041namespace 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
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053060static constexpr const char* ipmiUserMutex = "ipmi_usr_mutex";
61static constexpr const char* ipmiMutexCleanupLockFile =
Tyson Tuckerbear8c974f72022-09-19 15:49:06 -070062 "/var/run/ipmi/ipmi_usr_mutex_cleanup";
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +000063static constexpr const char* ipmiUserSignalLockFile =
Tyson Tuckerbear8c974f72022-09-19 15:49:06 -070064 "/var/run/ipmi/ipmi_usr_signal_mutex";
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053065static constexpr const char* ipmiUserDataFile = "/var/lib/ipmi/ipmi_user.json";
66static constexpr const char* ipmiGrpName = "ipmi";
67static constexpr size_t privNoAccess = 0xF;
68static constexpr size_t privMask = 0xF;
69
70// User manager related
Khang D Nguyen078aa6a2025-03-06 00:03:42 +070071static constexpr const char* userMgrService =
72 "xyz.openbmc_project.User.Manager";
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +053073static constexpr const char* userMgrObjBasePath = "/xyz/openbmc_project/user";
74static constexpr const char* userObjBasePath = "/xyz/openbmc_project/user";
75static constexpr const char* userMgrInterface =
76 "xyz.openbmc_project.User.Manager";
77static constexpr const char* usersInterface =
78 "xyz.openbmc_project.User.Attributes";
79static constexpr const char* deleteUserInterface =
80 "xyz.openbmc_project.Object.Delete";
81
82static constexpr const char* createUserMethod = "CreateUser";
83static constexpr const char* deleteUserMethod = "Delete";
84static constexpr const char* renameUserMethod = "RenameUser";
85// User manager signal memebers
86static constexpr const char* userRenamedSignal = "UserRenamed";
87// Mgr interface properties
88static constexpr const char* allPrivProperty = "AllPrivileges";
89static constexpr const char* allGrpProperty = "AllGroups";
90// User interface properties
91static constexpr const char* userPrivProperty = "UserPrivilege";
92static constexpr const char* userGrpProperty = "UserGroups";
93static constexpr const char* userEnabledProperty = "UserEnabled";
94
95static std::array<std::string, (PRIVILEGE_OEM + 1)> ipmiPrivIndex = {
96 "priv-reserved", // PRIVILEGE_RESERVED - 0
97 "priv-callback", // PRIVILEGE_CALLBACK - 1
98 "priv-user", // PRIVILEGE_USER - 2
99 "priv-operator", // PRIVILEGE_OPERATOR - 3
100 "priv-admin", // PRIVILEGE_ADMIN - 4
101 "priv-custom" // PRIVILEGE_OEM - 5
102};
103
104using namespace phosphor::logging;
105using Json = nlohmann::json;
106
Vernon Mauery16b86932019-05-01 08:36:11 -0700107using PrivAndGroupType = std::variant<std::string, std::vector<std::string>>;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530108
109using NoResource =
Willy Tu523e2d12023-09-05 11:36:48 -0700110 sdbusplus::error::xyz::openbmc_project::user::common::NoResource;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530111
112using InternalFailure =
Willy Tu523e2d12023-09-05 11:36:48 -0700113 sdbusplus::error::xyz::openbmc_project::common::InternalFailure;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530114
Lei YU4b0ddb62019-01-25 16:43:50 +0800115std::unique_ptr<sdbusplus::bus::match_t> userUpdatedSignal
116 __attribute__((init_priority(101)));
117std::unique_ptr<sdbusplus::bus::match_t> userMgrRenamedSignal
118 __attribute__((init_priority(101)));
119std::unique_ptr<sdbusplus::bus::match_t> userPropertiesSignal
120 __attribute__((init_priority(101)));
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530121
Patrick Williams5d82f472022-07-22 19:26:53 -0500122void setDbusProperty(sdbusplus::bus_t& bus, const std::string& service,
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530123 const std::string& objPath, const std::string& interface,
124 const std::string& property,
125 const DbusUserPropVariant& value)
126{
127 try
128 {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400129 auto method =
130 bus.new_method_call(service.c_str(), objPath.c_str(),
131 dBusPropertiesInterface, setPropertiesMethod);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530132 method.append(interface, property, value);
133 bus.call(method);
134 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500135 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530136 {
George Liu82844ef2024-07-17 17:03:56 +0800137 lg2::error("Failed to set {PROPERTY}, path: {PATH}, "
138 "interface: {INTERFACE}",
139 "PROPERTY", property, "PATH", objPath, "INTERFACE",
140 interface);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530141 throw;
142 }
143}
144
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530145UserAccess& getUserAccessObject()
146{
147 static UserAccess userAccess;
148 return userAccess;
149}
150
151int getUserNameFromPath(const std::string& path, std::string& userName)
152{
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530153 sdbusplus::message::object_path objPath(path);
154 userName.assign(objPath.filename());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530155 return 0;
156}
157
158void userUpdateHelper(UserAccess& usrAccess, const UserUpdateEvent& userEvent,
159 const std::string& userName, const std::string& priv,
160 const bool& enabled, const std::string& newUserName)
161{
162 UsersTbl* userData = usrAccess.getUsersTblPtr();
163 if (userEvent == UserUpdateEvent::userCreated)
164 {
165 if (usrAccess.addUserEntry(userName, priv, enabled) == false)
166 {
167 return;
168 }
169 }
170 else
171 {
172 // user index 0 is reserved, starts with 1
173 size_t usrIndex = 1;
174 for (; usrIndex <= ipmiMaxUsers; ++usrIndex)
175 {
176 std::string curName(
177 reinterpret_cast<char*>(userData->user[usrIndex].userName), 0,
178 ipmiMaxUserName);
179 if (userName == curName)
180 {
181 break; // found the entry
182 }
183 }
184 if (usrIndex > ipmiMaxUsers)
185 {
George Liu82844ef2024-07-17 17:03:56 +0800186 lg2::debug("User not found for signal, user name: {USER_NAME}, "
187 "user event: {USER_EVENT}",
188 "USER_NAME", userName, "USER_EVENT", userEvent);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530189 return;
190 }
191 switch (userEvent)
192 {
193 case UserUpdateEvent::userDeleted:
194 {
195 usrAccess.deleteUserIndex(usrIndex);
196 break;
197 }
198 case UserUpdateEvent::userPrivUpdated:
199 {
200 uint8_t userPriv =
201 static_cast<uint8_t>(
202 UserAccess::convertToIPMIPrivilege(priv)) &
203 privMask;
204 // Update all channels privileges, only if it is not equivalent
205 // to getUsrMgmtSyncIndex()
206 if (userData->user[usrIndex]
207 .userPrivAccess[UserAccess::getUsrMgmtSyncIndex()]
208 .privilege != userPriv)
209 {
210 for (size_t chIndex = 0; chIndex < ipmiMaxChannels;
211 ++chIndex)
212 {
213 userData->user[usrIndex]
214 .userPrivAccess[chIndex]
215 .privilege = userPriv;
216 }
217 }
218 break;
219 }
220 case UserUpdateEvent::userRenamed:
221 {
222 std::fill(
223 static_cast<uint8_t*>(userData->user[usrIndex].userName),
224 static_cast<uint8_t*>(userData->user[usrIndex].userName) +
225 sizeof(userData->user[usrIndex].userName),
226 0);
227 std::strncpy(
228 reinterpret_cast<char*>(userData->user[usrIndex].userName),
229 newUserName.c_str(), ipmiMaxUserName);
230 ipmiRenameUserEntryPassword(userName, newUserName);
231 break;
232 }
233 case UserUpdateEvent::userStateUpdated:
234 {
235 userData->user[usrIndex].userEnabled = enabled;
236 break;
237 }
238 default:
239 {
George Liu82844ef2024-07-17 17:03:56 +0800240 lg2::error("Unhandled user event: {USER_EVENT}", "USER_EVENT",
241 userEvent);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530242 return;
243 }
244 }
245 }
246 usrAccess.writeUserData();
George Liu82844ef2024-07-17 17:03:56 +0800247 lg2::debug("User event handled successfully, user name: {USER_NAME}, "
248 "user event: {USER_EVENT}",
249 "USER_NAME", userName.c_str(), "USER_EVENT", userEvent);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530250
251 return;
252}
253
Patrick Williams5d82f472022-07-22 19:26:53 -0500254void userUpdatedSignalHandler(UserAccess& usrAccess, sdbusplus::message_t& msg)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530255{
Patrick Williams5d82f472022-07-22 19:26:53 -0500256 static sdbusplus::bus_t bus(ipmid_get_sd_bus_connection());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530257 std::string signal = msg.get_member();
Patrick Venture3a697ad2019-08-19 11:12:05 -0700258 std::string userName, priv, newUserName;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530259 std::vector<std::string> groups;
260 bool enabled = false;
261 UserUpdateEvent userEvent = UserUpdateEvent::reservedEvent;
262 if (signal == intfAddedSignal)
263 {
264 DbusUserObjPath objPath;
265 DbusUserObjValue objValue;
266 msg.read(objPath, objValue);
267 getUserNameFromPath(objPath.str, userName);
268 if (usrAccess.getUserObjProperties(objValue, groups, priv, enabled) !=
269 0)
270 {
271 return;
272 }
273 if (std::find(groups.begin(), groups.end(), ipmiGrpName) ==
274 groups.end())
275 {
276 return;
277 }
278 userEvent = UserUpdateEvent::userCreated;
279 }
280 else if (signal == intfRemovedSignal)
281 {
282 DbusUserObjPath objPath;
283 std::vector<std::string> interfaces;
284 msg.read(objPath, interfaces);
285 getUserNameFromPath(objPath.str, userName);
286 userEvent = UserUpdateEvent::userDeleted;
287 }
288 else if (signal == userRenamedSignal)
289 {
290 msg.read(userName, newUserName);
291 userEvent = UserUpdateEvent::userRenamed;
292 }
293 else if (signal == propertiesChangedSignal)
294 {
295 getUserNameFromPath(msg.get_path(), userName);
296 }
297 else
298 {
George Liu82844ef2024-07-17 17:03:56 +0800299 lg2::error("Unknown user update signal: {SIGNAL}", "SIGNAL", signal);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530300 return;
301 }
302
303 if (signal.empty() || userName.empty() ||
304 (signal == userRenamedSignal && newUserName.empty()))
305 {
George Liu82844ef2024-07-17 17:03:56 +0800306 lg2::error("Invalid inputs received");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530307 return;
308 }
309
310 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
311 userLock{*(usrAccess.userMutex)};
312 usrAccess.checkAndReloadUserData();
313
314 if (signal == propertiesChangedSignal)
315 {
316 std::string intfName;
317 DbusUserObjProperties chProperties;
318 msg.read(intfName, chProperties); // skip reading 3rd argument.
319 for (const auto& prop : chProperties)
320 {
321 userEvent = UserUpdateEvent::reservedEvent;
322 std::string member = prop.first;
323 if (member == userPrivProperty)
324 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700325 priv = std::get<std::string>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530326 userEvent = UserUpdateEvent::userPrivUpdated;
327 }
328 else if (member == userGrpProperty)
329 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700330 groups = std::get<std::vector<std::string>>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530331 userEvent = UserUpdateEvent::userGrpUpdated;
332 }
333 else if (member == userEnabledProperty)
334 {
Vernon Maueryf442e112019-04-09 11:44:36 -0700335 enabled = std::get<bool>(prop.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530336 userEvent = UserUpdateEvent::userStateUpdated;
337 }
338 // Process based on event type.
339 if (userEvent == UserUpdateEvent::userGrpUpdated)
340 {
341 if (std::find(groups.begin(), groups.end(), ipmiGrpName) ==
342 groups.end())
343 {
344 // remove user from ipmi user list.
345 userUpdateHelper(usrAccess, UserUpdateEvent::userDeleted,
346 userName, priv, enabled, newUserName);
347 }
348 else
349 {
350 DbusUserObjProperties properties;
351 try
352 {
353 auto method = bus.new_method_call(
Khang D Nguyen078aa6a2025-03-06 00:03:42 +0700354 userMgrService, msg.get_path(),
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530355 dBusPropertiesInterface, getAllPropertiesMethod);
356 method.append(usersInterface);
357 auto reply = bus.call(method);
358 reply.read(properties);
359 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500360 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530361 {
George Liu82844ef2024-07-17 17:03:56 +0800362 lg2::debug("Failed to excute {METHOD}, path: {PATH}",
363 "METHOD", getAllPropertiesMethod, "PATH",
364 msg.get_path());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530365 return;
366 }
367 usrAccess.getUserProperties(properties, groups, priv,
368 enabled);
369 // add user to ipmi user list.
370 userUpdateHelper(usrAccess, UserUpdateEvent::userCreated,
371 userName, priv, enabled, newUserName);
372 }
373 }
374 else if (userEvent != UserUpdateEvent::reservedEvent)
375 {
376 userUpdateHelper(usrAccess, userEvent, userName, priv, enabled,
377 newUserName);
378 }
379 }
380 }
381 else if (userEvent != UserUpdateEvent::reservedEvent)
382 {
383 userUpdateHelper(usrAccess, userEvent, userName, priv, enabled,
384 newUserName);
385 }
386 return;
387}
388
389UserAccess::~UserAccess()
390{
391 if (signalHndlrObject)
392 {
393 userUpdatedSignal.reset();
394 userMgrRenamedSignal.reset();
395 userPropertiesSignal.reset();
396 sigHndlrLock.unlock();
397 }
398}
399
400UserAccess::UserAccess() : bus(ipmid_get_sd_bus_connection())
401{
402 std::ofstream mutexCleanUpFile;
403 mutexCleanUpFile.open(ipmiMutexCleanupLockFile,
404 std::ofstream::out | std::ofstream::app);
405 if (!mutexCleanUpFile.good())
406 {
George Liu82844ef2024-07-17 17:03:56 +0800407 lg2::debug("Unable to open mutex cleanup file");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530408 return;
409 }
410 mutexCleanUpFile.close();
411 mutexCleanupLock = boost::interprocess::file_lock(ipmiMutexCleanupLockFile);
412 if (mutexCleanupLock.try_lock())
413 {
414 boost::interprocess::named_recursive_mutex::remove(ipmiUserMutex);
415 }
416 mutexCleanupLock.lock_sharable();
417 userMutex = std::make_unique<boost::interprocess::named_recursive_mutex>(
418 boost::interprocess::open_or_create, ipmiUserMutex);
419
arun-pmbbe728c2020-01-10 15:18:04 +0530420 cacheUserDataFile();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530421 getSystemPrivAndGroups();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530422}
423
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530424UserInfo* UserAccess::getUserInfo(const uint8_t userId)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530425{
426 checkAndReloadUserData();
427 return &usersTbl.user[userId];
428}
429
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530430void UserAccess::setUserInfo(const uint8_t userId, UserInfo* userInfo)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530431{
432 checkAndReloadUserData();
433 std::copy(reinterpret_cast<uint8_t*>(userInfo),
434 reinterpret_cast<uint8_t*>(userInfo) + sizeof(*userInfo),
435 reinterpret_cast<uint8_t*>(&usersTbl.user[userId]));
436 writeUserData();
437}
438
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530439bool UserAccess::isValidChannel(const uint8_t chNum)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530440{
441 return (chNum < ipmiMaxChannels);
442}
443
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530444bool UserAccess::isValidUserId(const uint8_t userId)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530445{
446 return ((userId <= ipmiMaxUsers) && (userId != reservedUserId));
447}
448
Richard Marian Thomaiyara45cb342018-12-03 15:08:59 +0530449bool UserAccess::isValidPrivilege(const uint8_t priv)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530450{
jayaprakash Mutyala0e2dbee2019-12-26 13:03:04 +0000451 // Callback privilege is deprecated in OpenBMC
Alexander Filippovfc24fa52022-02-01 14:57:59 +0300452 return isValidPrivLimit(priv);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530453}
454
455uint8_t UserAccess::getUsrMgmtSyncIndex()
456{
Johnathan Manteyfd61fc32021-04-08 11:05:38 -0700457 // Identify the IPMI channel used to assign system user privilege levels
458 // in phosphor-user-manager. The default value is IPMI Channel 1. To
459 // assign a different channel add:
460 // "is_management_nic" : true
461 // into the channel_config.json file describing the assignment of the IPMI
462 // channels. It is only necessary to add the string above to ONE record in
463 // the channel_config.json file. All other records will be automatically
464 // assigned a "false" value.
465 return getChannelConfigObject().getManagementNICID();
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530466}
467
468CommandPrivilege UserAccess::convertToIPMIPrivilege(const std::string& value)
469{
470 auto iter = std::find(ipmiPrivIndex.begin(), ipmiPrivIndex.end(), value);
471 if (iter == ipmiPrivIndex.end())
472 {
473 if (value == "")
474 {
475 return static_cast<CommandPrivilege>(privNoAccess);
476 }
George Liu82844ef2024-07-17 17:03:56 +0800477 lg2::error("Error in converting to IPMI privilege: {PRIV}", "PRIV",
478 value);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530479 throw std::out_of_range("Out of range - convertToIPMIPrivilege");
480 }
481 else
482 {
483 return static_cast<CommandPrivilege>(
484 std::distance(ipmiPrivIndex.begin(), iter));
485 }
486}
487
488std::string UserAccess::convertToSystemPrivilege(const CommandPrivilege& value)
489{
490 if (value == static_cast<CommandPrivilege>(privNoAccess))
491 {
492 return "";
493 }
494 try
495 {
496 return ipmiPrivIndex.at(value);
497 }
498 catch (const std::out_of_range& e)
499 {
George Liu82844ef2024-07-17 17:03:56 +0800500 lg2::error("Error in converting to system privilege: {PRIV}", "PRIV",
501 value);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530502 throw std::out_of_range("Out of range - convertToSystemPrivilege");
503 }
504}
505
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000506bool UserAccess::isValidUserName(const std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530507{
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000508 if (userName.empty())
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530509 {
George Liu82844ef2024-07-17 17:03:56 +0800510 lg2::error("userName is empty");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530511 return false;
512 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530513 if (!std::regex_match(userName.c_str(),
nichanghao.nch0c96fdf2024-01-17 22:13:35 +0800514 std::regex("[a-zA-Z_][a-zA-Z_0-9]*")))
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530515 {
George Liu82844ef2024-07-17 17:03:56 +0800516 lg2::error("Unsupported characters in user name");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530517 return false;
518 }
519 if (userName == "root")
520 {
George Liu82844ef2024-07-17 17:03:56 +0800521 lg2::error("Invalid user name - root");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530522 return false;
523 }
524 std::map<DbusUserObjPath, DbusUserObjValue> properties;
525 try
526 {
Khang D Nguyen078aa6a2025-03-06 00:03:42 +0700527 auto method =
528 bus.new_method_call(userMgrService, userMgrObjBasePath,
529 dBusObjManager, getManagedObjectsMethod);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530530 auto reply = bus.call(method);
531 reply.read(properties);
532 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500533 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530534 {
George Liu82844ef2024-07-17 17:03:56 +0800535 lg2::error("Failed to excute {METHOD}, path: {PATH}", "METHOD",
536 getManagedObjectsMethod, "PATH", userMgrObjBasePath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530537 return false;
538 }
539
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530540 sdbusplus::message::object_path tempUserPath(userObjBasePath);
541 tempUserPath /= userName;
542 std::string usersPath(tempUserPath);
543
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530544 if (properties.find(usersPath) != properties.end())
545 {
George Liu82844ef2024-07-17 17:03:56 +0800546 lg2::debug("Username {USER_NAME} already exists", "USER_NAME",
547 userName);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530548 return false;
549 }
550
551 return true;
552}
553
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530554/** @brief Information exchanged by pam module and application.
555 *
556 * @param[in] numMsg - length of the array of pointers,msg.
557 *
558 * @param[in] msg - pointer to an array of pointers to pam_message structure
559 *
560 * @param[out] resp - struct pam response array
561 *
562 * @param[in] appdataPtr - member of pam_conv structure
563 *
564 * @return the response in pam response structure.
565 */
566
567static int pamFunctionConversation(int numMsg, const struct pam_message** msg,
568 struct pam_response** resp, void* appdataPtr)
569{
570 if (appdataPtr == nullptr)
571 {
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530572 return PAM_CONV_ERR;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530573 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530574
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530575 if (numMsg <= 0 || numMsg >= PAM_MAX_NUM_MSG)
576 {
577 return PAM_CONV_ERR;
578 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530579
580 for (int i = 0; i < numMsg; ++i)
581 {
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530582 /* Ignore all PAM messages except prompting for hidden input */
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530583 if (msg[i]->msg_style != PAM_PROMPT_ECHO_OFF)
584 {
585 continue;
586 }
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530587
588 /* Assume PAM is only prompting for the password as hidden input */
589 /* Allocate memory only when PAM_PROMPT_ECHO_OFF is encounterred */
590
591 char* appPass = reinterpret_cast<char*>(appdataPtr);
592 size_t appPassSize = std::strlen(appPass);
593
594 if (appPassSize >= PAM_MAX_RESP_SIZE)
595 {
596 return PAM_CONV_ERR;
597 }
598
599 char* pass = reinterpret_cast<char*>(malloc(appPassSize + 1));
600 if (pass == nullptr)
601 {
602 return PAM_BUF_ERR;
603 }
604
Patrick Williams1318a5e2024-08-16 15:19:54 -0400605 void* ptr =
606 calloc(static_cast<size_t>(numMsg), sizeof(struct pam_response));
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530607 if (ptr == nullptr)
608 {
609 free(pass);
610 return PAM_BUF_ERR;
611 }
612
613 std::strncpy(pass, appPass, appPassSize + 1);
614
615 *resp = reinterpret_cast<pam_response*>(ptr);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530616 resp[i]->resp = pass;
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530617
618 return PAM_SUCCESS;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530619 }
P Dheeraj Srujan Kumar2aeb1c12021-07-20 04:26:13 +0530620
621 return PAM_CONV_ERR;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530622}
623
624/** @brief Updating the PAM password
625 *
626 * @param[in] username - username in string
627 *
628 * @param[in] password - new password in string
629 *
630 * @return status
631 */
632
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000633int pamUpdatePasswd(const char* username, const char* password)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530634{
635 const struct pam_conv localConversation = {pamFunctionConversation,
636 const_cast<char*>(password)};
Jayanth Othayotha6fb32d2024-12-15 10:55:22 -0600637 pam_handle_t* localAuthHandle = nullptr; // this gets set by pam_start
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530638
Patrick Williams1318a5e2024-08-16 15:19:54 -0400639 int retval =
640 pam_start("passwd", username, &localConversation, &localAuthHandle);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530641
642 if (retval != PAM_SUCCESS)
643 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000644 return retval;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530645 }
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000646
647 retval = pam_chauthtok(localAuthHandle, PAM_SILENT);
648 if (retval != PAM_SUCCESS)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530649 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000650 pam_end(localAuthHandle, retval);
651 return retval;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530652 }
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000653
654 return pam_end(localAuthHandle, PAM_SUCCESS);
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530655}
656
Ayushi Smriti02650d52019-05-15 11:59:09 +0000657bool pamUserCheckAuthenticate(std::string_view username,
658 std::string_view password)
659{
660 const struct pam_conv localConversation = {
661 pamFunctionConversation, const_cast<char*>(password.data())};
662
Jayanth Othayotha6fb32d2024-12-15 10:55:22 -0600663 pam_handle_t* localAuthHandle = nullptr; // this gets set by pam_start
Ayushi Smriti02650d52019-05-15 11:59:09 +0000664
665 if (pam_start("dropbear", username.data(), &localConversation,
666 &localAuthHandle) != PAM_SUCCESS)
667 {
George Liu82844ef2024-07-17 17:03:56 +0800668 lg2::error("User Authentication Failure");
Ayushi Smriti02650d52019-05-15 11:59:09 +0000669 return false;
670 }
671
672 int retval = pam_authenticate(localAuthHandle,
673 PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK);
674
675 if (retval != PAM_SUCCESS)
676 {
George Liu82844ef2024-07-17 17:03:56 +0800677 lg2::debug("pam_authenticate returned failure: {ERROR}", "ERROR",
678 retval);
Ayushi Smriti02650d52019-05-15 11:59:09 +0000679
680 pam_end(localAuthHandle, retval);
681 return false;
682 }
683
684 if (pam_acct_mgmt(localAuthHandle, PAM_DISALLOW_NULL_AUTHTOK) !=
685 PAM_SUCCESS)
686 {
687 pam_end(localAuthHandle, PAM_SUCCESS);
688 return false;
689 }
690
691 if (pam_end(localAuthHandle, PAM_SUCCESS) != PAM_SUCCESS)
692 {
693 return false;
694 }
695 return true;
696}
697
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000698Cc UserAccess::setSpecialUserPassword(const std::string& userName,
Vernon Mauery1e22a0f2021-07-30 13:36:54 -0700699 const SecureString& userPassword)
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530700{
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000701 if (pamUpdatePasswd(userName.c_str(), userPassword.c_str()) != PAM_SUCCESS)
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530702 {
George Liu82844ef2024-07-17 17:03:56 +0800703 lg2::debug("Failed to update password");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000704 return ccUnspecifiedError;
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530705 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000706 return ccSuccess;
Richard Marian Thomaiyar788362c2019-04-14 15:12:47 +0530707}
708
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000709Cc UserAccess::setUserPassword(const uint8_t userId, const char* userPassword)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530710{
711 std::string userName;
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000712 if (ipmiUserGetUserName(userId, userName) != ccSuccess)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530713 {
George Liu82844ef2024-07-17 17:03:56 +0800714 lg2::debug("User Name not found, user Id: {USER_ID}", "USER_ID",
715 userId);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000716 return ccParmOutOfRange;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530717 }
Snehalatha Venkatesh61024d72021-04-08 16:24:39 +0000718
719 ipmi::SecureString passwd;
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530720 passwd.assign(reinterpret_cast<const char*>(userPassword), 0,
721 maxIpmi20PasswordSize);
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000722 int retval = pamUpdatePasswd(userName.c_str(), passwd.c_str());
723
724 switch (retval)
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530725 {
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000726 case PAM_SUCCESS:
727 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000728 return ccSuccess;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000729 }
730 case PAM_AUTHTOK_ERR:
731 {
George Liu82844ef2024-07-17 17:03:56 +0800732 lg2::debug("Bad authentication token");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000733 return ccInvalidFieldRequest;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000734 }
735 default:
736 {
George Liu82844ef2024-07-17 17:03:56 +0800737 lg2::debug("Failed to update password, user Id: {USER_ID}",
738 "USER_ID", userId);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000739 return ccUnspecifiedError;
jayaprakash Mutyala9fc5fa12019-08-29 15:14:06 +0000740 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530741 }
Suryakanth Sekar90b00c72019-01-16 10:37:57 +0530742}
743
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000744Cc UserAccess::setUserEnabledState(const uint8_t userId,
745 const bool& enabledState)
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530746{
747 if (!isValidUserId(userId))
748 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000749 return ccParmOutOfRange;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530750 }
751 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
752 userLock{*userMutex};
753 UserInfo* userInfo = getUserInfo(userId);
754 std::string userName;
755 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
756 ipmiMaxUserName);
757 if (userName.empty())
758 {
George Liu82844ef2024-07-17 17:03:56 +0800759 lg2::debug("User name not set / invalid");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000760 return ccUnspecifiedError;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530761 }
762 if (userInfo->userEnabled != enabledState)
763 {
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530764 sdbusplus::message::object_path tempUserPath(userObjBasePath);
765 tempUserPath /= userName;
766 std::string userPath(tempUserPath);
Khang D Nguyen078aa6a2025-03-06 00:03:42 +0700767 setDbusProperty(bus, userMgrService, userPath, usersInterface,
Patrick Venture99d1ba02019-02-21 15:11:24 -0800768 userEnabledProperty, enabledState);
Richard Marian Thomaiyar2fe92822019-03-02 22:07:03 +0530769 userInfo->userEnabled = enabledState;
770 try
771 {
772 writeUserData();
773 }
774 catch (const std::exception& e)
775 {
George Liu82844ef2024-07-17 17:03:56 +0800776 lg2::debug("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000777 return ccUnspecifiedError;
Richard Marian Thomaiyar2fe92822019-03-02 22:07:03 +0530778 }
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530779 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000780 return ccSuccess;
Richard Marian Thomaiyar282e79b2018-11-13 19:00:58 +0530781}
782
Patrick Williams1318a5e2024-08-16 15:19:54 -0400783Cc UserAccess::setUserPayloadAccess(
784 const uint8_t chNum, const uint8_t operation, const uint8_t userId,
785 const PayloadAccess& payloadAccess)
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000786{
787 constexpr uint8_t enable = 0x0;
788 constexpr uint8_t disable = 0x1;
789
790 if (!isValidChannel(chNum))
791 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000792 return ccInvalidFieldRequest;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000793 }
794 if (!isValidUserId(userId))
795 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000796 return ccParmOutOfRange;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000797 }
798 if (operation != enable && operation != disable)
799 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000800 return ccInvalidFieldRequest;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000801 }
802 // Check operation & payloadAccess if required.
803 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
804 userLock{*userMutex};
805 UserInfo* userInfo = getUserInfo(userId);
806
807 if (operation == enable)
808 {
809 userInfo->payloadAccess[chNum].stdPayloadEnables1 |=
810 payloadAccess.stdPayloadEnables1;
811
812 userInfo->payloadAccess[chNum].oemPayloadEnables1 |=
813 payloadAccess.oemPayloadEnables1;
814 }
815 else
816 {
817 userInfo->payloadAccess[chNum].stdPayloadEnables1 &=
818 ~(payloadAccess.stdPayloadEnables1);
819
820 userInfo->payloadAccess[chNum].oemPayloadEnables1 &=
821 ~(payloadAccess.oemPayloadEnables1);
822 }
823
824 try
825 {
826 writeUserData();
827 }
828 catch (const std::exception& e)
829 {
George Liu82844ef2024-07-17 17:03:56 +0800830 lg2::error("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000831 return ccUnspecifiedError;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000832 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000833 return ccSuccess;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +0000834}
835
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000836Cc UserAccess::setUserPrivilegeAccess(const uint8_t userId, const uint8_t chNum,
837 const UserPrivAccess& privAccess,
838 const bool& otherPrivUpdates)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530839{
840 if (!isValidChannel(chNum))
841 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000842 return ccInvalidFieldRequest;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530843 }
844 if (!isValidUserId(userId))
845 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000846 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530847 }
848 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
849 userLock{*userMutex};
850 UserInfo* userInfo = getUserInfo(userId);
851 std::string userName;
852 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
853 ipmiMaxUserName);
854 if (userName.empty())
855 {
George Liu82844ef2024-07-17 17:03:56 +0800856 lg2::debug("User name not set / invalid");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000857 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530858 }
859 std::string priv = convertToSystemPrivilege(
860 static_cast<CommandPrivilege>(privAccess.privilege));
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530861 uint8_t syncIndex = getUsrMgmtSyncIndex();
862 if (chNum == syncIndex &&
863 privAccess.privilege != userInfo->userPrivAccess[syncIndex].privilege)
864 {
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530865 sdbusplus::message::object_path tempUserPath(userObjBasePath);
866 tempUserPath /= userName;
867 std::string userPath(tempUserPath);
Khang D Nguyen078aa6a2025-03-06 00:03:42 +0700868 setDbusProperty(bus, userMgrService, userPath, usersInterface,
Patrick Venture99d1ba02019-02-21 15:11:24 -0800869 userPrivProperty, priv);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530870 }
871 userInfo->userPrivAccess[chNum].privilege = privAccess.privilege;
872
873 if (otherPrivUpdates)
874 {
875 userInfo->userPrivAccess[chNum].ipmiEnabled = privAccess.ipmiEnabled;
876 userInfo->userPrivAccess[chNum].linkAuthEnabled =
877 privAccess.linkAuthEnabled;
878 userInfo->userPrivAccess[chNum].accessCallback =
879 privAccess.accessCallback;
880 }
881 try
882 {
883 writeUserData();
884 }
885 catch (const std::exception& e)
886 {
George Liu82844ef2024-07-17 17:03:56 +0800887 lg2::debug("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000888 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530889 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000890 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530891}
892
893uint8_t UserAccess::getUserId(const std::string& userName)
894{
895 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
896 userLock{*userMutex};
897 checkAndReloadUserData();
898 // user index 0 is reserved, starts with 1
899 size_t usrIndex = 1;
900 for (; usrIndex <= ipmiMaxUsers; ++usrIndex)
901 {
902 std::string curName(
903 reinterpret_cast<char*>(usersTbl.user[usrIndex].userName), 0,
904 ipmiMaxUserName);
905 if (userName == curName)
906 {
907 break; // found the entry
908 }
909 }
910 if (usrIndex > ipmiMaxUsers)
911 {
George Liu82844ef2024-07-17 17:03:56 +0800912 lg2::debug("Username {USER_NAME} not found", "USER_NAME", userName);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530913 return invalidUserId;
914 }
915
916 return usrIndex;
917}
918
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000919Cc UserAccess::getUserName(const uint8_t userId, std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530920{
921 if (!isValidUserId(userId))
922 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000923 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530924 }
925 UserInfo* userInfo = getUserInfo(userId);
926 userName.assign(reinterpret_cast<char*>(userInfo->userName), 0,
927 ipmiMaxUserName);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000928 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530929}
930
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +0530931bool UserAccess::isIpmiInAvailableGroupList()
932{
933 if (std::find(availableGroups.begin(), availableGroups.end(),
934 ipmiGrpName) != availableGroups.end())
935 {
936 return true;
937 }
938 if (availableGroups.empty())
939 {
940 // available groups shouldn't be empty, re-query
941 getSystemPrivAndGroups();
942 if (std::find(availableGroups.begin(), availableGroups.end(),
943 ipmiGrpName) != availableGroups.end())
944 {
945 return true;
946 }
947 }
948 return false;
949}
950
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000951Cc UserAccess::setUserName(const uint8_t userId, const std::string& userName)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530952{
953 if (!isValidUserId(userId))
954 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000955 return ccParmOutOfRange;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530956 }
957
958 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
959 userLock{*userMutex};
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530960 std::string oldUser;
961 getUserName(userId, oldUser);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530962
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000963 if (oldUser == userName)
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +0530964 {
965 // requesting to set the same user name, return success.
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000966 return ccSuccess;
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +0530967 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000968
969 bool validUser = isValidUserName(userName);
Richard Marian Thomaiyar8550b602018-12-06 13:20:38 +0530970 UserInfo* userInfo = getUserInfo(userId);
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000971 if (userName.empty() && !oldUser.empty())
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530972 {
973 // Delete existing user
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +0530974 sdbusplus::message::object_path tempUserPath(userObjBasePath);
975 tempUserPath /= oldUser;
976 std::string userPath(tempUserPath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530977 try
978 {
Khang D Nguyen078aa6a2025-03-06 00:03:42 +0700979 auto method =
980 bus.new_method_call(userMgrService, userPath.c_str(),
981 deleteUserInterface, deleteUserMethod);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530982 auto reply = bus.call(method);
983 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500984 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530985 {
George Liu82844ef2024-07-17 17:03:56 +0800986 lg2::debug("Failed to excute {METHOD}, path:{PATH}", "METHOD",
987 deleteUserMethod, "PATH", userPath);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000988 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530989 }
Richard Marian Thomaiyar02710bb2018-11-28 20:42:25 +0530990 deleteUserIndex(userId);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530991 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +0000992 else if (oldUser.empty() && !userName.empty() && validUser)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +0530993 {
994 try
995 {
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +0530996 if (!isIpmiInAvailableGroupList())
997 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +0000998 return ccUnspecifiedError;
Richard Marian Thomaiyar489a4ed2020-01-17 11:48:40 +0530999 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301000 // Create new user
Khang D Nguyen078aa6a2025-03-06 00:03:42 +07001001 auto method =
1002 bus.new_method_call(userMgrService, userMgrObjBasePath,
1003 userMgrInterface, createUserMethod);
Alexander Filippovf6f3bb02022-02-01 14:38:40 +03001004 method.append(userName.c_str(), availableGroups,
1005 ipmiPrivIndex[PRIVILEGE_USER], false);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301006 auto reply = bus.call(method);
1007 }
Patrick Williams5d82f472022-07-22 19:26:53 -05001008 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301009 {
George Liu82844ef2024-07-17 17:03:56 +08001010 lg2::debug("Failed to excute {METHOD}, path: {PATH}", "METHOD",
1011 createUserMethod, "PATH", userMgrObjBasePath);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001012 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301013 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001014
1015 std::memset(userInfo->userName, 0, sizeof(userInfo->userName));
1016 std::memcpy(userInfo->userName,
1017 static_cast<const void*>(userName.data()), userName.size());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301018 userInfo->userInSystem = true;
Alexander Filippovf6f3bb02022-02-01 14:38:40 +03001019 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; chIndex++)
1020 {
1021 userInfo->userPrivAccess[chIndex].privilege =
1022 static_cast<uint8_t>(PRIVILEGE_USER);
1023 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301024 }
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001025 else if (oldUser != userName && validUser)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301026 {
1027 try
1028 {
1029 // User rename
Khang D Nguyen078aa6a2025-03-06 00:03:42 +07001030 auto method =
1031 bus.new_method_call(userMgrService, userMgrObjBasePath,
1032 userMgrInterface, renameUserMethod);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001033 method.append(oldUser.c_str(), userName.c_str());
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301034 auto reply = bus.call(method);
1035 }
Patrick Williams5d82f472022-07-22 19:26:53 -05001036 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301037 {
George Liu82844ef2024-07-17 17:03:56 +08001038 lg2::debug("Failed to excute {METHOD}, path: {PATH}", "METHOD",
1039 renameUserMethod, "PATH", userMgrObjBasePath);
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001040 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301041 }
1042 std::fill(static_cast<uint8_t*>(userInfo->userName),
1043 static_cast<uint8_t*>(userInfo->userName) +
1044 sizeof(userInfo->userName),
1045 0);
jayaprakash Mutyala76363302020-02-14 23:50:38 +00001046
1047 std::memset(userInfo->userName, 0, sizeof(userInfo->userName));
1048 std::memcpy(userInfo->userName,
1049 static_cast<const void*>(userName.data()), userName.size());
1050
1051 ipmiRenameUserEntryPassword(oldUser, userName);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301052 userInfo->userInSystem = true;
1053 }
1054 else if (!validUser)
1055 {
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001056 return ccInvalidFieldRequest;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301057 }
1058 try
1059 {
1060 writeUserData();
1061 }
1062 catch (const std::exception& e)
1063 {
George Liu82844ef2024-07-17 17:03:56 +08001064 lg2::debug("Write user data failed");
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001065 return ccUnspecifiedError;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301066 }
NITIN SHARMAb541a5a2019-07-18 12:46:59 +00001067 return ccSuccess;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301068}
1069
1070static constexpr const char* jsonUserName = "user_name";
1071static constexpr const char* jsonPriv = "privilege";
1072static constexpr const char* jsonIpmiEnabled = "ipmi_enabled";
1073static constexpr const char* jsonLinkAuthEnabled = "link_auth_enabled";
1074static constexpr const char* jsonAccCallbk = "access_callback";
1075static constexpr const char* jsonUserEnabled = "user_enabled";
1076static constexpr const char* jsonUserInSys = "user_in_system";
1077static constexpr const char* jsonFixedUser = "fixed_user_name";
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001078static constexpr const char* payloadEnabledStr = "payload_enabled";
1079static constexpr const char* stdPayloadStr = "std_payload";
1080static constexpr const char* oemPayloadStr = "OEM_payload";
1081
1082/** @brief to construct a JSON object from the given payload access details.
1083 *
1084 * @param[in] stdPayload - stdPayloadEnables1 in a 2D-array. (input)
1085 * @param[in] oemPayload - oemPayloadEnables1 in a 2D-array. (input)
1086 *
1087 * @details Sample output JSON object format :
1088 * "payload_enabled":{
1089 * "OEM_payload0":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1090 * "OEM_payload1":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1091 * "OEM_payload2":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1092 * "OEM_payload3":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1093 * "OEM_payload4":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1094 * "OEM_payload5":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1095 * "OEM_payload6":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1096 * "OEM_payload7":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1097 * "std_payload0":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1098 * "std_payload1":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1099 * "std_payload2":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1100 * "std_payload3":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1101 * "std_payload4":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1102 * "std_payload5":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1103 * "std_payload6":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1104 * "std_payload7":[false,...<repeat 'ipmiMaxChannels - 1' times>],
1105 * }
1106 */
1107static const Json constructJsonPayloadEnables(
1108 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1109 stdPayload,
1110 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1111 oemPayload)
1112{
1113 Json jsonPayloadEnabled;
1114
1115 for (auto payloadNum = 0; payloadNum < payloadsPerByte; payloadNum++)
1116 {
1117 std::ostringstream stdPayloadStream;
1118 std::ostringstream oemPayloadStream;
1119
1120 stdPayloadStream << stdPayloadStr << payloadNum;
1121 oemPayloadStream << oemPayloadStr << payloadNum;
1122
1123 jsonPayloadEnabled.push_back(Json::object_t::value_type(
1124 stdPayloadStream.str(), stdPayload[payloadNum]));
1125
1126 jsonPayloadEnabled.push_back(Json::object_t::value_type(
1127 oemPayloadStream.str(), oemPayload[payloadNum]));
1128 }
1129 return jsonPayloadEnabled;
1130}
1131
1132void UserAccess::readPayloadAccessFromUserInfo(
1133 const UserInfo& userInfo,
1134 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>& stdPayload,
1135 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>& oemPayload)
1136{
1137 for (auto payloadNum = 0; payloadNum < payloadsPerByte; payloadNum++)
1138 {
1139 for (auto chIndex = 0; chIndex < ipmiMaxChannels; chIndex++)
1140 {
1141 stdPayload[payloadNum][chIndex] =
1142 userInfo.payloadAccess[chIndex].stdPayloadEnables1[payloadNum];
1143
1144 oemPayload[payloadNum][chIndex] =
1145 userInfo.payloadAccess[chIndex].oemPayloadEnables1[payloadNum];
1146 }
1147 }
1148}
1149
1150void UserAccess::updatePayloadAccessInUserInfo(
1151 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
1152 stdPayload,
Willy Tu11d68892022-01-20 10:37:34 -08001153 const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&,
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001154 UserInfo& userInfo)
1155{
1156 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1157 {
1158 // Ensure that reserved/unsupported payloads are marked to zero.
1159 userInfo.payloadAccess[chIndex].stdPayloadEnables1.reset();
1160 userInfo.payloadAccess[chIndex].oemPayloadEnables1.reset();
1161 userInfo.payloadAccess[chIndex].stdPayloadEnables2Reserved.reset();
1162 userInfo.payloadAccess[chIndex].oemPayloadEnables2Reserved.reset();
1163 // Update SOL status as it is the only supported payload currently.
1164 userInfo.payloadAccess[chIndex]
1165 .stdPayloadEnables1[static_cast<uint8_t>(ipmi::PayloadType::SOL)] =
1166 stdPayload[static_cast<uint8_t>(ipmi::PayloadType::SOL)][chIndex];
1167 }
1168}
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301169
1170void UserAccess::readUserData()
1171{
1172 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1173 userLock{*userMutex};
1174
1175 std::ifstream iUsrData(ipmiUserDataFile, std::ios::in | std::ios::binary);
1176 if (!iUsrData.good())
1177 {
George Liu82844ef2024-07-17 17:03:56 +08001178 lg2::error("Error in reading IPMI user data file");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301179 throw std::ios_base::failure("Error opening IPMI user data file");
1180 }
1181
1182 Json jsonUsersTbl = Json::array();
1183 jsonUsersTbl = Json::parse(iUsrData, nullptr, false);
1184
1185 if (jsonUsersTbl.size() != ipmiMaxUsers)
1186 {
George Liu82844ef2024-07-17 17:03:56 +08001187 lg2::error("Error in reading IPMI user data file - User count issues");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301188 throw std::runtime_error(
1189 "Corrupted IPMI user data file - invalid user count");
1190 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001191
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301192 // user index 0 is reserved, starts with 1
1193 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1194 {
1195 Json userInfo = jsonUsersTbl[usrIndex - 1]; // json array starts with 0.
1196 if (userInfo.is_null())
1197 {
George Liu82844ef2024-07-17 17:03:56 +08001198 lg2::error("Error in reading IPMI user data file - "
1199 "user info corrupted");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301200 throw std::runtime_error(
1201 "Corrupted IPMI user data file - invalid user info");
1202 }
1203 std::string userName = userInfo[jsonUserName].get<std::string>();
1204 std::strncpy(reinterpret_cast<char*>(usersTbl.user[usrIndex].userName),
1205 userName.c_str(), ipmiMaxUserName);
1206
1207 std::vector<std::string> privilege =
1208 userInfo[jsonPriv].get<std::vector<std::string>>();
1209 std::vector<bool> ipmiEnabled =
1210 userInfo[jsonIpmiEnabled].get<std::vector<bool>>();
1211 std::vector<bool> linkAuthEnabled =
1212 userInfo[jsonLinkAuthEnabled].get<std::vector<bool>>();
1213 std::vector<bool> accessCallback =
1214 userInfo[jsonAccCallbk].get<std::vector<bool>>();
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001215
1216 // Payload Enables Processing.
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001217 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1218 stdPayload = {};
1219 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1220 oemPayload = {};
1221 try
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001222 {
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001223 const auto jsonPayloadEnabled = userInfo.at(payloadEnabledStr);
1224 for (auto payloadNum = 0; payloadNum < payloadsPerByte;
1225 payloadNum++)
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001226 {
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001227 std::ostringstream stdPayloadStream;
1228 std::ostringstream oemPayloadStream;
1229
1230 stdPayloadStream << stdPayloadStr << payloadNum;
1231 oemPayloadStream << oemPayloadStr << payloadNum;
1232
1233 stdPayload[payloadNum] =
1234 jsonPayloadEnabled[stdPayloadStream.str()]
1235 .get<std::array<bool, ipmiMaxChannels>>();
1236 oemPayload[payloadNum] =
1237 jsonPayloadEnabled[oemPayloadStream.str()]
1238 .get<std::array<bool, ipmiMaxChannels>>();
1239
1240 if (stdPayload[payloadNum].size() != ipmiMaxChannels ||
1241 oemPayload[payloadNum].size() != ipmiMaxChannels)
1242 {
George Liu82844ef2024-07-17 17:03:56 +08001243 lg2::error("Error in reading IPMI user data file - "
1244 "payload properties corrupted");
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001245 throw std::runtime_error(
1246 "Corrupted IPMI user data file - payload properties");
1247 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001248 }
1249 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -05001250 catch (const Json::out_of_range& e)
Saravanan Palanisamyc86045c2019-07-26 22:52:40 +00001251 {
1252 // Key not found in 'userInfo'; possibly an old JSON file. Use
1253 // default values for all payloads, and SOL payload default is true.
1254 stdPayload[static_cast<uint8_t>(ipmi::PayloadType::SOL)].fill(true);
1255 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001256
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301257 if (privilege.size() != ipmiMaxChannels ||
1258 ipmiEnabled.size() != ipmiMaxChannels ||
1259 linkAuthEnabled.size() != ipmiMaxChannels ||
1260 accessCallback.size() != ipmiMaxChannels)
1261 {
George Liu82844ef2024-07-17 17:03:56 +08001262 lg2::error("Error in reading IPMI user data file - "
1263 "properties corrupted");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301264 throw std::runtime_error(
1265 "Corrupted IPMI user data file - properties");
1266 }
1267 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1268 {
1269 usersTbl.user[usrIndex].userPrivAccess[chIndex].privilege =
1270 static_cast<uint8_t>(
1271 convertToIPMIPrivilege(privilege[chIndex]));
1272 usersTbl.user[usrIndex].userPrivAccess[chIndex].ipmiEnabled =
1273 ipmiEnabled[chIndex];
1274 usersTbl.user[usrIndex].userPrivAccess[chIndex].linkAuthEnabled =
1275 linkAuthEnabled[chIndex];
1276 usersTbl.user[usrIndex].userPrivAccess[chIndex].accessCallback =
1277 accessCallback[chIndex];
1278 }
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001279 updatePayloadAccessInUserInfo(stdPayload, oemPayload,
1280 usersTbl.user[usrIndex]);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301281 usersTbl.user[usrIndex].userEnabled =
1282 userInfo[jsonUserEnabled].get<bool>();
1283 usersTbl.user[usrIndex].userInSystem =
1284 userInfo[jsonUserInSys].get<bool>();
1285 usersTbl.user[usrIndex].fixedUserName =
1286 userInfo[jsonFixedUser].get<bool>();
1287 }
1288
George Liu82844ef2024-07-17 17:03:56 +08001289 lg2::debug("User data read from IPMI data file");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301290 iUsrData.close();
1291 // Update the timestamp
1292 fileLastUpdatedTime = getUpdatedFileTime();
1293 return;
1294}
1295
1296void UserAccess::writeUserData()
1297{
1298 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1299 userLock{*userMutex};
1300
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301301 Json jsonUsersTbl = Json::array();
1302 // user index 0 is reserved, starts with 1
1303 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1304 {
1305 Json jsonUserInfo;
1306 jsonUserInfo[jsonUserName] = std::string(
1307 reinterpret_cast<char*>(usersTbl.user[usrIndex].userName), 0,
1308 ipmiMaxUserName);
1309 std::vector<std::string> privilege(ipmiMaxChannels);
1310 std::vector<bool> ipmiEnabled(ipmiMaxChannels);
1311 std::vector<bool> linkAuthEnabled(ipmiMaxChannels);
1312 std::vector<bool> accessCallback(ipmiMaxChannels);
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001313
1314 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1315 stdPayload;
1316 std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>
1317 oemPayload;
1318
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301319 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; chIndex++)
1320 {
1321 privilege[chIndex] =
1322 convertToSystemPrivilege(static_cast<CommandPrivilege>(
1323 usersTbl.user[usrIndex].userPrivAccess[chIndex].privilege));
1324 ipmiEnabled[chIndex] =
1325 usersTbl.user[usrIndex].userPrivAccess[chIndex].ipmiEnabled;
1326 linkAuthEnabled[chIndex] =
1327 usersTbl.user[usrIndex].userPrivAccess[chIndex].linkAuthEnabled;
1328 accessCallback[chIndex] =
1329 usersTbl.user[usrIndex].userPrivAccess[chIndex].accessCallback;
1330 }
1331 jsonUserInfo[jsonPriv] = privilege;
1332 jsonUserInfo[jsonIpmiEnabled] = ipmiEnabled;
1333 jsonUserInfo[jsonLinkAuthEnabled] = linkAuthEnabled;
1334 jsonUserInfo[jsonAccCallbk] = accessCallback;
1335 jsonUserInfo[jsonUserEnabled] = usersTbl.user[usrIndex].userEnabled;
1336 jsonUserInfo[jsonUserInSys] = usersTbl.user[usrIndex].userInSystem;
1337 jsonUserInfo[jsonFixedUser] = usersTbl.user[usrIndex].fixedUserName;
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001338
1339 readPayloadAccessFromUserInfo(usersTbl.user[usrIndex], stdPayload,
1340 oemPayload);
Patrick Williams1318a5e2024-08-16 15:19:54 -04001341 Json jsonPayloadEnabledInfo =
1342 constructJsonPayloadEnables(stdPayload, oemPayload);
Saravanan Palanisamy77381f12019-05-15 22:33:17 +00001343 jsonUserInfo[payloadEnabledStr] = jsonPayloadEnabledInfo;
1344
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301345 jsonUsersTbl.push_back(jsonUserInfo);
1346 }
1347
Richard Marian Thomaiyar687df402019-05-09 00:16:53 +05301348 static std::string tmpFile{std::string(ipmiUserDataFile) + "_tmp"};
1349 int fd = open(tmpFile.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_SYNC,
1350 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
1351 if (fd < 0)
1352 {
George Liu82844ef2024-07-17 17:03:56 +08001353 lg2::error("Error in creating temporary IPMI user data file");
Richard Marian Thomaiyar687df402019-05-09 00:16:53 +05301354 throw std::ios_base::failure(
1355 "Error in creating temporary IPMI user data file");
1356 }
1357 const auto& writeStr = jsonUsersTbl.dump();
1358 if (write(fd, writeStr.c_str(), writeStr.size()) !=
1359 static_cast<ssize_t>(writeStr.size()))
1360 {
1361 close(fd);
George Liu82844ef2024-07-17 17:03:56 +08001362 lg2::error("Error in writing temporary IPMI user data file");
Richard Marian Thomaiyar687df402019-05-09 00:16:53 +05301363 throw std::ios_base::failure(
1364 "Error in writing temporary IPMI user data file");
1365 }
1366 close(fd);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301367
1368 if (std::rename(tmpFile.c_str(), ipmiUserDataFile) != 0)
1369 {
George Liu82844ef2024-07-17 17:03:56 +08001370 lg2::error("Error in renaming temporary IPMI user data file");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301371 throw std::runtime_error("Error in renaming IPMI user data file");
1372 }
1373 // Update the timestamp
1374 fileLastUpdatedTime = getUpdatedFileTime();
1375 return;
1376}
1377
1378bool UserAccess::addUserEntry(const std::string& userName,
1379 const std::string& sysPriv, const bool& enabled)
1380{
1381 UsersTbl* userData = getUsersTblPtr();
1382 size_t freeIndex = 0xFF;
1383 // user index 0 is reserved, starts with 1
1384 for (size_t usrIndex = 1; usrIndex <= ipmiMaxUsers; ++usrIndex)
1385 {
1386 std::string curName(
1387 reinterpret_cast<char*>(userData->user[usrIndex].userName), 0,
1388 ipmiMaxUserName);
1389 if (userName == curName)
1390 {
George Liu82844ef2024-07-17 17:03:56 +08001391 lg2::debug("Username {USER_NAME} exists", "USER_NAME", userName);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301392 return false; // user name exists.
1393 }
1394
1395 if ((!userData->user[usrIndex].userInSystem) &&
1396 (userData->user[usrIndex].userName[0] == '\0') &&
1397 (freeIndex == 0xFF))
1398 {
1399 freeIndex = usrIndex;
1400 }
1401 }
1402 if (freeIndex == 0xFF)
1403 {
George Liu82844ef2024-07-17 17:03:56 +08001404 lg2::error("No empty slots found");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301405 return false;
1406 }
1407 std::strncpy(reinterpret_cast<char*>(userData->user[freeIndex].userName),
1408 userName.c_str(), ipmiMaxUserName);
1409 uint8_t priv =
1410 static_cast<uint8_t>(UserAccess::convertToIPMIPrivilege(sysPriv)) &
1411 privMask;
1412 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1413 {
1414 userData->user[freeIndex].userPrivAccess[chIndex].privilege = priv;
1415 userData->user[freeIndex].userPrivAccess[chIndex].ipmiEnabled = true;
1416 userData->user[freeIndex].userPrivAccess[chIndex].linkAuthEnabled =
1417 true;
1418 userData->user[freeIndex].userPrivAccess[chIndex].accessCallback = true;
1419 }
1420 userData->user[freeIndex].userInSystem = true;
1421 userData->user[freeIndex].userEnabled = enabled;
1422
1423 return true;
1424}
1425
1426void UserAccess::deleteUserIndex(const size_t& usrIdx)
1427{
1428 UsersTbl* userData = getUsersTblPtr();
1429
1430 std::string userName(
1431 reinterpret_cast<char*>(userData->user[usrIdx].userName), 0,
1432 ipmiMaxUserName);
1433 ipmiClearUserEntryPassword(userName);
1434 std::fill(static_cast<uint8_t*>(userData->user[usrIdx].userName),
1435 static_cast<uint8_t*>(userData->user[usrIdx].userName) +
1436 sizeof(userData->user[usrIdx].userName),
1437 0);
1438 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1439 {
1440 userData->user[usrIdx].userPrivAccess[chIndex].privilege = privNoAccess;
1441 userData->user[usrIdx].userPrivAccess[chIndex].ipmiEnabled = false;
1442 userData->user[usrIdx].userPrivAccess[chIndex].linkAuthEnabled = false;
1443 userData->user[usrIdx].userPrivAccess[chIndex].accessCallback = false;
1444 }
1445 userData->user[usrIdx].userInSystem = false;
1446 userData->user[usrIdx].userEnabled = false;
1447 return;
1448}
1449
1450void UserAccess::checkAndReloadUserData()
1451{
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001452 std::timespec updateTime = getUpdatedFileTime();
1453 if ((updateTime.tv_sec != fileLastUpdatedTime.tv_sec ||
1454 updateTime.tv_nsec != fileLastUpdatedTime.tv_nsec) ||
1455 (updateTime.tv_sec == 0 && updateTime.tv_nsec == 0))
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301456 {
1457 std::fill(reinterpret_cast<uint8_t*>(&usersTbl),
1458 reinterpret_cast<uint8_t*>(&usersTbl) + sizeof(usersTbl), 0);
1459 readUserData();
1460 }
1461 return;
1462}
1463
1464UsersTbl* UserAccess::getUsersTblPtr()
1465{
1466 // reload data before using it.
1467 checkAndReloadUserData();
1468 return &usersTbl;
1469}
1470
1471void UserAccess::getSystemPrivAndGroups()
1472{
1473 std::map<std::string, PrivAndGroupType> properties;
1474 try
1475 {
Khang D Nguyen078aa6a2025-03-06 00:03:42 +07001476 auto method = bus.new_method_call(userMgrService, userMgrObjBasePath,
1477 dBusPropertiesInterface,
1478 getAllPropertiesMethod);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301479 method.append(userMgrInterface);
1480
1481 auto reply = bus.call(method);
1482 reply.read(properties);
1483 }
Patrick Williams5d82f472022-07-22 19:26:53 -05001484 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301485 {
George Liu82844ef2024-07-17 17:03:56 +08001486 lg2::debug("Failed to excute {METHOD}, path: {PATH}", "METHOD",
1487 getAllPropertiesMethod, "PATH", userMgrObjBasePath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301488 return;
1489 }
1490 for (const auto& t : properties)
1491 {
1492 auto key = t.first;
1493 if (key == allPrivProperty)
1494 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001495 availablePrivileges = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301496 }
1497 else if (key == allGrpProperty)
1498 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001499 availableGroups = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301500 }
1501 }
1502 // TODO: Implement Supported Privilege & Groups verification logic
1503 return;
1504}
1505
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001506std::timespec UserAccess::getUpdatedFileTime()
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301507{
1508 struct stat fileStat;
1509 if (stat(ipmiUserDataFile, &fileStat) != 0)
1510 {
George Liu82844ef2024-07-17 17:03:56 +08001511 lg2::debug("Error in getting last updated time stamp");
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001512 return std::timespec{0, 0};
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301513 }
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001514 return fileStat.st_mtim;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301515}
1516
1517void UserAccess::getUserProperties(const DbusUserObjProperties& properties,
1518 std::vector<std::string>& usrGrps,
1519 std::string& usrPriv, bool& usrEnabled)
1520{
1521 for (const auto& t : properties)
1522 {
1523 std::string key = t.first;
1524 if (key == userPrivProperty)
1525 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001526 usrPriv = std::get<std::string>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301527 }
1528 else if (key == userGrpProperty)
1529 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001530 usrGrps = std::get<std::vector<std::string>>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301531 }
1532 else if (key == userEnabledProperty)
1533 {
Vernon Maueryf442e112019-04-09 11:44:36 -07001534 usrEnabled = std::get<bool>(t.second);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301535 }
1536 }
1537 return;
1538}
1539
1540int UserAccess::getUserObjProperties(const DbusUserObjValue& userObjs,
1541 std::vector<std::string>& usrGrps,
1542 std::string& usrPriv, bool& usrEnabled)
1543{
1544 auto usrObj = userObjs.find(usersInterface);
1545 if (usrObj != userObjs.end())
1546 {
1547 getUserProperties(usrObj->second, usrGrps, usrPriv, usrEnabled);
1548 return 0;
1549 }
1550 return -EIO;
1551}
1552
arun-pmbbe728c2020-01-10 15:18:04 +05301553void UserAccess::cacheUserDataFile()
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301554{
1555 boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex>
1556 userLock{*userMutex};
1557 try
1558 {
1559 readUserData();
1560 }
1561 catch (const std::ios_base::failure& e)
1562 { // File is empty, create it for the first time
1563 std::fill(reinterpret_cast<uint8_t*>(&usersTbl),
1564 reinterpret_cast<uint8_t*>(&usersTbl) + sizeof(usersTbl), 0);
1565 // user index 0 is reserved, starts with 1
1566 for (size_t userIndex = 1; userIndex <= ipmiMaxUsers; ++userIndex)
1567 {
1568 for (size_t chIndex = 0; chIndex < ipmiMaxChannels; ++chIndex)
1569 {
1570 usersTbl.user[userIndex].userPrivAccess[chIndex].privilege =
1571 privNoAccess;
Saravanan Palanisamy92d81192019-08-07 18:00:04 +00001572 usersTbl.user[userIndex]
1573 .payloadAccess[chIndex]
1574 .stdPayloadEnables1[static_cast<uint8_t>(
1575 ipmi::PayloadType::SOL)] = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301576 }
1577 }
1578 writeUserData();
1579 }
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001580 // Create lock file if it does not exist
1581 int fd = open(ipmiUserSignalLockFile, O_CREAT | O_TRUNC | O_SYNC,
1582 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
1583 if (fd < 0)
1584 {
George Liu82844ef2024-07-17 17:03:56 +08001585 lg2::error("Error in creating IPMI user signal lock file");
Jayaprakash Mutyala08d3d062021-10-01 16:01:57 +00001586 throw std::ios_base::failure(
1587 "Error in creating temporary IPMI user signal lock file");
1588 }
1589 close(fd);
1590
1591 sigHndlrLock = boost::interprocess::file_lock(ipmiUserSignalLockFile);
George Liu1a2e1502022-07-08 12:20:19 +08001592 // Register it for single object and single process either netipmid /
arun-pmbbe728c2020-01-10 15:18:04 +05301593 // host-ipmid
1594 if (userUpdatedSignal == nullptr && sigHndlrLock.try_lock())
1595 {
George Liu82844ef2024-07-17 17:03:56 +08001596 lg2::debug("Registering signal handler");
arun-pmbbe728c2020-01-10 15:18:04 +05301597 userUpdatedSignal = std::make_unique<sdbusplus::bus::match_t>(
1598 bus,
1599 sdbusplus::bus::match::rules::type::signal() +
1600 sdbusplus::bus::match::rules::interface(dBusObjManager) +
1601 sdbusplus::bus::match::rules::path(userMgrObjBasePath),
Patrick Williams5d82f472022-07-22 19:26:53 -05001602 [&](sdbusplus::message_t& msg) {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001603 userUpdatedSignalHandler(*this, msg);
1604 });
arun-pmbbe728c2020-01-10 15:18:04 +05301605 userMgrRenamedSignal = std::make_unique<sdbusplus::bus::match_t>(
1606 bus,
1607 sdbusplus::bus::match::rules::type::signal() +
1608 sdbusplus::bus::match::rules::interface(userMgrInterface) +
1609 sdbusplus::bus::match::rules::path(userMgrObjBasePath),
Patrick Williams5d82f472022-07-22 19:26:53 -05001610 [&](sdbusplus::message_t& msg) {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001611 userUpdatedSignalHandler(*this, msg);
1612 });
arun-pmbbe728c2020-01-10 15:18:04 +05301613 userPropertiesSignal = std::make_unique<sdbusplus::bus::match_t>(
1614 bus,
1615 sdbusplus::bus::match::rules::type::signal() +
1616 sdbusplus::bus::match::rules::path_namespace(userObjBasePath) +
1617 sdbusplus::bus::match::rules::interface(
1618 dBusPropertiesInterface) +
1619 sdbusplus::bus::match::rules::member(propertiesChangedSignal) +
1620 sdbusplus::bus::match::rules::argN(0, usersInterface),
Patrick Williams5d82f472022-07-22 19:26:53 -05001621 [&](sdbusplus::message_t& msg) {
Patrick Williams1318a5e2024-08-16 15:19:54 -04001622 userUpdatedSignalHandler(*this, msg);
1623 });
arun-pmbbe728c2020-01-10 15:18:04 +05301624 signalHndlrObject = true;
1625 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301626 std::map<DbusUserObjPath, DbusUserObjValue> managedObjs;
1627 try
1628 {
Khang D Nguyen078aa6a2025-03-06 00:03:42 +07001629 auto method =
1630 bus.new_method_call(userMgrService, userMgrObjBasePath,
1631 dBusObjManager, getManagedObjectsMethod);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301632 auto reply = bus.call(method);
1633 reply.read(managedObjs);
1634 }
Patrick Williams5d82f472022-07-22 19:26:53 -05001635 catch (const sdbusplus::exception_t& e)
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301636 {
George Liu82844ef2024-07-17 17:03:56 +08001637 lg2::debug("Failed to excute {METHOD}, path: {PATH}", "METHOD",
1638 getManagedObjectsMethod, "PATH", userMgrObjBasePath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301639 return;
1640 }
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301641 bool updateRequired = false;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301642 UsersTbl* userData = &usersTbl;
1643 // user index 0 is reserved, starts with 1
1644 for (size_t usrIdx = 1; usrIdx <= ipmiMaxUsers; ++usrIdx)
1645 {
1646 if ((userData->user[usrIdx].userInSystem) &&
1647 (userData->user[usrIdx].userName[0] != '\0'))
1648 {
1649 std::vector<std::string> usrGrps;
1650 std::string usrPriv;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301651
1652 std::string userName(
1653 reinterpret_cast<char*>(userData->user[usrIdx].userName), 0,
1654 ipmiMaxUserName);
P Dheeraj Srujan Kumar0ce6a572021-12-13 09:01:55 +05301655 sdbusplus::message::object_path tempUserPath(userObjBasePath);
1656 tempUserPath /= userName;
1657 std::string usersPath(tempUserPath);
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301658
1659 auto usrObj = managedObjs.find(usersPath);
1660 if (usrObj != managedObjs.end())
1661 {
Chen,Yugang0e862fa2019-09-06 11:03:05 +08001662 bool usrEnabled = false;
Patrick Venture3a697ad2019-08-19 11:12:05 -07001663
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301664 // User exist. Lets check and update other fileds
1665 getUserObjProperties(usrObj->second, usrGrps, usrPriv,
1666 usrEnabled);
1667 if (std::find(usrGrps.begin(), usrGrps.end(), ipmiGrpName) ==
1668 usrGrps.end())
1669 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301670 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301671 // Group "ipmi" is removed so lets remove user in IPMI
1672 deleteUserIndex(usrIdx);
1673 }
1674 else
1675 {
1676 // Group "ipmi" is present so lets update other properties
1677 // in IPMI
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -05001678 uint8_t priv = UserAccess::convertToIPMIPrivilege(usrPriv) &
1679 privMask;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301680 // Update all channels priv, only if it is not equivalent to
1681 // getUsrMgmtSyncIndex()
1682 if (userData->user[usrIdx]
1683 .userPrivAccess[getUsrMgmtSyncIndex()]
1684 .privilege != priv)
1685 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301686 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301687 for (size_t chIndex = 0; chIndex < ipmiMaxChannels;
1688 ++chIndex)
1689 {
1690 userData->user[usrIdx]
1691 .userPrivAccess[chIndex]
1692 .privilege = priv;
1693 }
1694 }
1695 if (userData->user[usrIdx].userEnabled != usrEnabled)
1696 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301697 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301698 userData->user[usrIdx].userEnabled = usrEnabled;
1699 }
1700 }
1701
1702 // We are done with this obj. lets delete from MAP
1703 managedObjs.erase(usrObj);
1704 }
1705 else
1706 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301707 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301708 deleteUserIndex(usrIdx);
1709 }
1710 }
1711 }
1712
1713 // Walk through remnaining managedObj users list
1714 // Add them to ipmi data base
1715 for (const auto& usrObj : managedObjs)
1716 {
1717 std::vector<std::string> usrGrps;
1718 std::string usrPriv, userName;
Chen,Yugang0e862fa2019-09-06 11:03:05 +08001719 bool usrEnabled = false;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301720 std::string usrObjPath = std::string(usrObj.first);
1721 if (getUserNameFromPath(usrObj.first.str, userName) != 0)
1722 {
George Liu82844ef2024-07-17 17:03:56 +08001723 lg2::error("Error in user object path");
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301724 continue;
1725 }
1726 getUserObjProperties(usrObj.second, usrGrps, usrPriv, usrEnabled);
1727 // Add 'ipmi' group users
1728 if (std::find(usrGrps.begin(), usrGrps.end(), ipmiGrpName) !=
1729 usrGrps.end())
1730 {
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301731 updateRequired = true;
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301732 // CREATE NEW USER
1733 if (true != addUserEntry(userName, usrPriv, usrEnabled))
1734 {
1735 break;
1736 }
1737 }
1738 }
1739
Richard Marian Thomaiyare004e222019-05-09 00:37:55 +05301740 if (updateRequired)
1741 {
1742 // All userData slots update done. Lets write the data
1743 writeUserData();
1744 }
Richard Marian Thomaiyar5a6b6362018-03-12 23:42:34 +05301745
1746 return;
1747}
1748} // namespace ipmi