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