• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #include <bundle_info.h>
18 #include <bundle_mgr_interface.h>
19 #include <ipc_skeleton.h>
20 #include <iservice_registry.h>
21 #include <message_parcel.h>
22 #include <string_ex.h>
23 #include <system_ability.h>
24 #include <system_ability_definition.h>
25 
26 #include "accesstoken_kit.h"
27 #include "bundle_mgr_proxy.h"
28 #include "common_event_manager.h"
29 #include "common_event_support.h"
30 #include "edm_log.h"
31 #include "edm_sys_manager.h"
32 #include "enterprise_admin_connection.h"
33 #include "enterprise_bundle_connection.h"
34 #include "enterprise_conn_manager.h"
35 #include "matching_skills.h"
36 #include "os_account_manager.h"
37 #include "plugin_manager.h"
38 
39 namespace OHOS {
40 namespace EDM {
41 const bool REGISTER_RESULT =
42     SystemAbility::MakeAndRegisterAbility(EnterpriseDeviceMgrAbility::GetInstance().GetRefPtr());
43 
44 std::mutex EnterpriseDeviceMgrAbility::mutexLock_;
45 
46 sptr<EnterpriseDeviceMgrAbility> EnterpriseDeviceMgrAbility::instance_;
47 
48 constexpr int32_t DEFAULT_USER_ID = 100;
49 
AddCommonEventFuncMap()50 void EnterpriseDeviceMgrAbility::AddCommonEventFuncMap()
51 {
52     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED] =
53         &EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved;
54     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED] =
55         &EnterpriseDeviceMgrAbility::OnCommonEventPackageAdded;
56     commonEventFuncMap_[EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED] =
57         &EnterpriseDeviceMgrAbility::OnCommonEventPackageRemoved;
58 }
59 
60 const std::string PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN = "ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN";
61 const std::string PERMISSION_SET_ENTERPRISE_INFO = "ohos.permission.SET_ENTERPRISE_INFO";
62 const std::string PERMISSION_ENTERPRISE_SUBSCRIBE_MANAGED_EVENT = "ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT";
EnterpriseDeviceEventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscribeInfo,EnterpriseDeviceMgrAbility & listener)63 EnterpriseDeviceEventSubscriber::EnterpriseDeviceEventSubscriber(
64     const EventFwk::CommonEventSubscribeInfo &subscribeInfo,
65     EnterpriseDeviceMgrAbility &listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) {}
66 
OnReceiveEvent(const EventFwk::CommonEventData & data)67 void EnterpriseDeviceEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data)
68 {
69     const std::string action = data.GetWant().GetAction();
70     EDMLOGI("EDM OnReceiveEvent get action: %{public}s", action.c_str());
71     auto func = listener_.commonEventFuncMap_.find(action);
72     if (func != listener_.commonEventFuncMap_.end()) {
73         auto commonEventFunc = func->second;
74         if (commonEventFunc != nullptr) {
75             return (listener_.*commonEventFunc)(data);
76         }
77     } else {
78         EDMLOGW("OnReceiveEvent action is invalid");
79     }
80 }
81 
CreateEnterpriseDeviceEventSubscriber(EnterpriseDeviceMgrAbility & listener)82 std::shared_ptr<EventFwk::CommonEventSubscriber> EnterpriseDeviceMgrAbility::CreateEnterpriseDeviceEventSubscriber(
83     EnterpriseDeviceMgrAbility &listener)
84 {
85     EventFwk::MatchingSkills skill = EventFwk::MatchingSkills();
86     AddCommonEventFuncMap();
87     for (auto &item : commonEventFuncMap_) {
88         skill.AddEvent(item.first);
89         EDMLOGI("CreateEnterpriseDeviceEventSubscriber AddEvent: %{public}s", item.first.c_str());
90     }
91     EventFwk::CommonEventSubscribeInfo info(skill);
92     return std::make_shared<EnterpriseDeviceEventSubscriber>(info, listener);
93 }
94 
OnCommonEventUserRemoved(const EventFwk::CommonEventData & data)95 void EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved(const EventFwk::CommonEventData &data)
96 {
97     int userIdToRemove = data.GetCode();
98     if (userIdToRemove == 0) {
99         return;
100     }
101     EDMLOGI("OnCommonEventUserRemoved");
102     // include super admin, need to be removed
103     std::vector<std::shared_ptr<Admin>> userAdmin;
104     adminMgr_->GetAdminByUserId(userIdToRemove, userAdmin);
105     for (auto &item : userAdmin) {
106         ErrCode ret = RemoveAdmin(item->adminInfo_.packageName_, userIdToRemove);
107         if (ret != ERR_OK) {
108             EDMLOGW("EnterpriseDeviceMgrAbility::OnCommonEventUserRemoved ret = %{public}d; packagename = %{public}s",
109                 ret, item->adminInfo_.packageName_.c_str());
110         }
111     }
112 }
113 
OnCommonEventPackageAdded(const EventFwk::CommonEventData & data)114 void EnterpriseDeviceMgrAbility::OnCommonEventPackageAdded(const EventFwk::CommonEventData &data)
115 {
116     EDMLOGI("OnCommonEventPackageAdded");
117     OnCommonEventPackageAddedOrRemoved(data, ManagedEvent::BUNDLE_ADDED);
118 }
119 
OnCommonEventPackageRemoved(const EventFwk::CommonEventData & data)120 void EnterpriseDeviceMgrAbility::OnCommonEventPackageRemoved(const EventFwk::CommonEventData &data)
121 {
122     EDMLOGI("OnCommonEventPackageRemoved");
123     OnCommonEventPackageAddedOrRemoved(data, ManagedEvent::BUNDLE_REMOVED);
124 }
125 
OnCommonEventPackageAddedOrRemoved(const EventFwk::CommonEventData & data,ManagedEvent event)126 void EnterpriseDeviceMgrAbility::OnCommonEventPackageAddedOrRemoved(const EventFwk::CommonEventData &data,
127     ManagedEvent event)
128 {
129     std::unordered_map<int32_t, std::vector<std::shared_ptr<Admin>>> subAdmins;
130     adminMgr_->GetAdminBySubscribeEvent(event, subAdmins);
131     if (subAdmins.empty()) {
132         EDMLOGW("Get subscriber by common event failed.");
133         return;
134     }
135     std::string bundleName = data.GetWant().GetElement().GetBundleName();
136     AAFwk::Want want;
137     for (const auto &subAdmin : subAdmins) {
138         for (auto &it : subAdmin.second) {
139             want.SetElementName(it->adminInfo_.packageName_, it->adminInfo_.className_);
140             std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
141             sptr<IEnterpriseConnection> connection = manager->CreateBundleConnection(want,
142                 static_cast<uint32_t>(event), subAdmin.first, bundleName);
143             manager->ConnectAbility(connection);
144         }
145     }
146 }
147 
GetInstance()148 sptr<EnterpriseDeviceMgrAbility> EnterpriseDeviceMgrAbility::GetInstance()
149 {
150     if (instance_ == nullptr) {
151         std::lock_guard<std::mutex> autoLock(mutexLock_);
152         if (instance_ == nullptr) {
153             EDMLOGD("EnterpriseDeviceMgrAbility:GetInstance instance = new EnterpriseDeviceMgrAbility()");
154             instance_ = new (std::nothrow) EnterpriseDeviceMgrAbility();
155         }
156     }
157     return instance_;
158 }
159 
EnterpriseDeviceMgrAbility()160 EnterpriseDeviceMgrAbility::EnterpriseDeviceMgrAbility() : SystemAbility(ENTERPRISE_DEVICE_MANAGER_SA_ID, true)
161 {
162     EDMLOGI("EnterpriseDeviceMgrAbility:new instance");
163 }
164 
~EnterpriseDeviceMgrAbility()165 EnterpriseDeviceMgrAbility::~EnterpriseDeviceMgrAbility()
166 {
167     instance_ = nullptr;
168 
169     if (adminMgr_) {
170         adminMgr_.reset();
171     }
172 
173     if (pluginMgr_) {
174         pluginMgr_.reset();
175     }
176 
177     if (policyMgr_) {
178         policyMgr_.reset();
179     }
180     EDMLOGD("instance is destroyed");
181 }
182 
Dump(int32_t fd,const std::vector<std::u16string> & args)183 int32_t EnterpriseDeviceMgrAbility::Dump(int32_t fd, const std::vector<std::u16string>& args)
184 {
185     EDMLOGI("EnterpriseDeviceMgrAbility::Dump");
186     if (fd < 0) {
187         EDMLOGE("Dump fd invalid");
188         return ERR_EDM_DUMP_FAILED;
189     }
190     std::string result;
191     result.append("Ohos enterprise device manager service: \n");
192     std::vector<std::string> enabledAdminList;
193     GetEnabledAdmin(AdminType::NORMAL, enabledAdminList);
194     if (enabledAdminList.empty()) {
195         result.append("There is no admin enabled\n");
196     } else {
197         result.append("Enabled admin exist :\n");
198         for (const auto &enabledAdmin : enabledAdminList) {
199             result.append(enabledAdmin.c_str());
200             result.append("\n");
201         }
202     }
203     int32_t ret = dprintf(fd, "%s", result.c_str());
204     if (ret < 0) {
205         EDMLOGE("dprintf to dump fd failed");
206         return ERR_EDM_DUMP_FAILED;
207     }
208     return ERR_OK;
209 }
210 
OnStart()211 void EnterpriseDeviceMgrAbility::OnStart()
212 {
213     EDMLOGD("EnterpriseDeviceMgrAbility::OnStart() Publish");
214     if (!registerToService_) {
215         if (!Publish(this)) {
216             EDMLOGE("EnterpriseDeviceMgrAbility: res == false");
217             return;
218         }
219         registerToService_ = true;
220     }
221     if (!adminMgr_) {
222         adminMgr_ = AdminManager::GetInstance();
223     }
224     EDMLOGD("create adminMgr_ success");
225     adminMgr_->Init();
226 
227     if (!policyMgr_) {
228         policyMgr_ = PolicyManager::GetInstance();
229     }
230     EDMLOGD("create policyMgr_ success");
231     policyMgr_->Init();
232 
233     if (!pluginMgr_) {
234         pluginMgr_ = PluginManager::GetInstance();
235     }
236     EDMLOGD("create pluginMgr_ success");
237     pluginMgr_->Init();
238 
239     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
240 }
241 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)242 void EnterpriseDeviceMgrAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
243 {
244     EDMLOGD("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
245     commonEventSubscriber = CreateEnterpriseDeviceEventSubscriber(*this);
246     EventFwk::CommonEventManager::SubscribeCommonEvent(this->commonEventSubscriber);
247     EDMLOGI("create commonEventSubscriber success");
248 }
249 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)250 void EnterpriseDeviceMgrAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
251 {
252 }
253 
254 
OnStop()255 void EnterpriseDeviceMgrAbility::OnStop()
256 {
257     EDMLOGD("EnterpriseDeviceMgrAbility::OnStop()");
258 }
259 
GetAllPermissionsByAdmin(const std::string & bundleInfoName,std::vector<std::string> & permissionList,int32_t userId)260 ErrCode EnterpriseDeviceMgrAbility::GetAllPermissionsByAdmin(const std::string &bundleInfoName,
261     std::vector<std::string> &permissionList, int32_t userId)
262 {
263     bool ret = false;
264     AppExecFwk::BundleInfo bundleInfo;
265     auto bundleManager = GetBundleMgr();
266     permissionList.clear();
267     EDMLOGD("GetAllPermissionsByAdmin GetBundleInfo: bundleInfoName %{public}s userid %{public}d",
268         bundleInfoName.c_str(), userId);
269     ret = bundleManager->GetBundleInfo(bundleInfoName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION,
270         bundleInfo, userId);
271     if (!ret) {
272         EDMLOGW("GetAllPermissionsByAdmin: GetBundleInfo failed %{public}d", ret);
273         return ERR_EDM_PARAM_ERROR;
274     }
275     std::vector<std::string> reqPermission = bundleInfo.reqPermissions;
276     if (reqPermission.empty()) {
277         EDMLOGW("GetAllPermissionsByAdmin: bundleInfo reqPermissions empty");
278         return ERR_OK;
279     }
280 
281     std::vector<EdmPermission> edmPermissions;
282     ErrCode code = adminMgr_->GetReqPermission(reqPermission, edmPermissions);
283     if (SUCCEEDED(code)) {
284         for (const auto &perm : edmPermissions) {
285             permissionList.push_back(perm.getPermissionName());
286         }
287     }
288     return ERR_OK;
289 }
290 
GetBundleMgr()291 sptr<AppExecFwk::IBundleMgr> EnterpriseDeviceMgrAbility::GetBundleMgr()
292 {
293     auto remoteObject = EdmSysManager::GetRemoteObjectOfSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
294     sptr<AppExecFwk::IBundleMgr> proxy = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
295     return proxy;
296 }
297 
VerifyCallingPermission(const std::string & permissionName)298 bool EnterpriseDeviceMgrAbility::VerifyCallingPermission(const std::string &permissionName)
299 {
300     EDMLOGD("VerifyCallingPermission permission %{public}s", permissionName.c_str());
301     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
302     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
303     if (ret == Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
304         EDMLOGI("permission %{public}s: PERMISSION_GRANTED", permissionName.c_str());
305         return true;
306     }
307     EDMLOGW("verify AccessToken failed");
308     return false;
309 }
310 
VerifyEnableAdminCondition(AppExecFwk::ElementName & admin,AdminType type,int32_t userId)311 ErrCode EnterpriseDeviceMgrAbility::VerifyEnableAdminCondition(AppExecFwk::ElementName &admin,
312     AdminType type, int32_t userId)
313 {
314     if (adminMgr_->IsSuperAdmin(admin.GetBundleName())) {
315         if (type != AdminType::ENT || userId != DEFAULT_USER_ID) {
316             EDMLOGW("EnableAdmin: an exist super admin can't be enabled twice with different role or user id.");
317             return ERR_EDM_ADD_ADMIN_FAILED;
318         }
319     }
320 
321     std::shared_ptr<Admin> existAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
322     if (type == AdminType::ENT && adminMgr_->IsSuperAdminExist()) {
323         if (existAdmin == nullptr || existAdmin->adminInfo_.adminType_ != AdminType::ENT) {
324             EDMLOGW("EnableAdmin: There is another super admin enabled.");
325             return ERR_EDM_ADD_ADMIN_FAILED;
326         }
327     }
328 
329     if (type == AdminType::ENT && userId != DEFAULT_USER_ID) {
330         EDMLOGW("EnableAdmin: Super admin can only be enabled in default user.");
331         return ERR_EDM_ADD_ADMIN_FAILED;
332     }
333 
334     if (existAdmin == nullptr) {
335         return ERR_OK;
336     }
337 
338     /* An application can't be enabled twice with different ability name */
339     if (existAdmin->adminInfo_.className_ != admin.GetAbilityName()) {
340         EDMLOGW("EnableAdmin: There is another admin ability enabled with the same package name.");
341         return ERR_EDM_ADD_ADMIN_FAILED;
342     }
343 
344     /* An existed super admin can't be enabled to normal */
345     if ((existAdmin->adminInfo_.adminType_ == AdminType::ENT) && (type == AdminType::NORMAL)) {
346         EDMLOGW("EnableAdmin: The admin is super, can't be enabled to normal.");
347         return ERR_EDM_ADD_ADMIN_FAILED;
348     }
349     return ERR_OK;
350 }
351 
EnableAdmin(AppExecFwk::ElementName & admin,EntInfo & entInfo,AdminType type,int32_t userId)352 ErrCode EnterpriseDeviceMgrAbility::EnableAdmin(AppExecFwk::ElementName &admin, EntInfo &entInfo, AdminType type,
353     int32_t userId)
354 {
355     EDMLOGD("EnterpriseDeviceMgrAbility::EnableAdmin user id = %{public}d", userId);
356     std::lock_guard<std::mutex> autoLock(mutexLock_);
357     if (!IsHdc() && !VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
358         EDMLOGW("EnterpriseDeviceMgrAbility::EnableAdmin check permission failed");
359         return EdmReturnErrCode::PERMISSION_DENIED;
360     }
361     std::vector<AppExecFwk::ExtensionAbilityInfo> abilityInfo;
362     auto bundleManager = GetBundleMgr();
363     if (!bundleManager) {
364         EDMLOGW("can not get iBundleMgr");
365         return EdmReturnErrCode::SYSTEM_ABNORMALLY;
366     }
367     AAFwk::Want want;
368     want.SetElement(admin);
369     if (!bundleManager->QueryExtensionAbilityInfos(want, AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN,
370         AppExecFwk::ExtensionAbilityInfoFlag::GET_EXTENSION_INFO_WITH_PERMISSION, userId, abilityInfo)) {
371         EDMLOGW("EnableAdmin: QueryExtensionAbilityInfos failed");
372         return EdmReturnErrCode::COMPONENT_INVALID;
373     }
374     if (FAILED(VerifyEnableAdminCondition(admin, type, userId))) {
375         EDMLOGW("EnableAdmin: VerifyEnableAdminCondition failed.");
376         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
377     }
378 
379     /* Get all request and registered permissions */
380     std::vector<std::string> permissionList;
381     if (FAILED(GetAllPermissionsByAdmin(admin.GetBundleName(), permissionList, userId))) {
382         EDMLOGW("EnableAdmin: GetAllPermissionsByAdmin failed");
383         return EdmReturnErrCode::COMPONENT_INVALID;
384     }
385     /* Filter permissions with AdminType, such as NORMAL can't request super permission */
386     if (FAILED(adminMgr_->GetGrantedPermission(abilityInfo.at(0), permissionList, type))) {
387         EDMLOGW("EnableAdmin: GetGrantedPermission failed");
388         // permission verify, should throw exception if failed
389         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
390     }
391     if (FAILED(adminMgr_->SetAdminValue(abilityInfo.at(0), entInfo, type, permissionList, userId))) {
392         EDMLOGE("EnableAdmin: SetAdminValue failed.");
393         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
394     }
395     EDMLOGI("EnableAdmin: SetAdminValue success %{public}s, type:%{public}d", admin.GetBundleName().c_str(),
396         static_cast<uint32_t>(type));
397     AAFwk::Want connectWant;
398     connectWant.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
399     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
400     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(connectWant,
401         IEnterpriseAdmin::COMMAND_ON_ADMIN_ENABLED, userId);
402     manager->ConnectAbility(connection);
403     return ERR_OK;
404 }
405 
RemoveAdminItem(std::string adminName,std::string policyName,std::string policyValue)406 ErrCode EnterpriseDeviceMgrAbility::RemoveAdminItem(std::string adminName, std::string policyName,
407     std::string policyValue)
408 {
409     ErrCode ret;
410     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByPolicyName(policyName);
411     if (plugin == nullptr) {
412         EDMLOGW("RemoveAdminItem: Get plugin by policy failed: %{public}s\n", policyName.c_str());
413         return ERR_EDM_GET_PLUGIN_MGR_FAILED;
414     }
415     if ((ret = plugin->OnAdminRemove(adminName, policyValue)) != ERR_OK) {
416         EDMLOGW("RemoveAdminItem: OnAdminRemove failed, admin:%{public}s, value:%{public}s, res:%{public}d\n",
417             adminName.c_str(), policyValue.c_str(), ret);
418     }
419     if (plugin->NeedSavePolicy()) {
420         std::string mergedPolicyData = "";
421         if ((ret = plugin->MergePolicyData(adminName, mergedPolicyData)) != ERR_OK) {
422             EDMLOGW("RemoveAdminItem: Get admin by policy name failed: %{public}s, ErrCode:%{public}d\n",
423                 policyName.c_str(), ret);
424         }
425 
426         ErrCode setRet = ERR_OK;
427         std::unordered_map<std::string, std::string> adminListMap;
428         ret = policyMgr_->GetAdminByPolicyName(policyName, adminListMap);
429         if ((ret == ERR_EDM_POLICY_NOT_FOUND) || adminListMap.empty()) {
430             setRet = policyMgr_->SetPolicy("", policyName, "", "");
431         } else {
432             setRet = policyMgr_->SetPolicy(adminName, policyName, "", mergedPolicyData);
433         }
434 
435         if (FAILED(setRet)) {
436             EDMLOGW("RemoveAdminItem: DeleteAdminPolicy failed, admin:%{public}s, policy:%{public}s, res:%{public}d\n",
437                 adminName.c_str(), policyName.c_str(), ret);
438             return ERR_EDM_DEL_ADMIN_FAILED;
439         }
440     }
441     plugin->OnAdminRemoveDone(adminName, policyValue);
442     return ERR_OK;
443 }
444 
RemoveAdmin(const std::string & adminName,int32_t userId)445 ErrCode EnterpriseDeviceMgrAbility::RemoveAdmin(const std::string &adminName, int32_t userId)
446 {
447     EDMLOGD("RemoveAdmin %{public}s, user id = %{public}d", adminName.c_str(), userId);
448     std::unordered_map<std::string, std::string> policyItems;
449     policyMgr_->GetAllPolicyByAdmin(adminName, policyItems);
450     for (const auto &policyItem : policyItems) {
451         std::string policyItemName = policyItem.first;
452         std::string policyItemValue = policyItem.second;
453         EDMLOGD("RemoveAdmin: RemoveAdminItem policyName:%{public}s,policyValue:%{public}s", policyItemName.c_str(),
454             policyItemValue.c_str());
455         if (RemoveAdminItem(adminName, policyItemName, policyItemValue) != ERR_OK) {
456             return ERR_EDM_DEL_ADMIN_FAILED;
457         }
458     }
459     if (adminMgr_->DeleteAdmin(adminName, userId) != ERR_OK) {
460         return ERR_EDM_DEL_ADMIN_FAILED;
461     }
462     return ERR_OK;
463 }
464 
DisableAdmin(AppExecFwk::ElementName & admin,int32_t userId)465 ErrCode EnterpriseDeviceMgrAbility::DisableAdmin(AppExecFwk::ElementName &admin, int32_t userId)
466 {
467     EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin user id = %{public}d", userId);
468     std::lock_guard<std::mutex> autoLock(mutexLock_);
469     if (!IsHdc() && !VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
470         EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin check permission failed");
471         return EdmReturnErrCode::PERMISSION_DENIED;
472     }
473 
474     std::shared_ptr<Admin> adminPtr = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
475     if (adminPtr == nullptr) {
476         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
477     }
478     if (adminPtr->adminInfo_.adminType_ != AdminType::NORMAL) {
479         EDMLOGW("DisableAdmin: only remove normal admin.");
480         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
481     }
482 
483     if (FAILED(RemoveAdmin(admin.GetBundleName(), userId))) {
484         EDMLOGW("DisableAdmin: disable admin failed.");
485         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
486     }
487     AAFwk::Want want;
488     want.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
489     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
490     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(want,
491         IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, userId);
492     manager->ConnectAbility(connection);
493     return ERR_OK;
494 }
495 
IsHdc()496 bool EnterpriseDeviceMgrAbility::IsHdc()
497 {
498     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
499     Security::AccessToken::ATokenTypeEnum tokenType =
500         Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
501     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
502         EDMLOGI("caller tokenType is shell, verify success");
503         return true;
504     }
505     return false;
506 }
507 
CheckCallingUid(std::string & bundleName)508 ErrCode EnterpriseDeviceMgrAbility::CheckCallingUid(std::string &bundleName)
509 {
510     // super admin can be removed by itself
511     int uid = GetCallingUid();
512     auto bundleManager = GetBundleMgr();
513     std::string callingBundleName;
514     if (bundleManager->GetNameForUid(uid, callingBundleName) != ERR_OK) {
515         EDMLOGW("CheckCallingUid failed: get bundleName for uid %{public}d fail.", uid);
516         return ERR_EDM_PERMISSION_ERROR;
517     }
518     if (bundleName == callingBundleName) {
519         return ERR_OK;
520     }
521     EDMLOGW("CheckCallingUid failed: only the app %{public}s can remove itself.", callingBundleName.c_str());
522     return ERR_EDM_PERMISSION_ERROR;
523 }
524 
DisableSuperAdmin(std::string & bundleName)525 ErrCode EnterpriseDeviceMgrAbility::DisableSuperAdmin(std::string &bundleName)
526 {
527     std::lock_guard<std::mutex> autoLock(mutexLock_);
528     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
529         EDMLOGW("EnterpriseDeviceMgrAbility::DisableSuperAdmin check permission failed.");
530         return EdmReturnErrCode::PERMISSION_DENIED;
531     }
532     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
533     if (admin == nullptr) {
534         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
535     }
536     if (admin->adminInfo_.adminType_ != AdminType::ENT) {
537         EDMLOGW("DisableSuperAdmin: only remove super admin.");
538         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
539     }
540     if (FAILED(RemoveAdmin(bundleName, DEFAULT_USER_ID))) {
541         EDMLOGW("DisableSuperAdmin: RemoveAdmin(bundleName, DEFAULT_USER_ID) failed");
542         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
543     }
544     AAFwk::Want want;
545     want.SetElementName(admin->adminInfo_.packageName_, admin->adminInfo_.className_);
546     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
547     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(want,
548         IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, DEFAULT_USER_ID);
549     manager->ConnectAbility(connection);
550     return ERR_OK;
551 }
552 
IsSuperAdmin(std::string & bundleName)553 bool EnterpriseDeviceMgrAbility::IsSuperAdmin(std::string &bundleName)
554 {
555     std::lock_guard<std::mutex> autoLock(mutexLock_);
556     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
557     if (admin == nullptr) {
558         EDMLOGW("IsSuperAdmin: admin == nullptr.");
559         return false;
560     }
561     if (admin->adminInfo_.adminType_ == AdminType::ENT) {
562         EDMLOGW("IsSuperAdmin: admin->adminInfo_.adminType_ == AdminType::ENT.");
563         return true;
564     }
565     return false;
566 }
567 
IsAdminEnabled(AppExecFwk::ElementName & admin,int32_t userId)568 bool EnterpriseDeviceMgrAbility::IsAdminEnabled(AppExecFwk::ElementName &admin, int32_t userId)
569 {
570     std::lock_guard<std::mutex> autoLock(mutexLock_);
571     std::shared_ptr<Admin> existAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
572     if (existAdmin != nullptr) {
573         EDMLOGD("IsAdminEnabled: get admin successed");
574         return true;
575     }
576     return false;
577 }
578 
GetCurrentUserId()579 int32_t EnterpriseDeviceMgrAbility::GetCurrentUserId()
580 {
581     std::vector<int32_t> ids;
582     AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
583     EDMLOGD("EnterpriseDeviceMgrAbility GetCurrentUserId user id = %{public}d", ids.at(0));
584     return (ids.at(0));
585 }
586 
HandleDevicePolicy(uint32_t code,AppExecFwk::ElementName & admin,MessageParcel & data)587 ErrCode EnterpriseDeviceMgrAbility::HandleDevicePolicy(uint32_t code, AppExecFwk::ElementName &admin,
588     MessageParcel &data)
589 {
590     std::shared_ptr<Admin> deviceAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), GetCurrentUserId());
591     if (deviceAdmin == nullptr) {
592         EDMLOGW("HandleDevicePolicy: get admin failed");
593         return EdmReturnErrCode::ADMIN_INACTIVE;
594     }
595     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
596     if (plugin == nullptr) {
597         EDMLOGW("HandleDevicePolicy: get plugin failed, code:%{public}d", code);
598         return EdmReturnErrCode::INTERFACE_UNSUPPORTED;
599     }
600     EDMLOGD("HandleDevicePolicy: plugin info:%{public}d , %{public}s , %{public}s", plugin->GetCode(),
601         plugin->GetPolicyName().c_str(), plugin->GetPermission().c_str());
602     if (!deviceAdmin->CheckPermission(plugin->GetPermission())) {
603         EDMLOGW("HandleDevicePolicy: admin check permission failed");
604         return EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED;
605     }
606     if (!VerifyCallingPermission(plugin->GetPermission())) {
607         EDMLOGW("HandleDevicePolicy: VerifyCallingPermission failed");
608         return EdmReturnErrCode::PERMISSION_DENIED;
609     }
610     std::lock_guard<std::mutex> autoLock(mutexLock_);
611     std::string policyName = plugin->GetPolicyName();
612     std::string policyValue = "";
613     policyMgr_->GetPolicy(admin.GetBundleName(), policyName, policyValue);
614     bool isChanged = false;
615     ErrCode ret = plugin->OnHandlePolicy(code, data, policyValue, isChanged);
616     if (FAILED(ret)) {
617         EDMLOGW("HandleDevicePolicy: OnHandlePolicy failed");
618         return ret;
619     }
620 
621     EDMLOGD("HandleDevicePolicy: isChanged:%{public}d, needSave:%{public}d, policyValue:%{public}s\n", isChanged,
622         plugin->NeedSavePolicy(), policyValue.c_str());
623     std::string oldCombinePolicy = "";
624     policyMgr_->GetPolicy("", policyName, oldCombinePolicy);
625     std::string mergedPolicy = policyValue;
626     bool isGlobalChanged = false;
627     if (plugin->NeedSavePolicy() && isChanged) {
628         ret = plugin->MergePolicyData(admin.GetBundleName(), mergedPolicy);
629         if (FAILED(ret)) {
630             EDMLOGW("HandleDevicePolicy: MergePolicyData failed error:%{public}d", ret);
631             return ret;
632         }
633         policyMgr_->SetPolicy(admin.GetBundleName(), policyName, policyValue, mergedPolicy);
634         isGlobalChanged = (oldCombinePolicy != mergedPolicy);
635     }
636     plugin->OnHandlePolicyDone(code, admin.GetBundleName(), isGlobalChanged);
637     return ERR_OK;
638 }
639 
GetDevicePolicy(uint32_t code,AppExecFwk::ElementName * admin,MessageParcel & reply)640 ErrCode EnterpriseDeviceMgrAbility::GetDevicePolicy(uint32_t code, AppExecFwk::ElementName *admin,
641     MessageParcel &reply)
642 {
643     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
644     if (plugin == nullptr) {
645         EDMLOGW("GetDevicePolicy: get plugin failed");
646         reply.WriteInt32(ERR_EDM_GET_PLUGIN_MGR_FAILED);
647         return ERR_EDM_GET_PLUGIN_MGR_FAILED;
648     }
649     std::string policyName = plugin->GetPolicyName();
650     std::string policyValue;
651     std::string adminName = (admin == nullptr) ? "" : admin->GetBundleName();
652     if (policyMgr_->GetPolicy(adminName, policyName, policyValue) != ERR_OK) {
653         EDMLOGW("GetDevicePolicy: get policy failed");
654         reply.WriteInt32(ERR_EDM_POLICY_NOT_FIND);
655     } else {
656         reply.WriteInt32(ERR_OK);
657         plugin->WritePolicyToParcel(policyValue, reply);
658     }
659 
660     return ERR_OK;
661 }
662 
GetEnabledAdmin(AdminType type,std::vector<std::string> & enabledAdminList)663 ErrCode EnterpriseDeviceMgrAbility::GetEnabledAdmin(AdminType type, std::vector<std::string> &enabledAdminList)
664 {
665     std::vector<std::string> superList;
666     std::vector<std::string> normalList;
667     switch (type) {
668         case AdminType::NORMAL:
669             adminMgr_->GetEnabledAdmin(AdminType::NORMAL, normalList, GetCurrentUserId());
670             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
671             break;
672         case AdminType::ENT:
673             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
674             break;
675         case AdminType::UNKNOWN:
676             break;
677         default:
678             return ERR_EDM_PARAM_ERROR;
679     }
680     if (!superList.empty()) {
681         enabledAdminList.insert(enabledAdminList.begin(), superList.begin(), superList.end());
682     }
683     if (!normalList.empty()) {
684         enabledAdminList.insert(enabledAdminList.begin(), normalList.begin(), normalList.end());
685     }
686     for (const auto &enabledAdmin : enabledAdminList) {
687         EDMLOGD("GetEnabledAdmin: %{public}s", enabledAdmin.c_str());
688     }
689     return ERR_OK;
690 }
691 
GetEnterpriseInfo(AppExecFwk::ElementName & admin,MessageParcel & reply)692 ErrCode EnterpriseDeviceMgrAbility::GetEnterpriseInfo(AppExecFwk::ElementName &admin, MessageParcel &reply)
693 {
694     EntInfo entInfo;
695     ErrCode code = adminMgr_->GetEntInfo(admin.GetBundleName(), entInfo, GetCurrentUserId());
696     if (code != ERR_OK) {
697         reply.WriteInt32(EdmReturnErrCode::ADMIN_INACTIVE);
698         return EdmReturnErrCode::ADMIN_INACTIVE;
699     }
700     reply.WriteInt32(ERR_OK);
701     reply.WriteParcelable(&entInfo);
702     EDMLOGD("EnterpriseDeviceMgrAbility::GetEnterpriseInfo: entInfo->enterpriseName %{public}s, "
703         "entInfo->description:%{public}s",
704         entInfo.enterpriseName.c_str(), entInfo.description.c_str());
705     return ERR_OK;
706 }
707 
SetEnterpriseInfo(AppExecFwk::ElementName & admin,EntInfo & entInfo)708 ErrCode EnterpriseDeviceMgrAbility::SetEnterpriseInfo(AppExecFwk::ElementName &admin, EntInfo &entInfo)
709 {
710     std::lock_guard<std::mutex> autoLock(mutexLock_);
711     if (!VerifyCallingPermission(PERMISSION_SET_ENTERPRISE_INFO)) {
712         EDMLOGW("EnterpriseDeviceMgrAbility::SetEnterpriseInfo: check permission failed");
713         return EdmReturnErrCode::PERMISSION_DENIED;
714     }
715     int32_t userId = GetCurrentUserId();
716     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
717     if (adminItem == nullptr) {
718         return EdmReturnErrCode::ADMIN_INACTIVE;
719     }
720     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
721     if (ret != ERR_OK) {
722         EDMLOGW("SetEnterpriseInfo: CheckCallingUid failed: %{public}d", ret);
723         return EdmReturnErrCode::PERMISSION_DENIED;
724     }
725     ErrCode code = adminMgr_->SetEntInfo(admin.GetBundleName(), entInfo, userId);
726     return (code != ERR_OK) ? EdmReturnErrCode::ADMIN_INACTIVE : ERR_OK;
727 }
728 
SubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)729 ErrCode EnterpriseDeviceMgrAbility::SubscribeManagedEvent(const AppExecFwk::ElementName &admin,
730     const std::vector<uint32_t> &events)
731 {
732     return HandleManagedEvent(admin, events, true);
733 }
734 
UnsubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)735 ErrCode EnterpriseDeviceMgrAbility::UnsubscribeManagedEvent(const AppExecFwk::ElementName &admin,
736     const std::vector<uint32_t> &events)
737 {
738     return HandleManagedEvent(admin, events, false);
739 }
740 
HandleManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events,bool subscribe)741 ErrCode EnterpriseDeviceMgrAbility::HandleManagedEvent(const AppExecFwk::ElementName &admin,
742     const std::vector<uint32_t> &events, bool subscribe)
743 {
744     std::lock_guard<std::mutex> autoLock(mutexLock_);
745     if (!VerifyCallingPermission(PERMISSION_ENTERPRISE_SUBSCRIBE_MANAGED_EVENT)) {
746         EDMLOGW("EnterpriseDeviceMgrAbility::HandleManagedEvent: check permission failed");
747         return EdmReturnErrCode::PERMISSION_DENIED;
748     }
749     int32_t userId = GetCurrentUserId();
750     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
751     if (adminItem == nullptr) {
752         return EdmReturnErrCode::ADMIN_INACTIVE;
753     }
754     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
755     if (ret != ERR_OK) {
756         EDMLOGW("SubscribeManagedEvent: CheckCallingUid failed: %{public}d", ret);
757         return EdmReturnErrCode::PERMISSION_DENIED;
758     }
759     if (events.empty()) {
760         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
761     }
762     auto iter = std::find_if(events.begin(), events.end(), [this](uint32_t event) {
763         return !CheckManagedEvent(event);
764     });
765     if (iter != std::end(events)) {
766         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
767     }
768     if (subscribe) {
769         adminMgr_->SaveSubscribeEvents(events, adminItem, userId);
770     } else {
771         adminMgr_->RemoveSubscribeEvents(events, adminItem, userId);
772     }
773     return ERR_OK;
774 }
775 
CheckManagedEvent(uint32_t event)776 bool EnterpriseDeviceMgrAbility::CheckManagedEvent(uint32_t event)
777 {
778     switch (event) {
779         case static_cast<uint32_t>(ManagedEvent::BUNDLE_ADDED):
780         case static_cast<uint32_t>(ManagedEvent::BUNDLE_REMOVED):
781             break;
782         default:
783             return false;
784     }
785     return true;
786 }
787 } // namespace EDM
788 } // namespace OHOS