• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 "bundle_permission_mgr.h"
17 #include "access_token_error.h"
18 #include "app_log_tag_wrapper.h"
19 #include "app_log_wrapper.h"
20 #include "bundle_mgr_service.h"
21 #include "bundle_parser.h"
22 #include "ipc_skeleton.h"
23 #include "parameter.h"
24 #include "privacy_kit.h"
25 #include "tokenid_kit.h"
26 
27 namespace OHOS {
28 namespace AppExecFwk {
29 namespace {
30 // pre bundle profile
31 constexpr const char* INSTALL_LIST_PERMISSIONS_CONFIG = "/etc/app/install_list_permissions.json";
32 constexpr const char* SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
33 // install list permissions file
34 constexpr const char* INSTALL_LIST_PERMISSIONS_FILE_PATH = "/system/etc/app/install_list_permissions.json";
35 constexpr int16_t BASE_API_VERSION = 1000;
36 const char* IS_ROOT_MODE_PARAM = "const.debuggable";
37 const int32_t ROOT_MODE = 1;
38 const int32_t USER_MODE = 0;
39 }
40 
41 using namespace OHOS::Security;
42 std::map<std::string, DefaultPermission> BundlePermissionMgr::defaultPermissions_;
43 
Init()44 bool BundlePermissionMgr::Init()
45 {
46     std::vector<std::string> permissionFileList;
47 #ifdef USE_PRE_BUNDLE_PROFILE
48     std::vector<std::string> rootDirList;
49     BMSEventHandler::GetPreInstallRootDirList(rootDirList);
50     if (rootDirList.empty()) {
51         LOG_E(BMS_TAG_DEFAULT, "rootDirList is empty");
52         return false;
53     }
54     for (const auto &item : rootDirList) {
55         permissionFileList.push_back(item + INSTALL_LIST_PERMISSIONS_CONFIG);
56     }
57 #else
58     permissionFileList.emplace_back(INSTALL_LIST_PERMISSIONS_FILE_PATH);
59 #endif
60     BundleParser bundleParser;
61     std::set<DefaultPermission> permissions;
62     for (const auto &permissionFile : permissionFileList) {
63         if (bundleParser.ParseDefaultPermission(permissionFile, permissions) != ERR_OK) {
64             LOG_D(BMS_TAG_DEFAULT, "BundlePermissionMgr::Init failed");
65             continue;
66         }
67     }
68 
69     defaultPermissions_.clear();
70     for (const auto &permission : permissions) {
71         defaultPermissions_.try_emplace(permission.bundleName, permission);
72     }
73     LOG_D(BMS_TAG_DEFAULT, "BundlePermissionMgr::Init success");
74     return true;
75 }
76 
UnInit()77 void BundlePermissionMgr::UnInit()
78 {
79     LOG_D(BMS_TAG_DEFAULT, "BundlePermissionMgr::UnInit");
80     defaultPermissions_.clear();
81 }
82 
ConvertPermissionDef(const AccessToken::PermissionDef & permDef,PermissionDef & permissionDef)83 void BundlePermissionMgr::ConvertPermissionDef(
84     const AccessToken::PermissionDef &permDef, PermissionDef &permissionDef)
85 {
86     permissionDef.permissionName = permDef.permissionName;
87     permissionDef.bundleName = permDef.bundleName;
88     permissionDef.grantMode = permDef.grantMode;
89     permissionDef.availableLevel = permDef.availableLevel;
90     permissionDef.provisionEnable = permDef.provisionEnable;
91     permissionDef.distributedSceneEnable = permDef.distributedSceneEnable;
92     permissionDef.isKernelEffect = permDef.isKernelEffect;
93     permissionDef.hasValue = permDef.hasValue;
94     permissionDef.label = permDef.label;
95     permissionDef.labelId = permDef.labelId;
96     permissionDef.description = permDef.description;
97     permissionDef.descriptionId = permDef.descriptionId;
98     permissionDef.availableType = permDef.availableType;
99 }
100 
101 // Convert from the struct DefinePermission that parsed from config.json
ConvertPermissionDef(AccessToken::PermissionDef & permDef,const DefinePermission & definePermission,const std::string & bundleName)102 void BundlePermissionMgr::ConvertPermissionDef(
103     AccessToken::PermissionDef &permDef, const DefinePermission &definePermission, const std::string &bundleName)
104 {
105     permDef.permissionName = definePermission.name;
106     permDef.bundleName = bundleName;
107     permDef.grantMode = [&definePermission]() -> int {
108         if (definePermission.grantMode ==
109             Profile::DEFINEPERMISSION_GRANT_MODE_SYSTEM_GRANT) {
110             return AccessToken::GrantMode::SYSTEM_GRANT;
111         }
112         return AccessToken::GrantMode::USER_GRANT;
113     }();
114 
115     permDef.availableLevel = GetTokenApl(definePermission.availableLevel);
116     permDef.provisionEnable = definePermission.provisionEnable;
117     permDef.distributedSceneEnable = definePermission.distributedSceneEnable;
118     permDef.isKernelEffect = definePermission.isKernelEffect;
119     permDef.hasValue = definePermission.hasValue;
120     permDef.label = definePermission.label;
121     permDef.labelId = definePermission.labelId;
122     permDef.description = definePermission.description;
123     permDef.descriptionId = definePermission.descriptionId;
124     permDef.availableType = GetAvailableType(definePermission.availableType);
125 }
126 
GetAvailableType(const std::string & availableType)127 AccessToken::ATokenAvailableTypeEnum BundlePermissionMgr::GetAvailableType(
128     const std::string &availableType)
129 {
130     if (availableType == Profile::DEFINEPERMISSION_AVAILABLE_TYPE_MDM) {
131         return AccessToken::ATokenAvailableTypeEnum::MDM;
132     }
133     return AccessToken::ATokenAvailableTypeEnum::NORMAL;
134 }
135 
GetTokenApl(const std::string & apl)136 AccessToken::ATokenAplEnum BundlePermissionMgr::GetTokenApl(const std::string &apl)
137 {
138     if (apl == Profile::AVAILABLELEVEL_SYSTEM_CORE) {
139         return AccessToken::ATokenAplEnum::APL_SYSTEM_CORE;
140     }
141     if (apl == Profile::AVAILABLELEVEL_SYSTEM_BASIC) {
142         return AccessToken::ATokenAplEnum::APL_SYSTEM_BASIC;
143     }
144     return AccessToken::ATokenAplEnum::APL_NORMAL;
145 }
146 
CreateHapPolicyParam(const InnerBundleInfo & innerBundleInfo,const std::string & appServiceCapabilities)147 AccessToken::HapPolicyParams BundlePermissionMgr::CreateHapPolicyParam(const InnerBundleInfo &innerBundleInfo,
148     const std::string &appServiceCapabilities)
149 {
150     AccessToken::HapPolicyParams hapPolicy;
151     std::string apl = innerBundleInfo.GetAppPrivilegeLevel();
152     std::vector<AccessToken::PermissionDef> permDef = GetPermissionDefList(innerBundleInfo);
153     hapPolicy.apl = GetTokenApl(apl);
154     hapPolicy.domain = "domain";
155     hapPolicy.permList = permDef;
156     hapPolicy.permStateList = GetPermissionStateFullList(innerBundleInfo);
157     hapPolicy.aclRequestedList = innerBundleInfo.GetAllowedAcls();
158     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "-n %{public}s apl:%{public}s req permission size:%{public}zu, acls size:%{public}zu",
159         innerBundleInfo.GetBundleName().c_str(), apl.c_str(), hapPolicy.permStateList.size(),
160         hapPolicy.aclRequestedList.size());
161     BundleParser bundleParser;
162     hapPolicy.aclExtendedMap = bundleParser.ParseAclExtendedMap(appServiceCapabilities);
163     // default permission list
164     DefaultPermission permission;
165     if (!GetDefaultPermission(innerBundleInfo.GetBundleName(), permission)) {
166         return hapPolicy;
167     }
168 
169 #ifdef USE_PRE_BUNDLE_PROFILE
170     if (!MatchSignature(permission, innerBundleInfo.GetCertificateFingerprint()) &&
171         !MatchSignature(permission, innerBundleInfo.GetAppId()) &&
172         !MatchSignature(permission, innerBundleInfo.GetAppIdentifier()) &&
173         !MatchSignature(permission, innerBundleInfo.GetOldAppIds())) {
174         LOG_W(BMS_TAG_DEFAULT, "bundleName:%{public}s MatchSignature failed", innerBundleInfo.GetBundleName().c_str());
175         return hapPolicy;
176     }
177 #endif
178     for (const auto &perm: innerBundleInfo.GetAllRequestPermissions()) {
179         bool userCancellable = false;
180         if (!CheckPermissionInDefaultPermissions(permission, perm.name, userCancellable)) {
181             continue;
182         }
183         AccessToken::PreAuthorizationInfo preAuthorizationInfo;
184         preAuthorizationInfo.permissionName = perm.name;
185         preAuthorizationInfo.userCancelable = userCancellable;
186         hapPolicy.preAuthorizationInfo.emplace_back(preAuthorizationInfo);
187     }
188     LOG_I(BMS_TAG_DEFAULT, "end, preAuthorizationInfo size :%{public}zu", hapPolicy.preAuthorizationInfo.size());
189     return hapPolicy;
190 }
191 
DeleteAccessTokenId(const AccessToken::AccessTokenID tokenId)192 int32_t BundlePermissionMgr::DeleteAccessTokenId(const AccessToken::AccessTokenID tokenId)
193 {
194     return AccessToken::AccessTokenKit::DeleteToken(tokenId);
195 }
196 
ClearUserGrantedPermissionState(const AccessToken::AccessTokenID tokenId)197 int32_t BundlePermissionMgr::ClearUserGrantedPermissionState(const AccessToken::AccessTokenID tokenId)
198 {
199     return AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
200 }
201 
GetPermissionDefList(const InnerBundleInfo & innerBundleInfo)202 std::vector<AccessToken::PermissionDef> BundlePermissionMgr::GetPermissionDefList(
203     const InnerBundleInfo &innerBundleInfo)
204 {
205     const auto bundleName = innerBundleInfo.GetBundleName();
206     const auto defPermissions = innerBundleInfo.GetAllDefinePermissions();
207     std::vector<AccessToken::PermissionDef> permList;
208     if (!defPermissions.empty()) {
209         for (const auto &defPermission : defPermissions) {
210             AccessToken::PermissionDef perm;
211             LOG_D(BMS_TAG_DEFAULT, "defPermission %{public}s", defPermission.name.c_str());
212             ConvertPermissionDef(perm, defPermission, bundleName);
213             permList.emplace_back(perm);
214         }
215     }
216     return permList;
217 }
218 
GetPermissionStateFullList(const InnerBundleInfo & innerBundleInfo)219 std::vector<AccessToken::PermissionStateFull> BundlePermissionMgr::GetPermissionStateFullList(
220     const InnerBundleInfo &innerBundleInfo)
221 {
222     auto reqPermissions = innerBundleInfo.GetAllRequestPermissions();
223     std::vector<AccessToken::PermissionStateFull> permStateFullList;
224     if (!reqPermissions.empty()) {
225         for (const auto &reqPermission : reqPermissions) {
226             AccessToken::PermissionStateFull perState;
227             perState.permissionName = reqPermission.name;
228             perState.isGeneral = true;
229             perState.resDeviceID.emplace_back(innerBundleInfo.GetBaseApplicationInfo().deviceId);
230             perState.grantStatus.emplace_back(AccessToken::PermissionState::PERMISSION_DENIED);
231             perState.grantFlags.emplace_back(AccessToken::PermissionFlag::PERMISSION_DEFAULT_FLAG);
232             permStateFullList.emplace_back(perState);
233         }
234     } else {
235         LOG_D(BMS_TAG_DEFAULT, "BundlePermissionMgr::GetPermissionStateFullList requestPermission is empty");
236     }
237     return permStateFullList;
238 }
239 
GetAllReqPermissionStateFull(AccessToken::AccessTokenID tokenId,std::vector<AccessToken::PermissionStateFull> & newPermissionState)240 bool BundlePermissionMgr::GetAllReqPermissionStateFull(AccessToken::AccessTokenID tokenId,
241     std::vector<AccessToken::PermissionStateFull> &newPermissionState)
242 {
243     std::vector<AccessToken::PermissionStateFull> userGrantReqPermList;
244     int32_t ret = AccessToken::AccessTokenKit::GetReqPermissions(tokenId, userGrantReqPermList, false);
245     if (ret != AccessToken::AccessTokenKitRet::RET_SUCCESS) {
246         LOG_E(BMS_TAG_DEFAULT, "GetAllReqPermissionStateFull get user grant failed errcode: %{public}d", ret);
247         return false;
248     }
249     std::vector<AccessToken::PermissionStateFull> systemGrantReqPermList;
250     ret = AccessToken::AccessTokenKit::GetReqPermissions(tokenId, systemGrantReqPermList, true);
251     if (ret != AccessToken::AccessTokenKitRet::RET_SUCCESS) {
252         LOG_E(BMS_TAG_DEFAULT, "GetAllReqPermissionStateFull get system grant failed errcode: %{public}d", ret);
253         return false;
254     }
255     newPermissionState = userGrantReqPermList;
256     std::copy(systemGrantReqPermList.begin(), systemGrantReqPermList.end(), std::back_inserter(newPermissionState));
257     return true;
258 }
259 
GetRequestPermissionStates(BundleInfo & bundleInfo,uint32_t tokenId,const std::string deviceId)260 bool BundlePermissionMgr::GetRequestPermissionStates(
261     BundleInfo &bundleInfo, uint32_t tokenId, const std::string deviceId)
262 {
263     std::vector<std::string> requestPermission = bundleInfo.reqPermissions;
264     if (requestPermission.empty()) {
265         LOG_D(BMS_TAG_DEFAULT, "GetRequestPermissionStates requestPermission empty");
266         return true;
267     }
268     std::vector<Security::AccessToken::PermissionStateFull> allPermissionState;
269     if (!GetAllReqPermissionStateFull(tokenId, allPermissionState)) {
270         LOG_W(BMS_TAG_DEFAULT, "BundlePermissionMgr::GetRequestPermissionStates failed");
271     }
272     for (auto &req : requestPermission) {
273         auto iter = std::find_if(allPermissionState.begin(), allPermissionState.end(),
274             [req](const auto &perm) {
275                 return perm.permissionName == req;
276             });
277         if (iter != allPermissionState.end()) {
278             LOG_D(BMS_TAG_DEFAULT, "GetRequestPermissionStates request permission name: %{public}s", req.c_str());
279             for (std::vector<std::string>::size_type i = 0; i < iter->resDeviceID.size(); i++) {
280                 if (iter->resDeviceID[i] == deviceId) {
281                     bundleInfo.reqPermissionStates.emplace_back(iter->grantStatus[i]);
282                     break;
283                 }
284             }
285         } else {
286             LOG_NOFUNC_E(BMS_TAG_DEFAULT, "%{public}s not in ATM", req.c_str());
287             bundleInfo.reqPermissionStates.emplace_back(
288                 static_cast<int32_t>(AccessToken::PermissionState::PERMISSION_DENIED));
289         }
290     }
291     return true;
292 }
293 
VerifyPermissionByCallingTokenId(const std::string & permissionName,const Security::AccessToken::AccessTokenID callerToken)294 bool BundlePermissionMgr::VerifyPermissionByCallingTokenId(const std::string &permissionName,
295     const Security::AccessToken::AccessTokenID callerToken)
296 {
297     LOG_D(BMS_TAG_DEFAULT, "VerifyPermissionByCallingTokenId permission %{public}s, callerToken : %{public}u",
298         permissionName.c_str(), callerToken);
299     if (AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName) ==
300         AccessToken::PermissionState::PERMISSION_GRANTED) {
301         return true;
302     }
303     LOG_NOFUNC_W(BMS_TAG_DEFAULT, "permission denied caller:%{public}u", callerToken);
304     return false;
305 }
306 
VerifyCallingPermissionForAll(const std::string & permissionName)307 bool BundlePermissionMgr::VerifyCallingPermissionForAll(const std::string &permissionName)
308 {
309     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
310     LOG_D(BMS_TAG_DEFAULT, "VerifyCallingPermission permission %{public}s, callerToken : %{public}u",
311         permissionName.c_str(), callerToken);
312     if (AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName) ==
313         AccessToken::PermissionState::PERMISSION_GRANTED) {
314         return true;
315     }
316     LOG_NOFUNC_W(BMS_TAG_DEFAULT, "permission denied caller:%{public}u", callerToken);
317     return false;
318 }
319 
VerifyCallingPermissionsForAll(const std::vector<std::string> & permissionNames)320 bool BundlePermissionMgr::VerifyCallingPermissionsForAll(const std::vector<std::string> &permissionNames)
321 {
322     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
323     for (auto permissionName : permissionNames) {
324         if (AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName) ==
325             AccessToken::PermissionState::PERMISSION_GRANTED) {
326             LOG_D(BMS_TAG_DEFAULT, "verify success");
327             return true;
328         }
329     }
330     std::string errorMessage;
331     for (auto deniedPermission : permissionNames) {
332         errorMessage += deniedPermission + " ";
333     }
334     LOG_NOFUNC_W(BMS_TAG_DEFAULT, "%{public}s denied callerToken:%{public}u", errorMessage.c_str(), callerToken);
335     return false;
336 }
337 
VerifyPermission(const std::string & bundleName,const std::string & permissionName,const int32_t userId)338 int32_t BundlePermissionMgr::VerifyPermission(
339     const std::string &bundleName, const std::string &permissionName, const int32_t userId)
340 {
341     LOG_D(BMS_TAG_DEFAULT, "VerifyPermission bundleName %{public}s, permission %{public}s", bundleName.c_str(),
342         permissionName.c_str());
343     AccessToken::AccessTokenID tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId,
344         bundleName, 0);
345     return AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, permissionName);
346 }
347 
GetPermissionDef(const std::string & permissionName,PermissionDef & permissionDef)348 ErrCode BundlePermissionMgr::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef)
349 {
350     LOG_D(BMS_TAG_DEFAULT, "BundlePermissionMgr::GetPermissionDef permission %{public}s", permissionName.c_str());
351     AccessToken::PermissionDef accessTokenPermDef;
352     int32_t ret = AccessToken::AccessTokenKit::GetDefPermission(permissionName, accessTokenPermDef);
353     if (ret == AccessToken::AccessTokenKitRet::RET_SUCCESS) {
354         ConvertPermissionDef(accessTokenPermDef, permissionDef);
355         return ERR_OK;
356     }
357     return ERR_BUNDLE_MANAGER_QUERY_PERMISSION_DEFINE_FAILED;
358 }
359 
CheckPermissionInDefaultPermissions(const DefaultPermission & defaultPermission,const std::string & permissionName,bool & userCancellable)360 bool BundlePermissionMgr::CheckPermissionInDefaultPermissions(const DefaultPermission &defaultPermission,
361     const std::string &permissionName, bool &userCancellable)
362 {
363     auto &grantPermission = defaultPermission.grantPermission;
364     auto iter = std::find_if(grantPermission.begin(), grantPermission.end(), [&permissionName](const auto &defPerm) {
365             return defPerm.name == permissionName;
366         });
367     if (iter == grantPermission.end()) {
368         LOG_D(BMS_TAG_DEFAULT, "can not find permission(%{public}s)", permissionName.c_str());
369         return false;
370     }
371 
372     userCancellable = iter->userCancellable;
373     return true;
374 }
375 
GetDefaultPermission(const std::string & bundleName,DefaultPermission & permission)376 bool BundlePermissionMgr::GetDefaultPermission(
377     const std::string &bundleName, DefaultPermission &permission)
378 {
379     auto iter = defaultPermissions_.find(bundleName);
380     if (iter == defaultPermissions_.end()) {
381         LOG_NOFUNC_W(BMS_TAG_DEFAULT, "-n %{public}s not exist in defaultPermissions",
382             bundleName.c_str());
383         return false;
384     }
385 
386     permission = iter->second;
387     return true;
388 }
389 
MatchSignature(const DefaultPermission & permission,const std::vector<std::string> & signatures)390 bool BundlePermissionMgr::MatchSignature(
391     const DefaultPermission &permission, const std::vector<std::string> &signatures)
392 {
393     if (permission.appSignature.empty()) {
394         LOG_W(BMS_TAG_DEFAULT, "appSignature is empty");
395         return false;
396     }
397     for (const auto &signature : permission.appSignature) {
398         if (std::find(signatures.begin(), signatures.end(), signature) != signatures.end()) {
399             return true;
400         }
401     }
402 
403     return false;
404 }
405 
MatchSignature(const DefaultPermission & permission,const std::string & signature)406 bool BundlePermissionMgr::MatchSignature(
407     const DefaultPermission &permission, const std::string &signature)
408 {
409     if (permission.appSignature.empty() || signature.empty()) {
410         LOG_W(BMS_TAG_DEFAULT, "appSignature or signature is empty");
411         return false;
412     }
413     return std::find(permission.appSignature.begin(), permission.appSignature.end(),
414         signature) != permission.appSignature.end();
415 }
416 
GetHapApiVersion()417 int32_t BundlePermissionMgr::GetHapApiVersion()
418 {
419     // get appApiVersion from applicationInfo
420     std::string bundleName;
421     auto uid = IPCSkeleton::GetCallingUid();
422     auto userId = uid / Constants::BASE_USER_RANGE;
423     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
424     if (dataMgr == nullptr) {
425         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
426         return Constants::INVALID_API_VERSION;
427     }
428     auto ret = dataMgr->GetBundleNameForUid(uid, bundleName);
429     if (!ret) {
430         LOG_E(BMS_TAG_DEFAULT, "getBundleName failed, uid : %{public}d", uid);
431         return Constants::INVALID_API_VERSION;
432     }
433     ApplicationInfo applicationInfo;
434     auto res = dataMgr->GetApplicationInfoV9(bundleName,
435         static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE), userId, applicationInfo);
436     if (res != ERR_OK) {
437         LOG_E(BMS_TAG_DEFAULT, "getApplicationInfo failed");
438         return Constants::INVALID_API_VERSION;
439     }
440     auto appApiVersion = applicationInfo.apiTargetVersion % BASE_API_VERSION;
441     LOG_D(BMS_TAG_DEFAULT, "appApiVersion is %{public}d", appApiVersion);
442     auto systemApiVersion = GetSdkApiVersion();
443     // api version is the minimum value of {appApiVersion, systemApiVersion}
444     return systemApiVersion < appApiVersion ? systemApiVersion :appApiVersion;
445 }
446 
447 // if the api has been system api since it is published, then beginSystemApiVersion can be omitted
VerifySystemApp(int32_t beginSystemApiVersion)448 bool BundlePermissionMgr::VerifySystemApp(int32_t beginSystemApiVersion)
449 {
450     LOG_D(BMS_TAG_DEFAULT, "verifying systemApp");
451     uint64_t accessTokenIdEx = IPCSkeleton::GetCallingFullTokenID();
452     if (Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(accessTokenIdEx)) {
453         return true;
454     }
455     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
456     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
457     LOG_D(BMS_TAG_DEFAULT, "tokenType is %{private}d", tokenType);
458     int32_t callingUid = IPCSkeleton::GetCallingUid();
459     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
460         tokenType == AccessToken::ATokenTypeEnum::TOKEN_SHELL ||
461         callingUid == Constants::ROOT_UID ||
462         callingUid == ServiceConstants::SHELL_UID) {
463         LOG_D(BMS_TAG_DEFAULT, "caller tokenType is native, verify success");
464         return true;
465     }
466     if (beginSystemApiVersion != Constants::ALL_VERSIONCODE) {
467         auto apiVersion = GetHapApiVersion();
468         if (apiVersion == Constants::INVALID_API_VERSION) {
469             LOG_E(BMS_TAG_DEFAULT, "get api version failed, system app verification failed");
470             return false;
471         }
472         if (apiVersion < beginSystemApiVersion) {
473             LOG_I(BMS_TAG_DEFAULT, "previous app calling, verify success");
474             return true;
475         }
476     }
477     LOG_E(BMS_TAG_DEFAULT, "system app verification failed");
478     return false;
479 }
480 
IsSystemApp()481 bool BundlePermissionMgr::IsSystemApp()
482 {
483     LOG_D(BMS_TAG_DEFAULT, "verifying systemApp");
484     uint64_t accessTokenIdEx = IPCSkeleton::GetCallingFullTokenID();
485     if (Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(accessTokenIdEx)) {
486         return true;
487     }
488     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
489     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
490     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
491         LOG_W(BMS_TAG_DEFAULT, "IsSystemApp %{public}d,%{public}d,%{public}u",
492             IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid(), callerToken);
493         return false;
494     }
495     LOG_D(BMS_TAG_DEFAULT, "caller tokenType is not hap, ignore");
496     return true;
497 }
498 
IsNativeTokenType()499 bool BundlePermissionMgr::IsNativeTokenType()
500 {
501     LOG_D(BMS_TAG_DEFAULT, "begin to verify token type");
502     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
503     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
504     LOG_D(BMS_TAG_DEFAULT, "tokenType is %{private}d", tokenType);
505     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_NATIVE
506         || tokenType == AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
507         LOG_D(BMS_TAG_DEFAULT, "caller tokenType is native, verify success");
508         return true;
509     }
510     if (VerifyCallingUid()) {
511         LOG_D(BMS_TAG_DEFAULT, "caller is root or foundation or BMS_UID, verify success");
512         return true;
513     }
514     LOG_E(BMS_TAG_DEFAULT, "caller tokenType not native, verify failed");
515     return false;
516 }
517 
IsShellTokenType()518 bool BundlePermissionMgr::IsShellTokenType()
519 {
520     LOG_D(BMS_TAG_DEFAULT, "IsShellTokenType begin");
521     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
522     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
523     LOG_D(BMS_TAG_DEFAULT, "tokenType is %{private}d", tokenType);
524     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_SHELL) {
525         LOG_D(BMS_TAG_DEFAULT, "caller is shell, success");
526         return true;
527     }
528     LOG_I(BMS_TAG_DEFAULT, "caller not shell");
529     return false;
530 }
531 
VerifyCallingUid()532 bool BundlePermissionMgr::VerifyCallingUid()
533 {
534     LOG_D(BMS_TAG_DEFAULT, "begin to verify calling uid");
535     int32_t callingUid = IPCSkeleton::GetCallingUid();
536     LOG_D(BMS_TAG_DEFAULT, "calling uid is %{public}d", callingUid);
537     if (callingUid == Constants::ROOT_UID ||
538         callingUid == Constants::FOUNDATION_UID ||
539         callingUid == ServiceConstants::SHELL_UID ||
540         callingUid == ServiceConstants::BMS_UID) {
541         LOG_D(BMS_TAG_DEFAULT, "caller is root or foundation, verify success");
542         return true;
543     }
544     LOG_E(BMS_TAG_DEFAULT, "verify calling uid failed");
545     return false;
546 }
547 
VerifyPreload(const AAFwk::Want & want)548 bool BundlePermissionMgr::VerifyPreload(const AAFwk::Want &want)
549 {
550     std::string callingBundleName;
551     auto uid = IPCSkeleton::GetCallingUid();
552     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
553     if (dataMgr == nullptr) {
554         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
555         return false;
556     }
557     auto ret = dataMgr->GetBundleNameForUid(uid, callingBundleName);
558     if (!ret) {
559         return BundlePermissionMgr::VerifyCallingPermissionForAll(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED);
560     }
561     std::string bundleName = want.GetElement().GetBundleName();
562     return bundleName == callingBundleName || callingBundleName == SCENEBOARD_BUNDLE_NAME;
563 }
564 
IsCallingUidValid(int32_t uid)565 bool BundlePermissionMgr::IsCallingUidValid(int32_t uid)
566 {
567     int32_t callingUid = IPCSkeleton::GetCallingUid();
568     if (callingUid == uid) {
569         return true;
570     }
571     LOG_E(BMS_TAG_DEFAULT, "IsCallingUidValid failed, uid = %{public}d, calling uid = %{public}d", uid, callingUid);
572     return false;
573 }
574 
IsSelfCalling()575 bool BundlePermissionMgr::IsSelfCalling()
576 {
577     int32_t callingUid = IPCSkeleton::GetCallingUid();
578     if (callingUid == Constants::FOUNDATION_UID) {
579         return true;
580     }
581     return false;
582 }
583 
VerifyUninstallPermission()584 bool BundlePermissionMgr::VerifyUninstallPermission()
585 {
586     if (!BundlePermissionMgr::IsSelfCalling() &&
587         !BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_INSTALL_BUNDLE,
588         ServiceConstants::PERMISSION_UNINSTALL_BUNDLE})) {
589         LOG_E(BMS_TAG_DEFAULT, "uninstall bundle permission denied");
590         return false;
591     }
592     return true;
593 }
594 
VerifyRecoverPermission()595 bool BundlePermissionMgr::VerifyRecoverPermission()
596 {
597     if (!BundlePermissionMgr::IsSelfCalling() &&
598         !BundlePermissionMgr::VerifyCallingPermissionsForAll({Constants::PERMISSION_INSTALL_BUNDLE,
599         ServiceConstants::PERMISSION_RECOVER_BUNDLE})) {
600         LOG_E(BMS_TAG_DEFAULT, "recover bundle permission denied");
601         return false;
602     }
603     return true;
604 }
605 
AddPermissionUsedRecord(const std::string & permission,int32_t successCount,int32_t failCount)606 void BundlePermissionMgr::AddPermissionUsedRecord(
607     const std::string &permission, int32_t successCount, int32_t failCount)
608 {
609     LOG_D(BMS_TAG_DEFAULT, "AddPermissionUsedRecord permission:%{public}s", permission.c_str());
610     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
611     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
612     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
613         int32_t ret = AccessToken::PrivacyKit::AddPermissionUsedRecord(callerToken, permission,
614             successCount, failCount);
615         if (ret != AccessToken::AccessTokenKitRet::RET_SUCCESS) {
616             APP_LOGE("AddPermissionUsedRecord failed, ret = %{public}d", ret);
617         }
618     }
619 }
620 
IsBundleSelfCalling(const std::string & bundleName)621 bool BundlePermissionMgr::IsBundleSelfCalling(const std::string &bundleName)
622 {
623     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
624     if (dataMgr == nullptr) {
625         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
626         return false;
627     }
628     int32_t callingUid = IPCSkeleton::GetCallingUid();
629     LOG_D(BMS_TAG_DEFAULT, "start, callingUid: %{public}d", callingUid);
630     std::string callingBundleName;
631     if (dataMgr->GetNameForUid(callingUid, callingBundleName) != ERR_OK) {
632         return false;
633     }
634     LOG_D(BMS_TAG_DEFAULT, "bundleName :%{public}s, callingBundleName : %{public}s",
635         bundleName.c_str(), callingBundleName.c_str());
636     if (bundleName != callingBundleName) {
637         LOG_W(BMS_TAG_DEFAULT, "failed, callingUid: %{public}d", callingUid);
638         return false;
639     }
640     LOG_D(BMS_TAG_DEFAULT, "end, verify success");
641     return true;
642 }
643 
IsBundleSelfCalling(const std::string & bundleName,const int32_t & appIndex)644 bool BundlePermissionMgr::IsBundleSelfCalling(const std::string &bundleName, const int32_t &appIndex)
645 {
646     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
647     if (dataMgr == nullptr) {
648         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
649         return false;
650     }
651     int32_t callingUid = IPCSkeleton::GetCallingUid();
652     LOG_D(BMS_TAG_DEFAULT, "start, callingUid: %{public}d", callingUid);
653     std::string callingBundleName;
654     int32_t callerAppIndex = 0;
655     ErrCode ret = dataMgr->GetBundleNameAndIndexForUid(callingUid, callingBundleName, callerAppIndex);
656     if (ret != ERR_OK) {
657         LOG_E(BMS_TAG_DEFAULT, "failed, code: %{public}d", ret);
658         return false;
659     }
660     LOG_D(BMS_TAG_DEFAULT,
661         "bundleName :%{public}s, callingBundleName : %{public}s appIndex: %{public}d callerAppIndex: %{public}d",
662         bundleName.c_str(), callingBundleName.c_str(), appIndex, callerAppIndex);
663     if (bundleName != callingBundleName || appIndex != callerAppIndex) {
664         LOG_W(BMS_TAG_DEFAULT, "failed, callingUid: %{public}d", callingUid);
665         return false;
666     }
667     LOG_D(BMS_TAG_DEFAULT, "end, verify success");
668     return true;
669 }
670 
VerifyCallingBundleSdkVersion(int32_t beginApiVersion)671 bool BundlePermissionMgr::VerifyCallingBundleSdkVersion(int32_t beginApiVersion)
672 {
673     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
674     if (dataMgr == nullptr) {
675         LOG_E(BMS_TAG_DEFAULT, "DataMgr is nullptr");
676         return false;
677     }
678     int32_t callingUid = IPCSkeleton::GetCallingUid();
679     LOG_D(BMS_TAG_DEFAULT, "start, callingUid: %{public}d", callingUid);
680     std::string callingBundleName;
681     if (dataMgr->GetNameForUid(callingUid, callingBundleName) != ERR_OK) {
682         return false;
683     }
684     auto userId = callingUid / Constants::BASE_USER_RANGE;
685     ApplicationInfo applicationInfo;
686     auto res = dataMgr->GetApplicationInfoV9(callingBundleName,
687         static_cast<int32_t>(GetApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE), userId, applicationInfo);
688     if (res != ERR_OK) {
689         LOG_E(BMS_TAG_DEFAULT, "getApplicationInfo failed, callingBundleName:%{public}s", callingBundleName.c_str());
690         return false;
691     }
692     auto systemApiVersion = GetSdkApiVersion();
693     auto appApiVersion = applicationInfo.apiTargetVersion;
694     // api version is the minimum value of {appApiVersion, systemApiVersion}
695     appApiVersion = systemApiVersion < appApiVersion ? systemApiVersion : appApiVersion;
696     LOG_D(BMS_TAG_DEFAULT, "appApiVersion: %{public}d", appApiVersion);
697 
698     if ((appApiVersion % BASE_API_VERSION) < beginApiVersion) {
699         LOG_I(BMS_TAG_DEFAULT, "previous app calling, verify success");
700         return true;
701     }
702     return false;
703 }
704 
CreateHapInfoParams(const InnerBundleInfo & innerBundleInfo,const int32_t userId,const int32_t dlpType)705 Security::AccessToken::HapInfoParams BundlePermissionMgr::CreateHapInfoParams(const InnerBundleInfo &innerBundleInfo,
706     const int32_t userId, const int32_t dlpType)
707 {
708     AccessToken::HapInfoParams hapInfo;
709     hapInfo.userID = userId;
710     hapInfo.bundleName = innerBundleInfo.GetBundleName();
711     hapInfo.instIndex = innerBundleInfo.GetAppIndex();
712     hapInfo.appIDDesc = innerBundleInfo.GetAppId();
713     hapInfo.dlpType = dlpType;
714     hapInfo.apiVersion = innerBundleInfo.GetBaseApplicationInfo().apiTargetVersion;
715     hapInfo.isSystemApp = innerBundleInfo.IsSystemApp();
716     hapInfo.appDistributionType = innerBundleInfo.GetAppDistributionType();
717     hapInfo.isAtomicService = innerBundleInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE;
718     return hapInfo;
719 }
720 
InitHapToken(const InnerBundleInfo & innerBundleInfo,const int32_t userId,const int32_t dlpType,Security::AccessToken::AccessTokenIDEx & tokenIdeEx,Security::AccessToken::HapInfoCheckResult & checkResult,const std::string & appServiceCapabilities)721 int32_t BundlePermissionMgr::InitHapToken(const InnerBundleInfo &innerBundleInfo, const int32_t userId,
722     const int32_t dlpType, Security::AccessToken::AccessTokenIDEx& tokenIdeEx,
723     Security::AccessToken::HapInfoCheckResult &checkResult, const std::string &appServiceCapabilities)
724 {
725     LOG_I(BMS_TAG_DEFAULT, "start, init hap token bundleName:%{public}s", innerBundleInfo.GetBundleName().c_str());
726     AccessToken::HapInfoParams hapInfo = CreateHapInfoParams(innerBundleInfo, userId, dlpType);
727     AccessToken::HapPolicyParams hapPolicy = CreateHapPolicyParam(innerBundleInfo, appServiceCapabilities);
728 #ifdef X86_EMULATOR_MODE
729     std::string appId = innerBundleInfo.GetAppId();
730     if (appId == (innerBundleInfo.GetBundleName() + "_")) {
731         LOG_I(BMS_TAG_DEFAULT, "UnSignatureHap checkIgnore");
732         hapPolicy.checkIgnore = AccessToken::HapPolicyCheckIgnore::ACL_IGNORE_CHECK;
733     }
734 #endif
735     auto ret = AccessToken::AccessTokenKit::InitHapToken(hapInfo, hapPolicy, tokenIdeEx, checkResult);
736     if (AccessToken::AccessTokenError::ERR_SERVICE_ABNORMAL == ret ||
737         AccessToken::AccessTokenError::ERR_WRITE_PARCEL_FAILED == ret ||
738         AccessToken::AccessTokenError::ERR_READ_PARCEL_FAILED == ret) {
739         // try again
740         ret = AccessToken::AccessTokenKit::InitHapToken(hapInfo, hapPolicy, tokenIdeEx, checkResult);
741     }
742     if (ret != AccessToken::AccessTokenKitRet::RET_SUCCESS) {
743         LOG_E(BMS_TAG_DEFAULT, "InitHapToken failed, bundleName:%{public}s errCode:%{public}d",
744             innerBundleInfo.GetBundleName().c_str(), ret);
745         return ret;
746     }
747     LOG_I(BMS_TAG_DEFAULT, "bundleName: %{public}s tokenId:%{public}u", innerBundleInfo.GetBundleName().c_str(),
748         tokenIdeEx.tokenIdExStruct.tokenID);
749     return ERR_OK;
750 }
751 
UpdateHapToken(Security::AccessToken::AccessTokenIDEx & tokenIdeEx,const InnerBundleInfo & innerBundleInfo,int32_t userId,Security::AccessToken::HapInfoCheckResult & checkResult,const std::string & appServiceCapabilities,bool dataRefresh)752 int32_t BundlePermissionMgr::UpdateHapToken(Security::AccessToken::AccessTokenIDEx& tokenIdeEx,
753     const InnerBundleInfo &innerBundleInfo, int32_t userId, Security::AccessToken::HapInfoCheckResult &checkResult,
754     const std::string &appServiceCapabilities, bool dataRefresh)
755 {
756     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "start UpdateHapToken -n %{public}s", innerBundleInfo.GetBundleName().c_str());
757     AccessToken::UpdateHapInfoParams updateHapInfoParams;
758     updateHapInfoParams.appIDDesc = innerBundleInfo.GetAppId();
759     updateHapInfoParams.apiVersion = innerBundleInfo.GetBaseApplicationInfo().apiTargetVersion;
760     updateHapInfoParams.isSystemApp = innerBundleInfo.IsSystemApp();
761     updateHapInfoParams.appDistributionType = innerBundleInfo.GetAppDistributionType();
762     updateHapInfoParams.isAtomicService = innerBundleInfo.GetApplicationBundleType() == BundleType::ATOMIC_SERVICE;
763     //refresh new permissions for application
764     updateHapInfoParams.dataRefresh = dataRefresh;
765 
766     AccessToken::HapPolicyParams hapPolicy = CreateHapPolicyParam(innerBundleInfo, appServiceCapabilities);
767 #ifdef X86_EMULATOR_MODE
768     std::string appId = innerBundleInfo.GetAppId();
769     if (appId == (innerBundleInfo.GetBundleName() + "_")) {
770         LOG_I(BMS_TAG_DEFAULT, "UnSignatureHap checkIgnore");
771         hapPolicy.checkIgnore = AccessToken::HapPolicyCheckIgnore::ACL_IGNORE_CHECK;
772     }
773 #endif
774     auto ret = AccessToken::AccessTokenKit::UpdateHapToken(tokenIdeEx, updateHapInfoParams, hapPolicy, checkResult);
775     if (AccessToken::AccessTokenError::ERR_SERVICE_ABNORMAL == ret ||
776         AccessToken::AccessTokenError::ERR_WRITE_PARCEL_FAILED == ret) {
777         // try again
778         ret = AccessToken::AccessTokenKit::UpdateHapToken(tokenIdeEx, updateHapInfoParams, hapPolicy, checkResult);
779     }
780     if (AccessToken::AccessTokenError::ERR_TOKENID_NOT_EXIST == ret) {
781         AccessToken::HapInfoParams hapInfo = CreateHapInfoParams(innerBundleInfo, userId, 0);
782         hapInfo.isRestore = true;
783         hapInfo.tokenID = tokenIdeEx.tokenIdExStruct.tokenID;
784         ret = AccessToken::AccessTokenKit::InitHapToken(hapInfo, hapPolicy, tokenIdeEx, checkResult);
785     }
786     if (ret != AccessToken::AccessTokenKitRet::RET_SUCCESS) {
787         LOG_NOFUNC_E(BMS_TAG_DEFAULT, "UpdateHapToken failed, bundleName:%{public}s errCode:%{public}d",
788             innerBundleInfo.GetBundleName().c_str(), ret);
789         return ret;
790     }
791     LOG_NOFUNC_I(BMS_TAG_DEFAULT, "end UpdateHapToken");
792     return ERR_OK;
793 }
794 
GetCheckResultMsg(const Security::AccessToken::HapInfoCheckResult & checkResult)795 std::string BundlePermissionMgr::GetCheckResultMsg(const Security::AccessToken::HapInfoCheckResult &checkResult)
796 {
797     std::string result = "";
798     auto permissionName = checkResult.permCheckResult.permissionName;
799     auto reason = checkResult.permCheckResult.rule;
800     if (reason == Security::AccessToken::PERMISSION_ACL_RULE) {
801         result = "PermissionName: " + permissionName;
802         return result;
803     }
804     return result;
805 }
806 
CheckUserFromShell(int32_t userId)807 bool BundlePermissionMgr::CheckUserFromShell(int32_t userId)
808 {
809     // check if from shell call, specified user must be same with current active user
810     int32_t mode = GetIntParameter(IS_ROOT_MODE_PARAM, USER_MODE);
811     if (mode == ROOT_MODE) {
812         return true;
813     }
814     if (!BundlePermissionMgr::IsShellTokenType()) {
815         return true;
816     }
817     auto curUser = AccountHelper::GetCurrentActiveUserId();
818     if (curUser == Constants::INVALID_USERID) {
819         LOG_E(BMS_TAG_DEFAULT, "get current user fail");
820         return false;
821     }
822     if (userId != curUser && userId != Constants::DEFAULT_USERID && userId != Constants::U1 &&
823         userId != Constants::UNSPECIFIED_USERID) {
824         LOG_E(BMS_TAG_DEFAULT, "specified user %{public}d is not same with current user %{public}d",
825             userId, curUser);
826         return false;
827     }
828     return true;
829 }
830 }  // namespace AppExecFwk
831 }  // namespace OHOS