• 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         abilityInfo.empty()) {
372         EDMLOGW("EnableAdmin: QueryExtensionAbilityInfos failed");
373         return EdmReturnErrCode::COMPONENT_INVALID;
374     }
375     if (FAILED(VerifyEnableAdminCondition(admin, type, userId))) {
376         EDMLOGW("EnableAdmin: VerifyEnableAdminCondition failed.");
377         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
378     }
379 
380     /* Get all request and registered permissions */
381     std::vector<std::string> permissionList;
382     if (FAILED(GetAllPermissionsByAdmin(admin.GetBundleName(), permissionList, userId))) {
383         EDMLOGW("EnableAdmin: GetAllPermissionsByAdmin failed");
384         return EdmReturnErrCode::COMPONENT_INVALID;
385     }
386     /* Filter permissions with AdminType, such as NORMAL can't request super permission */
387     if (FAILED(adminMgr_->GetGrantedPermission(abilityInfo.at(0), permissionList, type))) {
388         EDMLOGW("EnableAdmin: GetGrantedPermission failed");
389         // permission verify, should throw exception if failed
390         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
391     }
392     if (FAILED(adminMgr_->SetAdminValue(abilityInfo.at(0), entInfo, type, permissionList, userId))) {
393         EDMLOGE("EnableAdmin: SetAdminValue failed.");
394         return EdmReturnErrCode::ENABLE_ADMIN_FAILED;
395     }
396     EDMLOGI("EnableAdmin: SetAdminValue success %{public}s, type:%{public}d", admin.GetBundleName().c_str(),
397         static_cast<uint32_t>(type));
398     AAFwk::Want connectWant;
399     connectWant.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
400     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
401     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(connectWant,
402         IEnterpriseAdmin::COMMAND_ON_ADMIN_ENABLED, userId);
403     manager->ConnectAbility(connection);
404     return ERR_OK;
405 }
406 
RemoveAdminItem(std::string adminName,std::string policyName,std::string policyValue)407 ErrCode EnterpriseDeviceMgrAbility::RemoveAdminItem(std::string adminName, std::string policyName,
408     std::string policyValue)
409 {
410     ErrCode ret;
411     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByPolicyName(policyName);
412     if (plugin == nullptr) {
413         EDMLOGW("RemoveAdminItem: Get plugin by policy failed: %{public}s\n", policyName.c_str());
414         return ERR_EDM_GET_PLUGIN_MGR_FAILED;
415     }
416     if ((ret = plugin->OnAdminRemove(adminName, policyValue)) != ERR_OK) {
417         EDMLOGW("RemoveAdminItem: OnAdminRemove failed, admin:%{public}s, value:%{public}s, res:%{public}d\n",
418             adminName.c_str(), policyValue.c_str(), ret);
419     }
420     if (plugin->NeedSavePolicy()) {
421         std::string mergedPolicyData = "";
422         if ((ret = plugin->MergePolicyData(adminName, mergedPolicyData)) != ERR_OK) {
423             EDMLOGW("RemoveAdminItem: Get admin by policy name failed: %{public}s, ErrCode:%{public}d\n",
424                 policyName.c_str(), ret);
425         }
426 
427         ErrCode setRet = ERR_OK;
428         std::unordered_map<std::string, std::string> adminListMap;
429         ret = policyMgr_->GetAdminByPolicyName(policyName, adminListMap);
430         if ((ret == ERR_EDM_POLICY_NOT_FOUND) || adminListMap.empty()) {
431             setRet = policyMgr_->SetPolicy("", policyName, "", "");
432         } else {
433             setRet = policyMgr_->SetPolicy(adminName, policyName, "", mergedPolicyData);
434         }
435 
436         if (FAILED(setRet)) {
437             EDMLOGW("RemoveAdminItem: DeleteAdminPolicy failed, admin:%{public}s, policy:%{public}s, res:%{public}d\n",
438                 adminName.c_str(), policyName.c_str(), ret);
439             return ERR_EDM_DEL_ADMIN_FAILED;
440         }
441     }
442     plugin->OnAdminRemoveDone(adminName, policyValue);
443     return ERR_OK;
444 }
445 
RemoveAdmin(const std::string & adminName,int32_t userId)446 ErrCode EnterpriseDeviceMgrAbility::RemoveAdmin(const std::string &adminName, int32_t userId)
447 {
448     EDMLOGD("RemoveAdmin %{public}s, user id = %{public}d", adminName.c_str(), userId);
449     std::unordered_map<std::string, std::string> policyItems;
450     policyMgr_->GetAllPolicyByAdmin(adminName, policyItems);
451     for (const auto &policyItem : policyItems) {
452         std::string policyItemName = policyItem.first;
453         std::string policyItemValue = policyItem.second;
454         EDMLOGD("RemoveAdmin: RemoveAdminItem policyName:%{public}s,policyValue:%{public}s", policyItemName.c_str(),
455             policyItemValue.c_str());
456         if (RemoveAdminItem(adminName, policyItemName, policyItemValue) != ERR_OK) {
457             return ERR_EDM_DEL_ADMIN_FAILED;
458         }
459     }
460     if (adminMgr_->DeleteAdmin(adminName, userId) != ERR_OK) {
461         return ERR_EDM_DEL_ADMIN_FAILED;
462     }
463     return ERR_OK;
464 }
465 
DisableAdmin(AppExecFwk::ElementName & admin,int32_t userId)466 ErrCode EnterpriseDeviceMgrAbility::DisableAdmin(AppExecFwk::ElementName &admin, int32_t userId)
467 {
468     EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin user id = %{public}d", userId);
469     std::lock_guard<std::mutex> autoLock(mutexLock_);
470     if (!IsHdc() && !VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
471         EDMLOGW("EnterpriseDeviceMgrAbility::DisableAdmin check permission failed");
472         return EdmReturnErrCode::PERMISSION_DENIED;
473     }
474 
475     std::shared_ptr<Admin> adminPtr = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
476     if (adminPtr == nullptr) {
477         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
478     }
479     if (adminPtr->adminInfo_.adminType_ != AdminType::NORMAL) {
480         EDMLOGW("DisableAdmin: only remove normal admin.");
481         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
482     }
483 
484     if (FAILED(RemoveAdmin(admin.GetBundleName(), userId))) {
485         EDMLOGW("DisableAdmin: disable admin failed.");
486         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
487     }
488     AAFwk::Want want;
489     want.SetElementName(admin.GetBundleName(), admin.GetAbilityName());
490     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
491     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(want,
492         IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, userId);
493     manager->ConnectAbility(connection);
494     return ERR_OK;
495 }
496 
IsHdc()497 bool EnterpriseDeviceMgrAbility::IsHdc()
498 {
499     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
500     Security::AccessToken::ATokenTypeEnum tokenType =
501         Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
502     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
503         EDMLOGI("caller tokenType is shell, verify success");
504         return true;
505     }
506     return false;
507 }
508 
CheckCallingUid(std::string & bundleName)509 ErrCode EnterpriseDeviceMgrAbility::CheckCallingUid(std::string &bundleName)
510 {
511     // super admin can be removed by itself
512     int uid = GetCallingUid();
513     auto bundleManager = GetBundleMgr();
514     std::string callingBundleName;
515     if (bundleManager->GetNameForUid(uid, callingBundleName) != ERR_OK) {
516         EDMLOGW("CheckCallingUid failed: get bundleName for uid %{public}d fail.", uid);
517         return ERR_EDM_PERMISSION_ERROR;
518     }
519     if (bundleName == callingBundleName) {
520         return ERR_OK;
521     }
522     EDMLOGW("CheckCallingUid failed: only the app %{public}s can remove itself.", callingBundleName.c_str());
523     return ERR_EDM_PERMISSION_ERROR;
524 }
525 
DisableSuperAdmin(std::string & bundleName)526 ErrCode EnterpriseDeviceMgrAbility::DisableSuperAdmin(std::string &bundleName)
527 {
528     std::lock_guard<std::mutex> autoLock(mutexLock_);
529     if (!VerifyCallingPermission(PERMISSION_MANAGE_ENTERPRISE_DEVICE_ADMIN)) {
530         EDMLOGW("EnterpriseDeviceMgrAbility::DisableSuperAdmin check permission failed.");
531         return EdmReturnErrCode::PERMISSION_DENIED;
532     }
533     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
534     if (admin == nullptr) {
535         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
536     }
537     if (admin->adminInfo_.adminType_ != AdminType::ENT) {
538         EDMLOGW("DisableSuperAdmin: only remove super admin.");
539         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
540     }
541     if (FAILED(RemoveAdmin(bundleName, DEFAULT_USER_ID))) {
542         EDMLOGW("DisableSuperAdmin: RemoveAdmin(bundleName, DEFAULT_USER_ID) failed");
543         return EdmReturnErrCode::DISABLE_ADMIN_FAILED;
544     }
545     AAFwk::Want want;
546     want.SetElementName(admin->adminInfo_.packageName_, admin->adminInfo_.className_);
547     std::shared_ptr<EnterpriseConnManager> manager = DelayedSingleton<EnterpriseConnManager>::GetInstance();
548     sptr<IEnterpriseConnection> connection = manager->CreateAdminConnection(want,
549         IEnterpriseAdmin::COMMAND_ON_ADMIN_DISABLED, DEFAULT_USER_ID);
550     manager->ConnectAbility(connection);
551     return ERR_OK;
552 }
553 
IsSuperAdmin(std::string & bundleName)554 bool EnterpriseDeviceMgrAbility::IsSuperAdmin(std::string &bundleName)
555 {
556     std::lock_guard<std::mutex> autoLock(mutexLock_);
557     std::shared_ptr<Admin> admin = adminMgr_->GetAdminByPkgName(bundleName, DEFAULT_USER_ID);
558     if (admin == nullptr) {
559         EDMLOGW("IsSuperAdmin: admin == nullptr.");
560         return false;
561     }
562     if (admin->adminInfo_.adminType_ == AdminType::ENT) {
563         EDMLOGW("IsSuperAdmin: admin->adminInfo_.adminType_ == AdminType::ENT.");
564         return true;
565     }
566     return false;
567 }
568 
IsAdminEnabled(AppExecFwk::ElementName & admin,int32_t userId)569 bool EnterpriseDeviceMgrAbility::IsAdminEnabled(AppExecFwk::ElementName &admin, int32_t userId)
570 {
571     std::lock_guard<std::mutex> autoLock(mutexLock_);
572     std::shared_ptr<Admin> existAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
573     if (existAdmin != nullptr) {
574         EDMLOGD("IsAdminEnabled: get admin successed");
575         return true;
576     }
577     return false;
578 }
579 
GetCurrentUserId()580 int32_t EnterpriseDeviceMgrAbility::GetCurrentUserId()
581 {
582     std::vector<int32_t> ids;
583     ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
584     if (FAILED(ret) || ids.empty()) {
585         EDMLOGE("EnterpriseDeviceMgrAbility GetCurrentUserId failed");
586         return -1;
587     }
588     EDMLOGD("EnterpriseDeviceMgrAbility GetCurrentUserId user id = %{public}d", ids.at(0));
589     return (ids.at(0));
590 }
591 
HandleDevicePolicy(uint32_t code,AppExecFwk::ElementName & admin,MessageParcel & data)592 ErrCode EnterpriseDeviceMgrAbility::HandleDevicePolicy(uint32_t code, AppExecFwk::ElementName &admin,
593     MessageParcel &data)
594 {
595     std::shared_ptr<Admin> deviceAdmin = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), GetCurrentUserId());
596     if (deviceAdmin == nullptr) {
597         EDMLOGW("HandleDevicePolicy: get admin failed");
598         return EdmReturnErrCode::ADMIN_INACTIVE;
599     }
600     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
601     if (plugin == nullptr) {
602         EDMLOGW("HandleDevicePolicy: get plugin failed, code:%{public}d", code);
603         return EdmReturnErrCode::INTERFACE_UNSUPPORTED;
604     }
605     EDMLOGD("HandleDevicePolicy: plugin info:%{public}d , %{public}s , %{public}s", plugin->GetCode(),
606         plugin->GetPolicyName().c_str(), plugin->GetPermission().c_str());
607     if (!deviceAdmin->CheckPermission(plugin->GetPermission())) {
608         EDMLOGW("HandleDevicePolicy: admin check permission failed");
609         return EdmReturnErrCode::ADMIN_EDM_PERMISSION_DENIED;
610     }
611     if (!VerifyCallingPermission(plugin->GetPermission())) {
612         EDMLOGW("HandleDevicePolicy: VerifyCallingPermission failed");
613         return EdmReturnErrCode::PERMISSION_DENIED;
614     }
615     std::lock_guard<std::mutex> autoLock(mutexLock_);
616     std::string policyName = plugin->GetPolicyName();
617     std::string policyValue = "";
618     policyMgr_->GetPolicy(admin.GetBundleName(), policyName, policyValue);
619     bool isChanged = false;
620     ErrCode ret = plugin->OnHandlePolicy(code, data, policyValue, isChanged);
621     if (FAILED(ret)) {
622         EDMLOGW("HandleDevicePolicy: OnHandlePolicy failed");
623         return ret;
624     }
625 
626     EDMLOGD("HandleDevicePolicy: isChanged:%{public}d, needSave:%{public}d, policyValue:%{public}s\n", isChanged,
627         plugin->NeedSavePolicy(), policyValue.c_str());
628     std::string oldCombinePolicy = "";
629     policyMgr_->GetPolicy("", policyName, oldCombinePolicy);
630     std::string mergedPolicy = policyValue;
631     bool isGlobalChanged = false;
632     if (plugin->NeedSavePolicy() && isChanged) {
633         ret = plugin->MergePolicyData(admin.GetBundleName(), mergedPolicy);
634         if (FAILED(ret)) {
635             EDMLOGW("HandleDevicePolicy: MergePolicyData failed error:%{public}d", ret);
636             return ret;
637         }
638         policyMgr_->SetPolicy(admin.GetBundleName(), policyName, policyValue, mergedPolicy);
639         isGlobalChanged = (oldCombinePolicy != mergedPolicy);
640     }
641     plugin->OnHandlePolicyDone(code, admin.GetBundleName(), isGlobalChanged);
642     return ERR_OK;
643 }
644 
GetDevicePolicy(uint32_t code,AppExecFwk::ElementName * admin,MessageParcel & reply)645 ErrCode EnterpriseDeviceMgrAbility::GetDevicePolicy(uint32_t code, AppExecFwk::ElementName *admin,
646     MessageParcel &reply)
647 {
648     std::shared_ptr<IPlugin> plugin = pluginMgr_->GetPluginByFuncCode(code);
649     if (plugin == nullptr) {
650         EDMLOGW("GetDevicePolicy: get plugin failed");
651         reply.WriteInt32(ERR_EDM_GET_PLUGIN_MGR_FAILED);
652         return ERR_EDM_GET_PLUGIN_MGR_FAILED;
653     }
654     std::string policyName = plugin->GetPolicyName();
655     std::string policyValue;
656     std::string adminName = (admin == nullptr) ? "" : admin->GetBundleName();
657     if (policyMgr_->GetPolicy(adminName, policyName, policyValue) != ERR_OK) {
658         EDMLOGW("GetDevicePolicy: get policy failed");
659         reply.WriteInt32(ERR_EDM_POLICY_NOT_FIND);
660     } else {
661         reply.WriteInt32(ERR_OK);
662         plugin->WritePolicyToParcel(policyValue, reply);
663     }
664 
665     return ERR_OK;
666 }
667 
GetEnabledAdmin(AdminType type,std::vector<std::string> & enabledAdminList)668 ErrCode EnterpriseDeviceMgrAbility::GetEnabledAdmin(AdminType type, std::vector<std::string> &enabledAdminList)
669 {
670     std::vector<std::string> superList;
671     std::vector<std::string> normalList;
672     switch (type) {
673         case AdminType::NORMAL:
674             adminMgr_->GetEnabledAdmin(AdminType::NORMAL, normalList, GetCurrentUserId());
675             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
676             break;
677         case AdminType::ENT:
678             adminMgr_->GetEnabledAdmin(AdminType::ENT, superList, DEFAULT_USER_ID);
679             break;
680         case AdminType::UNKNOWN:
681             break;
682         default:
683             return ERR_EDM_PARAM_ERROR;
684     }
685     if (!superList.empty()) {
686         enabledAdminList.insert(enabledAdminList.begin(), superList.begin(), superList.end());
687     }
688     if (!normalList.empty()) {
689         enabledAdminList.insert(enabledAdminList.begin(), normalList.begin(), normalList.end());
690     }
691     for (const auto &enabledAdmin : enabledAdminList) {
692         EDMLOGD("GetEnabledAdmin: %{public}s", enabledAdmin.c_str());
693     }
694     return ERR_OK;
695 }
696 
GetEnterpriseInfo(AppExecFwk::ElementName & admin,MessageParcel & reply)697 ErrCode EnterpriseDeviceMgrAbility::GetEnterpriseInfo(AppExecFwk::ElementName &admin, MessageParcel &reply)
698 {
699     EntInfo entInfo;
700     ErrCode code = adminMgr_->GetEntInfo(admin.GetBundleName(), entInfo, GetCurrentUserId());
701     if (code != ERR_OK) {
702         reply.WriteInt32(EdmReturnErrCode::ADMIN_INACTIVE);
703         return EdmReturnErrCode::ADMIN_INACTIVE;
704     }
705     reply.WriteInt32(ERR_OK);
706     reply.WriteParcelable(&entInfo);
707     EDMLOGD("EnterpriseDeviceMgrAbility::GetEnterpriseInfo: entInfo->enterpriseName %{public}s, "
708         "entInfo->description:%{public}s",
709         entInfo.enterpriseName.c_str(), entInfo.description.c_str());
710     return ERR_OK;
711 }
712 
SetEnterpriseInfo(AppExecFwk::ElementName & admin,EntInfo & entInfo)713 ErrCode EnterpriseDeviceMgrAbility::SetEnterpriseInfo(AppExecFwk::ElementName &admin, EntInfo &entInfo)
714 {
715     std::lock_guard<std::mutex> autoLock(mutexLock_);
716     if (!VerifyCallingPermission(PERMISSION_SET_ENTERPRISE_INFO)) {
717         EDMLOGW("EnterpriseDeviceMgrAbility::SetEnterpriseInfo: check permission failed");
718         return EdmReturnErrCode::PERMISSION_DENIED;
719     }
720     int32_t userId = GetCurrentUserId();
721     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
722     if (adminItem == nullptr) {
723         return EdmReturnErrCode::ADMIN_INACTIVE;
724     }
725     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
726     if (ret != ERR_OK) {
727         EDMLOGW("SetEnterpriseInfo: CheckCallingUid failed: %{public}d", ret);
728         return EdmReturnErrCode::PERMISSION_DENIED;
729     }
730     ErrCode code = adminMgr_->SetEntInfo(admin.GetBundleName(), entInfo, userId);
731     return (code != ERR_OK) ? EdmReturnErrCode::ADMIN_INACTIVE : ERR_OK;
732 }
733 
SubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)734 ErrCode EnterpriseDeviceMgrAbility::SubscribeManagedEvent(const AppExecFwk::ElementName &admin,
735     const std::vector<uint32_t> &events)
736 {
737     return HandleManagedEvent(admin, events, true);
738 }
739 
UnsubscribeManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events)740 ErrCode EnterpriseDeviceMgrAbility::UnsubscribeManagedEvent(const AppExecFwk::ElementName &admin,
741     const std::vector<uint32_t> &events)
742 {
743     return HandleManagedEvent(admin, events, false);
744 }
745 
HandleManagedEvent(const AppExecFwk::ElementName & admin,const std::vector<uint32_t> & events,bool subscribe)746 ErrCode EnterpriseDeviceMgrAbility::HandleManagedEvent(const AppExecFwk::ElementName &admin,
747     const std::vector<uint32_t> &events, bool subscribe)
748 {
749     std::lock_guard<std::mutex> autoLock(mutexLock_);
750     if (!VerifyCallingPermission(PERMISSION_ENTERPRISE_SUBSCRIBE_MANAGED_EVENT)) {
751         EDMLOGW("EnterpriseDeviceMgrAbility::HandleManagedEvent: check permission failed");
752         return EdmReturnErrCode::PERMISSION_DENIED;
753     }
754     int32_t userId = GetCurrentUserId();
755     std::shared_ptr<Admin> adminItem = adminMgr_->GetAdminByPkgName(admin.GetBundleName(), userId);
756     if (adminItem == nullptr) {
757         return EdmReturnErrCode::ADMIN_INACTIVE;
758     }
759     int32_t ret = CheckCallingUid(adminItem->adminInfo_.packageName_);
760     if (ret != ERR_OK) {
761         EDMLOGW("SubscribeManagedEvent: CheckCallingUid failed: %{public}d", ret);
762         return EdmReturnErrCode::PERMISSION_DENIED;
763     }
764     if (events.empty()) {
765         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
766     }
767     auto iter = std::find_if(events.begin(), events.end(), [this](uint32_t event) {
768         return !CheckManagedEvent(event);
769     });
770     if (iter != std::end(events)) {
771         return EdmReturnErrCode::MANAGED_EVENTS_INVALID;
772     }
773     if (subscribe) {
774         adminMgr_->SaveSubscribeEvents(events, adminItem, userId);
775     } else {
776         adminMgr_->RemoveSubscribeEvents(events, adminItem, userId);
777     }
778     return ERR_OK;
779 }
780 
CheckManagedEvent(uint32_t event)781 bool EnterpriseDeviceMgrAbility::CheckManagedEvent(uint32_t event)
782 {
783     switch (event) {
784         case static_cast<uint32_t>(ManagedEvent::BUNDLE_ADDED):
785         case static_cast<uint32_t>(ManagedEvent::BUNDLE_REMOVED):
786             break;
787         default:
788             return false;
789     }
790     return true;
791 }
792 } // namespace EDM
793 } // namespace OHOS