• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "enterprise_device_mgr_ability.h"
17 
18 #include <bundle_info.h>
19 #include <bundle_mgr_interface.h>
20 #include <ipc_skeleton.h>
21 #include <iservice_registry.h>
22 #include <message_parcel.h>
23 #include <string_ex.h>
24 #include <system_ability.h>
25 #include <system_ability_definition.h>
26 
27 #include "accesstoken_kit.h"
28 #include "application_state_observer.h"
29 #include "bundle_mgr_proxy.h"
30 #include "common_event_manager.h"
31 #include "common_event_support.h"
32 #include "device_policies_storage_rdb.h"
33 #include "directory_ex.h"
34 #include "edm_constants.h"
35 #include "edm_errors.h"
36 #include "edm_log.h"
37 #include "edm_sys_manager.h"
38 #include "enterprise_admin_connection.h"
39 #include "enterprise_bundle_connection.h"
40 #include "enterprise_conn_manager.h"
41 #include "matching_skills.h"
42 #include "os_account_manager.h"
43 #include "parameters.h"
44 
45 namespace OHOS {
46 namespace EDM {
47 const bool REGISTER_RESULT =
48     SystemAbility::MakeAndRegisterAbility(EnterpriseDeviceMgrAbility::GetInstance().GetRefPtr());
49 
50 const std::string PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN = "ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN";
51 const std::string PERMISSION_SET_ENTERPRISE_INFO = "ohos.permission.SET_ENTERPRISE_INFO";
52 const std::string PERMISSION_ENTERPRISE_SUBSCRIBE_MANAGED_EVENT = "ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT";
53 const std::string PARAM_EDM_ENABLE = "persist.edm.edm_enable";
54 
55 std::mutex EnterpriseDeviceMgrAbility::mutexLock_;
56 
57 sptr<EnterpriseDeviceMgrAbility> EnterpriseDeviceMgrAbility::instance_;
58 
AddCommonEventFuncMap()59 void EnterpriseDeviceMgrAbility::AddCommonEventFuncMap()
60 {
61     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED] =
62         &EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved;
63     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED] =
64         &EnterpriseDeviceMgrAbility::OnCommonEventPackageAdded;
65     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED] =
66         &EnterpriseDeviceMgrAbility::OnCommonEventPackageRemoved;
67 }
68 
AddOnAddSystemAbilityFuncMap()69 void EnterpriseDeviceMgrAbility::AddOnAddSystemAbilityFuncMap()
70 {
71     addSystemAbilityFuncMap_[APP_MGR_SERVICE_ID] = &EnterpriseDeviceMgrAbility::OnAppManagerServiceStart;
72     addSystemAbilityFuncMap_[COMMON_EVENT_SERVICE_ID] = &EnterpriseDeviceMgrAbility::OnCommonEventServiceStart;
73 }
74 
EnterpriseDeviceEventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscribeInfo,EnterpriseDeviceMgrAbility & listener)75 EnterpriseDeviceEventSubscriber::EnterpriseDeviceEventSubscriber(
76     const EventFwk::CommonEventSubscribeInfo &subscribeInfo,
77     EnterpriseDeviceMgrAbility &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {}
78 
OnReceiveEvent(const EventFwk::CommonEventData & data)79 void EnterpriseDeviceEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data)
80 {
81     const std::string action = data.GetWant().GetAction();
82     EDMLOGI("EDM OnReceiveEvent get action: %{public}s", action.c_str());
83     auto func = listener_.commonEventFuncMap_.find(action);
84     if (func != listener_.commonEventFuncMap_.end()) {
85         auto commonEventFunc = func->second;
86         if (commonEventFunc != nullptr) {
87             return (listener_.*commonEventFunc)(data);
88         }
89     } else {
90         EDMLOGW("OnReceiveEvent action is invalid");
91     }
92 }
93 
CreateEnterpriseDeviceEventSubscriber(EnterpriseDeviceMgrAbility & listener)94 std::shared_ptr<EventFwk::CommonEventSubscriber> EnterpriseDeviceMgrAbility::CreateEnterpriseDeviceEventSubscriber(
95     EnterpriseDeviceMgrAbility &listener)
96 {
97     EventFwk::MatchingSkills skill = EventFwk::MatchingSkills();
98     AddCommonEventFuncMap();
99     for (auto &item : commonEventFuncMap_) {
100         skill.AddEvent(item.first);
101         EDMLOGI("CreateEnterpriseDeviceEventSubscriber AddEvent: %{public}s", item.first.c_str());
102     }
103     EventFwk::CommonEventSubscribeInfo info(skill);
104     return std::make_shared<EnterpriseDeviceEventSubscriber>(info, listener);
105 }
106 
OnCommonEventUserRemoved(const EventFwk::CommonEventData & data)107 void EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved(const EventFwk::CommonEventData &data)
108 {
109     int userIdToRemove = data.GetCode();
110     if (userIdToRemove == 0) {
111         return;
112     }
113     EDMLOGI("OnCommonEventUserRemoved");
114     std::lock_guard<std::mutex> autoLock(mutexLock_);
115     // include super admin, need to be removed
116     std::vector<std::shared_ptr<Admin>> userAdmin;
117     adminMgr_->GetAdminByUserId(userIdToRemove, userAdmin);
118     policyMgr_ = GetAndSwitchPolicyManagerByUserId(userIdToRemove);
119     for (auto &item : userAdmin) {
120         if (FAILED(RemoveAdmin(item->adminInfo_.packageName_, userIdToRemove))) {
121             EDMLOGW("EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved remove admin failed packagename = %{public}s",
122                 item->adminInfo_.packageName_.c_str());
123         }
124     }
125     std::vector<std::shared_ptr<Admin>> subAndSuperAdmin;
126     adminMgr_->GetAdminByUserId(DEFAULT_USER_ID, subAndSuperAdmin);
127     for (const auto &subAdmin : subAndSuperAdmin) {
128         if ((subAdmin->GetAdminType() == AdminType::SUB_SUPER_ADMIN || subAdmin->GetAdminType() == AdminType::ENT) &&
129             FAILED(RemoveAdmin(subAdmin->adminInfo_.packageName_, userIdToRemove))) {
130             EDMLOGW("EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved: remove sub and super admin policy failed.");
131         }
132     }
133     policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
134 }
135 
OnCommonEventPackageAdded(const EventFwk::CommonEventData & data)136 void EnterpriseDeviceMgrAbility::OnCommonEventPackageAdded(const EventFwk::CommonEventData &data)
137 {
138     EDMLOGI("OnCommonEventPackageAdded");
139     std::string bundleName = data.GetWant().GetElement().GetBundleName();
140     ConnectAbilityOnSystemEvent(bundleName, ManagedEvent::BUNDLE_ADDED);
141 }
142 
OnCommonEventPackageRemoved(const EventFwk::CommonEventData & data)143 void EnterpriseDeviceMgrAbility::OnCommonEventPackageRemoved(const EventFwk::CommonEventData &data)
144 {
145     EDMLOGI("OnCommonEventPackageRemoved");
146     std::string bundleName = data.GetWant().GetElement().GetBundleName();
147     int32_t userId = data.GetWant().GetIntParam(AppExecFwk::Constants::USER_ID, AppExecFwk::Constants::INVALID_USERID);
148     std::lock_guard<std::mutex> autoLock(mutexLock_);
149     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, userId);
150     if (admin != nullptr) {
151         if (admin->adminInfo_.adminType_ == AdminType::NORMAL) {
152             RemoveAdmin(bundleName, userId);
153         }
154         if (admin->adminInfo_.adminType_ == AdminType::SUB_SUPER_ADMIN && userId == DEFAULT_USER_ID) {
155             RemovePolicyAndAdmin(bundleName);
156         }
157         if (admin->adminInfo_.adminType_ == AdminType::ENT && userId == DEFAULT_USER_ID) {
158             // remove sub-super admin
159             std::vector<std::string> subAdmins;
160             adminMgr_->GetSubSuperAdminsByParentName(bundleName, subAdmins);
161             for (auto const &subAdminName : subAdmins) {
162                 RemovePolicyAndAdmin(subAdminName);
163             }
164             // remove super admin
165             RemovePolicyAndAdmin(bundleName);
166         }
167         if (!adminMgr_->IsAdminExist()) {
168             system::SetParameter(PARAM_EDM_ENABLE, "false");
169         }
170     }
171     ConnectAbilityOnSystemEvent(bundleName, ManagedEvent::BUNDLE_REMOVED);
172 }
173 
ConnectAbilityOnSystemEvent(const std::string & bundleName,ManagedEvent event)174 void EnterpriseDeviceMgrAbility::ConnectAbilityOnSystemEvent(const std::string &bundleName, ManagedEvent event)
175 {
176     std::unordered_map<int32_t, std::vector<std::shared_ptr<Admin>>> subAdmins;
177     adminMgr_->GetAdminBySubscribeEvent(event, subAdmins);
178     if (subAdmins.empty()) {
179         EDMLOGW("Get subscriber by common event failed.");
180         return;
181     }
182     AAFwk::Want want;
183     for (const auto &subAdmin : subAdmins) {
184         for (const auto &it : subAdmin.second) {
185             want.SetElementName(it->adminInfo_.packageName_, it->adminInfo_.className_);
186             std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
187             sptr<IEnterpriseConnection> connection =
188                 manager->CreateBundleConnection(want, static_cast<uint32_t>(event), subAdmin.first, bundleName);
189             manager->ConnectAbility(connection);
190         }
191     }
192 }
193 
GetInstance()194 sptr<EnterpriseDeviceMgrAbility> EnterpriseDeviceMgrAbility::GetInstance()
195 {
196     if (instance_ == nullptr) {
197         std::lock_guard<std::mutex> autoLock(mutexLock_);
198         if (instance_ == nullptr) {
199             EDMLOGD("EnterpriseDeviceMgrAbility:GetInstance instance = new EnterpriseDeviceMgrAbility()");
200             instance_ = new (std::nothrow) EnterpriseDeviceMgrAbility();
201         }
202     }
203     return instance_;
204 }
205 
EnterpriseDeviceMgrAbility()206 EnterpriseDeviceMgrAbility::EnterpriseDeviceMgrAbility() : SystemAbility(ENTERPRISE_DEVICE_MANAGER_SA_ID, true)
207 {
208     EDMLOGI("EnterpriseDeviceMgrAbility:new instance");
209 }
210 
~EnterpriseDeviceMgrAbility()211 EnterpriseDeviceMgrAbility::~EnterpriseDeviceMgrAbility()
212 {
213     instance_ = nullptr;
214 
215     if (adminMgr_) {
216         adminMgr_.reset();
217     }
218 
219     if (pluginMgr_) {
220         pluginMgr_.reset();
221     }
222 
223     if (policyMgr_) {
224         policyMgr_.reset();
225     }
226     EDMLOGD("instance is destroyed");
227 }
228 
Dump(int32_t fd,const std::vector<std::u16string> & args)229 int32_t EnterpriseDeviceMgrAbility::Dump(int32_t fd, const std::vector<std::u16string> &args)
230 {
231     EDMLOGI("EnterpriseDeviceMgrAbility::Dump");
232     if (fd < 0) {
233         EDMLOGE("Dump fd invalid");
234         return ERR_EDM_DUMP_FAILED;
235     }
236     std::string result;
237     result.append("Ohos enterprise device manager service: \n");
238     std::vector<std::string> enabledAdminList;
239     GetEnabledAdmin(AdminType::NORMAL, enabledAdminList);
240     if (enabledAdminList.empty()) {
241         result.append("There is no admin enabled\n");
242     } else {
243         result.append("Enabled admin exist :\n");
244         for (const auto &enabledAdmin : enabledAdminList) {
245             result.append(enabledAdmin);
246             result.append("\n");
247         }
248     }
249     int32_t ret = dprintf(fd, "%s", result.c_str());
250     if (ret < 0) {
251         EDMLOGE("dprintf to dump fd failed");
252         return ERR_EDM_DUMP_FAILED;
253     }
254     return ERR_OK;
255 }
256 
OnStart()257 void EnterpriseDeviceMgrAbility::OnStart()
258 {
259     std::lock_guard<std::mutex> autoLock(mutexLock_);
260     EDMLOGD("EnterpriseDeviceMgrAbility::OnStart() Publish");
261     if (!registerToService_) {
262         if (!Publish(this)) {
263             EDMLOGE("EnterpriseDeviceMgrAbility: res == false");
264             return;
265         }
266         registerToService_ = true;
267     }
268     if (!adminMgr_) {
269         adminMgr_ = AdminManager::GetInstance();
270     }
271     EDMLOGD("create adminMgr_ success");
272     adminMgr_->Init();
273     InitAllPolices();
274 
275     if (!pluginMgr_) {
276         pluginMgr_ = PluginManager::GetInstance();
277     }
278     EDMLOGD("create pluginMgr_ success");
279     pluginMgr_->Init();
280 
281     AddOnAddSystemAbilityFuncMap();
282     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
283     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
284 }
285 
InitAllPolices()286 void EnterpriseDeviceMgrAbility::InitAllPolices()
287 {
288     std::vector<int32_t> userIds;
289     auto devicePolicies = DevicePoliciesStorageRdb::GetInstance();
290     if (devicePolicies == nullptr) {
291         EDMLOGE("OnAddSystemAbility::InitAllPolices:get rdbStore failed.");
292         return;
293     }
294     devicePolicies->QueryAllUserId(userIds);
295     for (auto userId : userIds) {
296         if (userId < DEFAULT_USER_ID) {
297             continue;
298         }
299         GetAndSwitchPolicyManagerByUserId(userId);
300     }
301     policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
302 }
303 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)304 void EnterpriseDeviceMgrAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
305 {
306     EDMLOGD("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
307     auto func = addSystemAbilityFuncMap_.find(systemAbilityId);
308     if (func != addSystemAbilityFuncMap_.end()) {
309         auto memberFunc = func->second;
310         if (memberFunc != nullptr) {
311             return (this->*memberFunc)(systemAbilityId, deviceId);
312         }
313     }
314 }
315 
OnAppManagerServiceStart(int32_t systemAbilityId,const std::string & deviceId)316 void EnterpriseDeviceMgrAbility::OnAppManagerServiceStart(int32_t systemAbilityId, const std::string &deviceId)
317 {
318     EDMLOGI("OnAppManagerServiceStart");
319     std::unordered_map<int32_t, std::vector<std::shared_ptr<Admin>>> subAdmins;
320     adminMgr_->GetAdminBySubscribeEvent(ManagedEvent::APP_START, subAdmins);
321     adminMgr_->GetAdminBySubscribeEvent(ManagedEvent::APP_STOP, subAdmins);
322     if (!subAdmins.empty()) {
323         EDMLOGI("the admin that listened the APP_START or APP_STOP event is existed");
324         SubscribeAppState();
325     }
326 }
327 
OnCommonEventServiceStart(int32_t systemAbilityId,const std::string & deviceId)328 void EnterpriseDeviceMgrAbility::OnCommonEventServiceStart(int32_t systemAbilityId, const std::string &deviceId)
329 {
330     commonEventSubscriber = CreateEnterpriseDeviceEventSubscriber(*this);
331     EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber);
332     EDMLOGI("create commonEventSubscriber success");
333 }
334 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)335 void EnterpriseDeviceMgrAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) {}
336 
OnStop()337 void EnterpriseDeviceMgrAbility::OnStop()
338 {
339     EDMLOGD("EnterpriseDeviceMgrAbility::OnStop()");
340 }
341 
GetAllPermissionsByAdmin(const std::string & bundleInfoName,std::vector<std::string> & permissionList,int32_t userId)342 ErrCode EnterpriseDeviceMgrAbility::GetAllPermissionsByAdmin(const std::string &bundleInfoName,
343     std::vector<std::string> &permissionList, int32_t userId)
344 {
345     bool ret = false;
346     AppExecFwk::BundleInfo bundleInfo;
347     auto bundleManager = GetBundleMgr();
348     permissionList.clear();
349     EDMLOGD("GetAllPermissionsByAdmin GetBundleInfo: bundleInfoName %{public}s userid %{public}d",
350         bundleInfoName.c_str(), userId);
351     ret = bundleManager->GetBundleInfo(bundleInfoName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION,
352         bundleInfo, userId);
353     if (!ret) {
354         EDMLOGW("GetAllPermissionsByAdmin: GetBundleInfo failed %{public}d", ret);
355         return ERR_EDM_PARAM_ERROR;
356     }
357     std::vector<std::string> reqPermission = bundleInfo.reqPermissions;
358     if (reqPermission.empty()) {
359         EDMLOGW("GetAllPermissionsByAdmin: bundleInfo reqPermissions empty");
360         return ERR_OK;
361     }
362 
363     std::vector<EdmPermission> edmPermissions;
364     ErrCode code = adminMgr_->GetReqPermission(reqPermission, edmPermissions);
365     if (SUCCEEDED(code)) {
366         for (const auto &perm : edmPermissions) {
367             permissionList.push_back(perm.getPermissionName());
368         }
369     }
370     return ERR_OK;
371 }
372 
GetAppMgr()373 sptr<AppExecFwk::IAppMgr> EnterpriseDeviceMgrAbility::GetAppMgr()
374 {
375     auto remoteObject = EdmSysManager::GetRemoteObjectOfSystemAbility(OHOS::APP_MGR_SERVICE_ID);
376     return iface_cast<AppExecFwk::IAppMgr>(remoteObject);
377 }
378 
GetBundleMgr()379 sptr<AppExecFwk::IBundleMgr> EnterpriseDeviceMgrAbility::GetBundleMgr()
380 {
381     auto remoteObject = EdmSysManager::GetRemoteObjectOfSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
382     sptr<AppExecFwk::IBundleMgr> proxy = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
383     return proxy;
384 }
385 
SubscribeAppState()386 bool EnterpriseDeviceMgrAbility::SubscribeAppState()
387 {
388     if (appStateObserver_) {
389         EDMLOGD("appStateObserver has subscribed");
390         return true;
391     }
392     sptr<AppExecFwk::IAppMgr> appMgr = GetAppMgr();
393     if (!appMgr) {
394         EDMLOGE("GetAppMgr failed");
395         return false;
396     }
397     appStateObserver_ = new (std::nothrow) ApplicationStateObserver(*this);
398     if (!appStateObserver_) {
399         EDMLOGE("new ApplicationStateObserver failed");
400         return false;
401     }
402     if (appMgr->RegisterApplicationStateObserver(appStateObserver_) != ERR_OK) {
403         EDMLOGE("RegisterApplicationStateObserver fail!");
404         appStateObserver_.clear();
405         appStateObserver_ = nullptr;
406         return false;
407     }
408     return true;
409 }
410 
UnsubscribeAppState()411 bool EnterpriseDeviceMgrAbility::UnsubscribeAppState()
412 {
413     if (!appStateObserver_) {
414         EDMLOGD("appStateObserver has subscribed");
415         return true;
416     }
417     std::unordered_map<int32_t, std::vector<std::shared_ptr<Admin>>> subAdmins;
418     adminMgr_->GetAdminBySubscribeEvent(ManagedEvent::APP_START, subAdmins);
419     adminMgr_->GetAdminBySubscribeEvent(ManagedEvent::APP_STOP, subAdmins);
420     if (!subAdmins.empty()) {
421         return true;
422     }
423     sptr<AppExecFwk::IAppMgr> appMgr = GetAppMgr();
424     if (!appMgr || appMgr->UnregisterApplicationStateObserver(appStateObserver_) != ERR_OK) {
425         EDMLOGE("UnregisterApplicationStateObserver fail!");
426         return false;
427     }
428     appStateObserver_.clear();
429     appStateObserver_ = nullptr;
430     return true;
431 }
432 
VerifyCallingPermission(const std::string & permissionName)433 bool EnterpriseDeviceMgrAbility::VerifyCallingPermission(const std::string &permissionName)
434 {
435     EDMLOGD("VerifyCallingPermission permission %{public}s", permissionName.c_str());
436     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
437     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
438     if (ret == Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
439         EDMLOGI("permission %{public}s: PERMISSION_GRANTED", permissionName.c_str());
440         return true;
441     }
442     EDMLOGW("verify AccessToken failed");
443     return false;
444 }
445 
VerifyEnableAdminCondition(AppExecFwk::ElementName & admin,AdminType type,int32_t userId)446 ErrCode EnterpriseDeviceMgrAbility::VerifyEnableAdminCondition(AppExecFwk::ElementName &admin, AdminType type,
447     int32_t userId)
448 {
449     if (type == AdminType::UNKNOWN) {
450         EDMLOGW("EnableAdmin: admin type is invalid.");
451         return ERR_EDM_ADD_ADMIN_FAILED;
452     }
453     if (type == AdminType::ENT && userId != DEFAULT_USER_ID) {
454         EDMLOGW("EnableAdmin: Super admin can only be enabled in default user.");
455         return ERR_EDM_ADD_ADMIN_FAILED;
456     }
457 
458     std::shared_ptr<Admin> existAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
459     if (existAdmin != nullptr) {
460         if (existAdmin->GetAdminType() == AdminType::SUB_SUPER_ADMIN) {
461             EDMLOGW("EnableAdmin: sub-super admin can not be enabled as a normal or super admin.");
462             return ERR_EDM_ADD_ADMIN_FAILED;
463         }
464         if (existAdmin->GetAdminType() == AdminType::ENT && (type != AdminType::ENT || userId != DEFAULT_USER_ID)) {
465             EDMLOGW("EnableAdmin: an exist super admin can't be enabled twice with different role or user id.");
466             return ERR_EDM_ADD_ADMIN_FAILED;
467         }
468         /* An application can't be enabled twice with different ability name */
469         if (existAdmin->adminInfo_.className_ != admin.GetAbilityName()) {
470             EDMLOGW("EnableAdmin: There is another admin ability enabled with the same package name.");
471             return ERR_EDM_ADD_ADMIN_FAILED;
472         }
473     }
474     if (type == AdminType::ENT && adminMgr_->IsSuperAdminExist()) {
475         if (existAdmin == nullptr || existAdmin->adminInfo_.adminType_ != AdminType::ENT) {
476             EDMLOGW("EnableAdmin: There is another super admin enabled.");
477             return ERR_EDM_ADD_ADMIN_FAILED;
478         }
479     }
480     return ERR_OK;
481 }
482 
EnableAdmin(AppExecFwk::ElementName & admin,EntInfo & entInfo,AdminType type,int32_t userId)483 ErrCode EnterpriseDeviceMgrAbility::EnableAdmin(AppExecFwk::ElementName &admin, EntInfo &entInfo, AdminType type,
484     int32_t userId)
485 {
486     EDMLOGD("EnterpriseDeviceMgrAbility::EnableAdmin user id = %{public}d", userId);
487     std::lock_guard<std::mutex> autoLock(mutexLock_);
488     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
489         EDMLOGW("EnterpriseDeviceMgrAbility::EnableAdmin check permission failed");
490         return EdmReturnErrCode::PERMISSION_DENIED;
491     }
492     std::vector<AppExecFwk::ExtensionAbilityInfo> abilityInfo;
493     auto bundleManager = GetBundleMgr();
494     if (!bundleManager) {
495         EDMLOGW("can not get iBundleMgr");
496         return EdmReturnErrCode::SYSTEM_ABNORMALLY;
497     }
498     AAFwk::Want want;
499     want.SetElement(admin);
500     if (!bundleManager->QueryExtensionAbilityInfos(want, AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN,
501         AppExecFwk::ExtensionAbilityInfoFlag::GET_EXTENSION_INFO_WITH_PERMISSION, userId, abilityInfo) ||
502         abilityInfo.empty()) {
503         EDMLOGW("EnableAdmin: QueryExtensionAbilityInfos failed");
504         return EdmReturnErrCode::COMPONENT_INVALID;
505     }
506     if (FAILED(VerifyEnableAdminCondition(admin, type, userId))) {
507         EDMLOGW("EnableAdmin: VerifyEnableAdminCondition failed.");
508         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
509     }
510 
511     /* Get all request and registered permissions */
512     std::vector<std::string> permissionList;
513     if (FAILED(GetAllPermissionsByAdmin(admin.GetBundleName(), permissionList, userId))) {
514         EDMLOGW("EnableAdmin: GetAllPermissionsByAdmin failed");
515         return EdmReturnErrCode::COMPONENT_INVALID;
516     }
517     /* Filter permissions with AdminType, such as NORMAL can't request super permission */
518     if (FAILED(adminMgr_->GetGrantedPermission(permissionList, type))) {
519         EDMLOGW("EnableAdmin: GetGrantedPermission failed");
520         // permission verify, should throw exception if failed
521         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
522     }
523     if (FAILED(adminMgr_->SetAdminValue(abilityInfo.at(0), entInfo, type, permissionList, userId))) {
524         EDMLOGE("EnableAdmin: SetAdminValue failed.");
525         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
526     }
527     system::SetParameter(PARAM_EDM_ENABLE, "true");
528     EDMLOGI("EnableAdmin: SetAdminValue success %{public}s, type:%{public}d", admin.GetBundleName().c_str(),
529         static_cast<uint32_t>(type));
530     AAFwk::Want connectWant;
531     connectWant.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
532     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
533     sptr<IEnterpriseConnection> connection =
534         manager->CreateAdminConnection(connectWant, IEnterpriseAdmin::COMMAND_ON_ADMIN_ENABLED, userId);
535     manager->ConnectAbility(connection);
536     return ERR_OK;
537 }
538 
RemoveAdminItem(const std::string & adminName,const std::string & policyName,const std::string & policyValue,int32_t userId)539 ErrCode EnterpriseDeviceMgrAbility::RemoveAdminItem(const std::string &adminName, const std::string &policyName,
540     const std::string &policyValue, int32_t userId)
541 {
542     ErrCode ret;
543     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByPolicyName(policyName);
544     if (plugin == nullptr) {
545         EDMLOGW("RemoveAdminItem: Get plugin by policy failed: %{public}s\n", policyName.c_str());
546         return ERR_EDM_GET_PLUGIN_MGR_FAILED;
547     }
548     if ((ret = plugin->OnAdminRemove(adminName, policyValue, userId)) != ERR_OK) {
549         EDMLOGW("RemoveAdminItem: OnAdminRemove failed, admin:%{public}s, value:%{public}s, res:%{public}d\n",
550             adminName.c_str(), policyValue.c_str(), ret);
551     }
552     if (plugin->NeedSavePolicy()) {
553         std::string mergedPolicyData;
554         if ((ret = plugin->MergePolicyData(adminName, mergedPolicyData)) != ERR_OK) {
555             EDMLOGW("RemoveAdminItem: Get admin by policy name failed: %{public}s, ErrCode:%{public}d\n",
556                 policyName.c_str(), ret);
557         }
558 
559         ErrCode setRet = ERR_OK;
560         std::unordered_map<std::string, std::string> adminListMap;
561         ret = policyMgr_->GetAdminByPolicyName(policyName, adminListMap);
562         if ((ret == ERR_EDM_POLICY_NOT_FOUND) || adminListMap.empty()) {
563             setRet = policyMgr_->SetPolicy("", policyName, "", "");
564         } else {
565             setRet = policyMgr_->SetPolicy(adminName, policyName, "", mergedPolicyData);
566         }
567 
568         if (FAILED(setRet)) {
569             EDMLOGW("RemoveAdminItem: DeleteAdminPolicy failed, admin:%{public}s, policy:%{public}s, res:%{public}d\n",
570                 adminName.c_str(), policyName.c_str(), ret);
571             return ERR_EDM_DEL_ADMIN_FAILED;
572         }
573     }
574     plugin->OnAdminRemoveDone(adminName, policyValue, userId);
575     return ERR_OK;
576 }
577 
RemoveAdmin(const std::string & adminName,int32_t userId)578 ErrCode EnterpriseDeviceMgrAbility::RemoveAdmin(const std::string &adminName, int32_t userId)
579 {
580     EDMLOGD("RemoveAdmin %{public}s, user id = %{public}d", adminName.c_str(), userId);
581     std::unordered_map<std::string, std::string> policyItems;
582     policyMgr_->GetAllPolicyByAdmin(adminName, policyItems);
583     for (const auto &policyItem : policyItems) {
584         std::string policyItemName = policyItem.first;
585         std::string policyItemValue = policyItem.second;
586         EDMLOGD("RemoveAdmin: RemoveAdminItem policyName:%{public}s,policyValue:%{public}s", policyItemName.c_str(),
587             policyItemValue.c_str());
588         if (RemoveAdminItem(adminName, policyItemName, policyItemValue, userId) != ERR_OK) {
589             return ERR_EDM_DEL_ADMIN_FAILED;
590         }
591     }
592 
593     if (adminMgr_->IsSuperOrSubSuperAdmin(adminName) && userId != DEFAULT_USER_ID) {
594         EDMLOGI("Remove super admin %{public}s and user id = %{public}d", adminName.c_str(), userId);
595         return ERR_OK;
596     }
597 
598     bool shouldUnsubscribeAppState = ShouldUnsubscribeAppState(adminName, userId);
599     if (adminMgr_->DeleteAdmin(adminName, userId) != ERR_OK) {
600         return ERR_EDM_DEL_ADMIN_FAILED;
601     }
602     if (shouldUnsubscribeAppState) {
603         UnsubscribeAppState();
604     }
605     return ERR_OK;
606 }
607 
RemovePolicyAndAdmin(const std::string & bundleName)608 ErrCode EnterpriseDeviceMgrAbility::RemovePolicyAndAdmin(const std::string &bundleName)
609 {
610     for (auto it = policyMgrMap_.rbegin(); it != policyMgrMap_.rend(); ++it) {
611         EDMLOGD("RemovePolicyAndAdmin: policyMgrMap_ it->first %{public}d", it->first);
612         policyMgr_ = GetAndSwitchPolicyManagerByUserId(it->first);
613         if (FAILED(RemoveAdmin(bundleName, it->first))) {
614             policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
615             return ERR_EDM_DEL_ADMIN_FAILED;
616         }
617     }
618     policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
619     return ERR_OK;
620 }
621 
ShouldUnsubscribeAppState(const std::string & adminName,int32_t userId)622 bool EnterpriseDeviceMgrAbility::ShouldUnsubscribeAppState(const std::string &adminName, int32_t userId)
623 {
624     std::shared_ptr<Admin> adminPtr = adminMgr_->GetAdminByPkgName(adminName, userId);
625     return std::any_of(adminPtr->adminInfo_.managedEvents_.begin(), adminPtr->adminInfo_.managedEvents_.end(),
626         [](ManagedEvent event) { return event == ManagedEvent::APP_START || event == ManagedEvent::APP_STOP; });
627 }
628 
DisableAdmin(AppExecFwk::ElementName & admin,int32_t userId)629 ErrCode EnterpriseDeviceMgrAbility::DisableAdmin(AppExecFwk::ElementName &admin, int32_t userId)
630 {
631     EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin user id = %{public}d", userId);
632     std::lock_guard<std::mutex> autoLock(mutexLock_);
633     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
634         EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin check permission failed");
635         return EdmReturnErrCode::PERMISSION_DENIED;
636     }
637 
638     std::shared_ptr<Admin> adminPtr = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
639     if (adminPtr == nullptr) {
640         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
641     }
642     if (adminPtr->adminInfo_.adminType_ != AdminType::NORMAL) {
643         EDMLOGW("DisableAdmin: only remove normal admin.");
644         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
645     }
646 
647     if (FAILED(RemoveAdmin(admin.GetBundleName(), userId))) {
648         EDMLOGW("DisableAdmin: disable admin failed.");
649         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
650     }
651     if (!adminMgr_->IsAdminExist()) {
652         system::SetParameter(PARAM_EDM_ENABLE, "false");
653     }
654     AAFwk::Want want;
655     want.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
656     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
657     sptr<IEnterpriseConnection> connection =
658         manager->CreateAdminConnection(want, IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, userId);
659     manager->ConnectAbility(connection);
660     return ERR_OK;
661 }
662 
CheckCallingUid(const std::string & bundleName)663 ErrCode EnterpriseDeviceMgrAbility::CheckCallingUid(const std::string &bundleName)
664 {
665     // super admin can be removed by itself
666     int uid = GetCallingUid();
667     auto bundleManager = GetBundleMgr();
668     std::string callingBundleName;
669     if (bundleManager->GetNameForUid(uid, callingBundleName) != ERR_OK) {
670         EDMLOGW("CheckCallingUid failed: get bundleName for uid %{public}d fail.", uid);
671         return ERR_EDM_PERMISSION_ERROR;
672     }
673     if (bundleName == callingBundleName) {
674         return ERR_OK;
675     }
676     EDMLOGW("CheckCallingUid failed: only the app %{public}s can remove itself.", callingBundleName.c_str());
677     return ERR_EDM_PERMISSION_ERROR;
678 }
679 
DisableSuperAdmin(const std::string & bundleName)680 ErrCode EnterpriseDeviceMgrAbility::DisableSuperAdmin(const std::string &bundleName)
681 {
682     std::lock_guard<std::mutex> autoLock(mutexLock_);
683     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
684         EDMLOGW("EnterpriseDeviceMgrAbility::DisableSuperAdmin check permission failed.");
685         return EdmReturnErrCode::PERMISSION_DENIED;
686     }
687     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
688     if (admin == nullptr) {
689         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
690     }
691     if (admin->adminInfo_.adminType_ != AdminType::ENT) {
692         EDMLOGW("DisableSuperAdmin: only remove super admin.");
693         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
694     }
695     // disable sub-super admin
696     std::vector<std::string> subAdmins;
697     adminMgr_->GetSubSuperAdminsByParentName(bundleName, subAdmins);
698     for (auto const &subAdminName : subAdmins) {
699         if (FAILED(RemovePolicyAndAdmin(subAdminName))) {
700             EDMLOGW("DisableSuperAdmin: remove sub-super admin failed.");
701             return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
702         }
703     }
704     // disable super admin
705     if (FAILED(RemovePolicyAndAdmin(bundleName))) {
706         EDMLOGW("DisableSuperAdmin: remove super admin failed.");
707         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
708     }
709     if (!adminMgr_->IsAdminExist()) {
710         system::SetParameter(PARAM_EDM_ENABLE, "false");
711     }
712     AAFwk::Want want;
713     want.SetElementName(admin->adminInfo_.packageName_, admin->adminInfo_.className_);
714     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
715     sptr<IEnterpriseConnection> connection =
716         manager->CreateAdminConnection(want, IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, DEFAULT_USER_ID);
717     manager->ConnectAbility(connection);
718     return ERR_OK;
719 }
720 
IsSuperAdmin(const std::string & bundleName)721 bool EnterpriseDeviceMgrAbility::IsSuperAdmin(const std::string &bundleName)
722 {
723     std::lock_guard<std::mutex> autoLock(mutexLock_);
724     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
725     if (admin == nullptr) {
726         EDMLOGW("IsSuperAdmin: admin == nullptr.");
727         return false;
728     }
729     if (admin->adminInfo_.adminType_ == AdminType::ENT) {
730         EDMLOGW("IsSuperAdmin: admin->adminInfo_.adminType_ == AdminType::ENT.");
731         return true;
732     }
733     return false;
734 }
735 
IsAdminEnabled(AppExecFwk::ElementName & admin,int32_t userId)736 bool EnterpriseDeviceMgrAbility::IsAdminEnabled(AppExecFwk::ElementName &admin, int32_t userId)
737 {
738     std::lock_guard<std::mutex> autoLock(mutexLock_);
739     std::shared_ptr<Admin> existAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
740     if (existAdmin != nullptr) {
741         EDMLOGD("IsAdminEnabled: get admin successed");
742         return true;
743     }
744     return false;
745 }
746 
GetCurrentUserId()747 int32_t EnterpriseDeviceMgrAbility::GetCurrentUserId()
748 {
749     std::vector<int32_t> ids;
750     ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
751     if (FAILED(ret) || ids.empty()) {
752         EDMLOGE("EnterpriseDeviceMgrAbility GetCurrentUserId failed");
753         return -1;
754     }
755     EDMLOGD("EnterpriseDeviceMgrAbility GetCurrentUserId user id = %{public}d", ids.at(0));
756     return (ids.at(0));
757 }
758 
GetAndSwitchPolicyManagerByUserId(int32_t userId)759 std::shared_ptr<PolicyManager> EnterpriseDeviceMgrAbility::GetAndSwitchPolicyManagerByUserId(int32_t userId)
760 {
761     auto iter = policyMgrMap_.find(userId);
762     std::shared_ptr<PolicyManager> policyMgr;
763     if (iter == policyMgrMap_.end()) {
764         policyMgr.reset(new (std::nothrow) PolicyManager(userId));
765         policyMgrMap_.insert(std::make_pair(userId, policyMgr));
766         EDMLOGI("get policyMgr failed create success userId : %{public}d", userId);
767         policyMgr->Init();
768     } else {
769         policyMgr = iter->second;
770     }
771     IPolicyManager::policyManagerInstance_ = policyMgr.get();
772     return policyMgr;
773 }
774 
UpdateDevicePolicy(uint32_t code,AppExecFwk::ElementName & admin,MessageParcel & data,MessageParcel & reply,int32_t userId)775 ErrCode EnterpriseDeviceMgrAbility::UpdateDevicePolicy(uint32_t code, AppExecFwk::ElementName &admin,
776     MessageParcel &data, MessageParcel &reply, int32_t userId)
777 {
778     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
779     if (plugin == nullptr) {
780         EDMLOGW("UpdateDevicePolicy: get plugin failed, code:%{public}d", code);
781         return EdmReturnErrCode::INTERFACE_UNSUPPORTED;
782     }
783 
784     // Set policy to other users except 100
785     policyMgr_ = GetAndSwitchPolicyManagerByUserId(userId);
786     std::string policyName = plugin->GetPolicyName();
787     std::string policyValue;
788     policyMgr_->GetPolicy(admin.GetBundleName(), policyName, policyValue);
789     bool isChanged = false;
790     ErrCode ret = plugin->OnHandlePolicy(code, data, reply, policyValue, isChanged, userId);
791     if (FAILED(ret)) {
792         EDMLOGW("UpdateDevicePolicy: OnHandlePolicy failed");
793         return ret;
794     }
795     EDMLOGD("UpdateDevicePolicy: isChanged:%{public}d, needSave:%{public}d\n", isChanged, plugin->NeedSavePolicy());
796     std::string oldCombinePolicy;
797     policyMgr_->GetPolicy("", policyName, oldCombinePolicy);
798     std::string mergedPolicy = policyValue;
799     bool isGlobalChanged = false;
800     if (plugin->NeedSavePolicy() && isChanged) {
801         ret = plugin->MergePolicyData(admin.GetBundleName(), mergedPolicy);
802         if (FAILED(ret)) {
803             EDMLOGW("UpdateDevicePolicy: MergePolicyData failed error:%{public}d", ret);
804             return ret;
805         }
806         policyMgr_->SetPolicy(admin.GetBundleName(), policyName, policyValue, mergedPolicy);
807         isGlobalChanged = (oldCombinePolicy != mergedPolicy);
808     }
809     plugin->OnHandlePolicyDone(code, admin.GetBundleName(), isGlobalChanged, userId);
810     // Reset to 100 policyMgr
811     policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
812     return ERR_OK;
813 }
814 
HandleDevicePolicy(uint32_t code,AppExecFwk::ElementName & admin,MessageParcel & data,MessageParcel & reply,int32_t userId)815 ErrCode EnterpriseDeviceMgrAbility::HandleDevicePolicy(uint32_t code, AppExecFwk::ElementName &admin,
816     MessageParcel &data, MessageParcel &reply, int32_t userId)
817 {
818     std::lock_guard<std::mutex> autoLock(mutexLock_);
819     bool isUserExist = false;
820     AccountSA::OsAccountManager::IsOsAccountExists(userId, isUserExist);
821     if (!isUserExist) {
822         return EdmReturnErrCode::PARAM_ERROR;
823     }
824     EDMLOGI("HandleDevicePolicy: HandleDevicePolicy userId = %{public}d", userId);
825     std::shared_ptr<Admin> deviceAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), GetCurrentUserId());
826     if (deviceAdmin == nullptr) {
827         EDMLOGW("HandleDevicePolicy: get admin failed");
828         return EdmReturnErrCode::ADMIN_INACTIVE;
829     }
830     if (FAILED(CheckCallingUid(deviceAdmin->adminInfo_.packageName_))) {
831         EDMLOGW("HandleDevicePolicy: CheckCallingUid failed.");
832         return EdmReturnErrCode::PERMISSION_DENIED;
833     }
834     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
835     if (plugin == nullptr) {
836         EDMLOGW("HandleDevicePolicy: get plugin failed, code:%{public}d", code);
837         return EdmReturnErrCode::INTERFACE_UNSUPPORTED;
838     }
839     EDMLOGD("HandleDevicePolicy: plugin info:%{public}d , %{public}s , %{public}s", plugin->GetCode(),
840         plugin->GetPolicyName().c_str(), plugin->GetPermission(FuncOperateType::SET).c_str());
841     if (!deviceAdmin->CheckPermission(plugin->GetPermission(FuncOperateType::SET)) ||
842         (deviceAdmin->adminInfo_.adminType_ != AdminType::ENT &&
843             deviceAdmin->adminInfo_.adminType_ != AdminType::SUB_SUPER_ADMIN && userId != GetCurrentUserId())) {
844         EDMLOGW("HandleDevicePolicy: admin check permission failed");
845         return EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED;
846     }
847     if (!VerifyCallingPermission(plugin->GetPermission(FuncOperateType::SET))) {
848         EDMLOGW("HandleDevicePolicy: VerifyCallingPermission failed");
849         return EdmReturnErrCode::PERMISSION_DENIED;
850     }
851     return UpdateDevicePolicy(code, admin, data, reply, userId);
852 }
853 
GetDevicePolicy(uint32_t code,MessageParcel & data,MessageParcel & reply,int32_t userId)854 ErrCode EnterpriseDeviceMgrAbility::GetDevicePolicy(uint32_t code, MessageParcel &data, MessageParcel &reply,
855     int32_t userId)
856 {
857     std::lock_guard<std::mutex> autoLock(mutexLock_);
858     bool isUserExist = false;
859     AccountSA::OsAccountManager::IsOsAccountExists(userId, isUserExist);
860     if (!isUserExist) {
861         reply.WriteInt32(EdmReturnErrCode::PARAM_ERROR);
862         return EdmReturnErrCode::PARAM_ERROR;
863     }
864     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
865     if (plugin == nullptr) {
866         EDMLOGW("GetDevicePolicy: get plugin failed");
867         reply.WriteInt32(EdmReturnErrCode::INTERFACE_UNSUPPORTED);
868         return EdmReturnErrCode::INTERFACE_UNSUPPORTED;
869     }
870     std::string adminName;
871     std::string getPermission = plugin->GetPermission(FuncOperateType::GET);
872     // has admin
873     if (data.ReadInt32() == 0) {
874         ErrCode ret = CheckGetPolicyPermission(data, reply, getPermission, adminName);
875         if (FAILED(ret)) {
876             return ret;
877         }
878     }
879     if (!getPermission.empty() && !VerifyCallingPermission(getPermission)) {
880         EDMLOGW("GetDevicePolicy: VerifyCallingPermission failed");
881         reply.WriteInt32(EdmReturnErrCode::PERMISSION_DENIED);
882         return EdmReturnErrCode::PERMISSION_DENIED;
883     }
884     std::string policyName = plugin->GetPolicyName();
885     std::string policyValue;
886 
887     policyMgr_ = GetAndSwitchPolicyManagerByUserId(userId);
888     if (plugin->NeedSavePolicy()) {
889         policyMgr_->GetPolicy(adminName, policyName, policyValue);
890     }
891     ErrCode ret = plugin->OnGetPolicy(policyValue, data, reply, userId);
892     policyMgr_ = GetAndSwitchPolicyManagerByUserId(DEFAULT_USER_ID);
893     return ret;
894 }
895 
CheckGetPolicyPermission(MessageParcel & data,MessageParcel & reply,const std::string & getPermission,std::string & adminName)896 ErrCode EnterpriseDeviceMgrAbility::CheckGetPolicyPermission(MessageParcel &data, MessageParcel &reply,
897     const std::string &getPermission, std::string &adminName)
898 {
899     std::unique_ptr<AppExecFwk::ElementName> admin(data.ReadParcelable<AppExecFwk::ElementName>());
900     if (!admin) {
901         EDMLOGW("GetDevicePolicy: ReadParcelable failed");
902         reply.WriteInt32(EdmReturnErrCode::PARAM_ERROR);
903         return ERR_EDM_PARAM_ERROR;
904     }
905     std::shared_ptr<Admin> deviceAdmin = adminMgr_->GetAdminByPkgName(admin->GetBundleName(), GetCurrentUserId());
906     if (deviceAdmin == nullptr) {
907         EDMLOGW("GetDevicePolicy: get admin failed");
908         reply.WriteInt32(EdmReturnErrCode::ADMIN_INACTIVE);
909         return EdmReturnErrCode::ADMIN_INACTIVE;
910     }
911     if (FAILED(CheckCallingUid(deviceAdmin->adminInfo_.packageName_))) {
912         EDMLOGW("GetDevicePolicy: CheckCallingUid failed.");
913         reply.WriteInt32(EdmReturnErrCode::PERMISSION_DENIED);
914         return EdmReturnErrCode::PERMISSION_DENIED;
915     }
916     if (!getPermission.empty() && !deviceAdmin->CheckPermission(getPermission)) {
917         EDMLOGW("GetDevicePolicy: admin check permission failed %{public}s", getPermission.c_str());
918         reply.WriteInt32(EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED);
919         return EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED;
920     }
921     adminName = admin->GetBundleName();
922     return ERR_OK;
923 }
924 
GetEnabledAdmin(AdminType type,std::vector<std::string> & enabledAdminList)925 ErrCode EnterpriseDeviceMgrAbility::GetEnabledAdmin(AdminType type, std::vector<std::string> &enabledAdminList)
926 {
927     std::lock_guard<std::mutex> autoLock(mutexLock_);
928     std::vector<std::string> superList;
929     std::vector<std::string> normalList;
930     switch (type) {
931         case AdminType::NORMAL:
932             adminMgr_->GetEnabledAdmin(AdminType::NORMAL, normalList, GetCurrentUserId());
933             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
934             break;
935         case AdminType::ENT:
936             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
937             break;
938         case AdminType::UNKNOWN:
939             break;
940         default:
941             return ERR_EDM_PARAM_ERROR;
942     }
943     if (!superList.empty()) {
944         enabledAdminList.insert(enabledAdminList.begin(), superList.begin(), superList.end());
945     }
946     if (!normalList.empty()) {
947         enabledAdminList.insert(enabledAdminList.begin(), normalList.begin(), normalList.end());
948     }
949     for (const auto &enabledAdmin : enabledAdminList) {
950         EDMLOGD("GetEnabledAdmin: %{public}s", enabledAdmin.c_str());
951     }
952     return ERR_OK;
953 }
954 
GetEnterpriseInfo(AppExecFwk::ElementName & admin,MessageParcel & reply)955 ErrCode EnterpriseDeviceMgrAbility::GetEnterpriseInfo(AppExecFwk::ElementName &admin, MessageParcel &reply)
956 {
957     std::lock_guard<std::mutex> autoLock(mutexLock_);
958     EntInfo entInfo;
959     int32_t userId = adminMgr_->IsSuperOrSubSuperAdmin(admin.GetBundleName()) ? DEFAULT_USER_ID : GetCurrentUserId();
960     ErrCode code = adminMgr_->GetEntInfo(admin.GetBundleName(), entInfo, userId);
961     if (code != ERR_OK) {
962         reply.WriteInt32(EdmReturnErrCode::ADMIN_INACTIVE);
963         return EdmReturnErrCode::ADMIN_INACTIVE;
964     }
965     reply.WriteInt32(ERR_OK);
966     reply.WriteParcelable(&entInfo);
967     EDMLOGD(
968         "EnterpriseDeviceMgrAbility::GetEnterpriseInfo: entInfo->enterpriseName %{public}s, "
969         "entInfo->description:%{public}s",
970         entInfo.enterpriseName.c_str(), entInfo.description.c_str());
971     return ERR_OK;
972 }
973 
SetEnterpriseInfo(AppExecFwk::ElementName & admin,EntInfo & entInfo)974 ErrCode EnterpriseDeviceMgrAbility::SetEnterpriseInfo(AppExecFwk::ElementName &admin, EntInfo &entInfo)
975 {
976     std::lock_guard<std::mutex> autoLock(mutexLock_);
977     if (!VerifyCallingPermission(PERMISSION_SET_ENTERPRISE_INFO)) {
978         EDMLOGW("EnterpriseDeviceMgrAbility::SetEnterpriseInfo: check permission failed");
979         return EdmReturnErrCode::PERMISSION_DENIED;
980     }
981     int32_t userId = adminMgr_->IsSuperOrSubSuperAdmin(admin.GetBundleName()) ? DEFAULT_USER_ID : GetCurrentUserId();
982     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
983     if (adminItem == nullptr) {
984         return EdmReturnErrCode::ADMIN_INACTIVE;
985     }
986     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
987     if (ret != ERR_OK) {
988         EDMLOGW("SetEnterpriseInfo: CheckCallingUid failed: %{public}d", ret);
989         return EdmReturnErrCode::PERMISSION_DENIED;
990     }
991     ErrCode code = adminMgr_->SetEntInfo(admin.GetBundleName(), entInfo, userId);
992     return (code != ERR_OK) ? EdmReturnErrCode::ADMIN_INACTIVE : ERR_OK;
993 }
994 
HandleApplicationEvent(const std::vector<uint32_t> & events,bool subscribe)995 ErrCode EnterpriseDeviceMgrAbility::HandleApplicationEvent(const std::vector<uint32_t> &events, bool subscribe)
996 {
997     bool shouldHandleAppState = std::any_of(events.begin(), events.end(), [](uint32_t event) {
998         return event == static_cast<uint32_t>(ManagedEvent::APP_START) ||
999             event == static_cast<uint32_t>(ManagedEvent::APP_STOP);
1000     });
1001     if (!shouldHandleAppState) {
1002         return ERR_OK;
1003     }
1004     if (subscribe) {
1005         return SubscribeAppState() ? ERR_OK : EdmReturnErrCode::SYSTEM_ABNORMALLY;
1006     } else {
1007         return UnsubscribeAppState() ? ERR_OK : EdmReturnErrCode::SYSTEM_ABNORMALLY;
1008     }
1009 }
1010 
SubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)1011 ErrCode EnterpriseDeviceMgrAbility::SubscribeManagedEvent(const AppExecFwk::ElementName &admin,
1012     const std::vector<uint32_t> &events)
1013 {
1014     std::lock_guard<std::mutex> autoLock(mutexLock_);
1015     RETURN_IF_FAILED(VerifyManagedEvent(admin, events));
1016     RETURN_IF_FAILED(HandleApplicationEvent(events, true));
1017     int32_t userId = adminMgr_->IsSuperOrSubSuperAdmin(admin.GetBundleName()) ? DEFAULT_USER_ID : GetCurrentUserId();
1018     adminMgr_->SaveSubscribeEvents(events, admin.GetBundleName(), userId);
1019     return ERR_OK;
1020 }
1021 
UnsubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)1022 ErrCode EnterpriseDeviceMgrAbility::UnsubscribeManagedEvent(const AppExecFwk::ElementName &admin,
1023     const std::vector<uint32_t> &events)
1024 {
1025     std::lock_guard<std::mutex> autoLock(mutexLock_);
1026     RETURN_IF_FAILED(VerifyManagedEvent(admin, events));
1027     int32_t userId = adminMgr_->IsSuperOrSubSuperAdmin(admin.GetBundleName()) ? DEFAULT_USER_ID : GetCurrentUserId();
1028     adminMgr_->RemoveSubscribeEvents(events, admin.GetBundleName(), userId);
1029     return HandleApplicationEvent(events, false);
1030 }
1031 
VerifyManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)1032 ErrCode EnterpriseDeviceMgrAbility::VerifyManagedEvent(const AppExecFwk::ElementName &admin,
1033     const std::vector<uint32_t> &events)
1034 {
1035     if (!VerifyCallingPermission(PERMISSION_ENTERPRISE_SUBSCRIBE_MANAGED_EVENT)) {
1036         EDMLOGW("EnterpriseDeviceMgrAbility::VerifyManagedEvent: check permission failed");
1037         return EdmReturnErrCode::PERMISSION_DENIED;
1038     }
1039     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), GetCurrentUserId());
1040     if (adminItem == nullptr) {
1041         return EdmReturnErrCode::ADMIN_INACTIVE;
1042     }
1043     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
1044     if (ret != ERR_OK) {
1045         EDMLOGW("VerifyManagedEvent: CheckCallingUid failed: %{public}d", ret);
1046         return EdmReturnErrCode::PERMISSION_DENIED;
1047     }
1048     if (events.empty()) {
1049         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
1050     }
1051     auto iter =
1052         std::find_if(events.begin(), events.end(), [this](uint32_t event) { return !CheckManagedEvent(event); });
1053     if (iter != std::end(events)) {
1054         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
1055     }
1056     return ERR_OK;
1057 }
1058 
CheckManagedEvent(uint32_t event)1059 bool EnterpriseDeviceMgrAbility::CheckManagedEvent(uint32_t event)
1060 {
1061     switch (event) {
1062         case static_cast<uint32_t>(ManagedEvent::BUNDLE_ADDED):
1063         case static_cast<uint32_t>(ManagedEvent::BUNDLE_REMOVED):
1064         case static_cast<uint32_t>(ManagedEvent::APP_START):
1065         case static_cast<uint32_t>(ManagedEvent::APP_STOP):
1066             break;
1067         default:
1068             return false;
1069     }
1070     return true;
1071 }
1072 
AuthorizeAdmin(const AppExecFwk::ElementName & admin,const std::string & bundleName)1073 ErrCode EnterpriseDeviceMgrAbility::AuthorizeAdmin(const AppExecFwk::ElementName &admin, const std::string &bundleName)
1074 {
1075     std::lock_guard<std::mutex> autoLock(mutexLock_);
1076     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
1077         EDMLOGW("EnterpriseDeviceMgrAbility::AuthorizeAdmin: check permission failed");
1078         return EdmReturnErrCode::PERMISSION_DENIED;
1079     }
1080     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), GetCurrentUserId());
1081     if (adminItem == nullptr) {
1082         EDMLOGW("EnterpriseDeviceMgrAbility::AuthorizeAdmin: not active admin.");
1083         return EdmReturnErrCode::ADMIN_INACTIVE;
1084     }
1085     if (adminItem->GetAdminType() != AdminType::ENT) {
1086         EDMLOGW("AuthorizeAdmin: Caller is not super admin.");
1087         return EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED;
1088     }
1089     if (FAILED(CheckCallingUid(admin.GetBundleName()))) {
1090         EDMLOGW("AuthorizeAdmin: CheckCallingUid failed.");
1091         return EdmReturnErrCode::PERMISSION_DENIED;
1092     }
1093     /* Get all request and registered permissions */
1094     std::vector<std::string> permissionList;
1095     if (FAILED(GetAllPermissionsByAdmin(bundleName, permissionList, DEFAULT_USER_ID))) {
1096         EDMLOGW("EnableAdmin: GetAllPermissionsByAdmin failed.");
1097         return EdmReturnErrCode::AUTHORIZE_PERMISSION_FAILED;
1098     }
1099     if (FAILED(adminMgr_->SaveAuthorizedAdmin(bundleName, permissionList, admin.GetBundleName()))) {
1100         EDMLOGW("EnableAdmin: SaveAuthorizedAdmin failed.");
1101         return EdmReturnErrCode::AUTHORIZE_PERMISSION_FAILED;
1102     }
1103     return ERR_OK;
1104 }
1105 } // namespace EDM
1106 } // namespace OHOS