1 /*
2 * Copyright (c) 2021-2025 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 "accesstoken_info_manager.h"
17
18 #include <cinttypes>
19 #include <cstdint>
20 #include <cstdio>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <securec.h>
24 #include "access_token.h"
25 #include "accesstoken_dfx_define.h"
26 #include "accesstoken_id_manager.h"
27 #include "accesstoken_common_log.h"
28 #include "accesstoken_remote_token_manager.h"
29 #include "access_token_db_operator.h"
30 #include "access_token_error.h"
31 #include "atm_tools_param_info_parcel.h"
32 #include "callback_manager.h"
33 #include "constant_common.h"
34 #include "data_translator.h"
35 #include "data_validator.h"
36 #ifdef SUPPORT_SANDBOX_APP
37 #include "dlp_permission_set_manager.h"
38 #endif
39 #include "generic_values.h"
40 #include "hap_token_info_inner.h"
41 #include "hisysevent_adapter.h"
42 #include "ipc_skeleton.h"
43 #include "json_parse_loader.h"
44 #include "permission_manager.h"
45 #include "permission_map.h"
46 #include "permission_validator.h"
47 #include "perm_setproc.h"
48 #include "tokenid_attributes.h"
49 #include "token_field_const.h"
50 #include "token_setproc.h"
51 #ifdef TOKEN_SYNC_ENABLE
52 #include "token_modify_notifier.h"
53 #endif
54
55 namespace OHOS {
56 namespace Security {
57 namespace AccessToken {
58 namespace {
59 std::recursive_mutex g_instanceMutex;
60 static const unsigned int SYSTEM_APP_FLAG = 0x0001;
61 static const unsigned int ATOMIC_SERVICE_FLAG = 0x0002;
62 static constexpr int32_t BASE_USER_RANGE = 200000;
63 static constexpr int32_t SYSTEM_APP = 1;
64 #ifdef TOKEN_SYNC_ENABLE
65 static const int MAX_PTHREAD_NAME_LEN = 15; // pthread name max length
66 static const char* ACCESS_TOKEN_PACKAGE_NAME = "ohos.security.distributed_token_sync";
67 #endif
68 static const char* SYSTEM_RESOURCE_BUNDLE_NAME = "ohos.global.systemres";
69 }
70
AccessTokenInfoManager()71 AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) {}
72
~AccessTokenInfoManager()73 AccessTokenInfoManager::~AccessTokenInfoManager()
74 {
75 if (!hasInited_) {
76 return;
77 }
78
79 #ifdef TOKEN_SYNC_ENABLE
80 int32_t ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(ACCESS_TOKEN_PACKAGE_NAME);
81 if (ret != ERR_OK) {
82 LOGE(ATM_DOMAIN, ATM_TAG, "UnInitDeviceManager failed, code: %{public}d", ret);
83 }
84 #endif
85
86 this->hasInited_ = false;
87 }
88
Init(uint32_t & hapSize,uint32_t & nativeSize,uint32_t & pefDefSize,uint32_t & dlpSize,std::map<int32_t,TokenIdInfo> & tokenIdAplMap)89 void AccessTokenInfoManager::Init(uint32_t& hapSize, uint32_t& nativeSize, uint32_t& pefDefSize, uint32_t& dlpSize,
90 std::map<int32_t, TokenIdInfo>& tokenIdAplMap)
91 {
92 OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->managerLock_);
93 if (hasInited_) {
94 return;
95 }
96
97 LOGI(ATM_DOMAIN, ATM_TAG, "Init begin!");
98 LibraryLoader loader(CONFIG_PARSE_LIBPATH);
99 ConfigPolicyLoaderInterface* policy = loader.GetObject<ConfigPolicyLoaderInterface>();
100 if (policy == nullptr) {
101 LOGE(ATM_DOMAIN, ATM_TAG, "Dlopen libaccesstoken_json_parse failed.");
102 return;
103 }
104 std::vector<NativeTokenInfoBase> tokenInfos;
105 int ret = policy->GetAllNativeTokenInfo(tokenInfos);
106 if (ret != RET_SUCCESS) {
107 ReportSysEventServiceStartError(
108 INIT_NATIVE_TOKENINFO_ERROR, "GetAllNativeTokenInfo fail from native json.", ret);
109 LOGE(ATM_DOMAIN, ATM_TAG, "Failed to load native from native json, err=%{public}d.", ret);
110 return;
111 }
112
113 #ifdef SUPPORT_SANDBOX_APP
114 std::vector<PermissionDlpMode> dlpPerms;
115 ret = policy->GetDlpPermissions(dlpPerms);
116 dlpSize = dlpPerms.size();
117 if (ret == RET_SUCCESS) {
118 LOGI(ATM_DOMAIN, ATM_TAG, "Load dlpPer size=%{public}u.", dlpSize);
119 DlpPermissionSetManager::GetInstance().ProcessDlpPermInfos(dlpPerms);
120 }
121 #endif
122
123 InitHapTokenInfos(hapSize, tokenIdAplMap);
124 nativeSize = tokenInfos.size();
125 InitNativeTokenInfos(tokenInfos);
126 pefDefSize = GetDefPermissionsSize();
127
128 LOGI(ATM_DOMAIN, ATM_TAG,
129 "Init success, hapSize %{public}u, nativeSize %{public}u, pefDefSize %{public}u, dlpSize %{public}u.",
130 hapSize, nativeSize, pefDefSize, dlpSize);
131
132 hasInited_ = true;
133 }
134
IsSystemResource(const std::string & bundleName)135 static bool IsSystemResource(const std::string& bundleName)
136 {
137 return std::string(SYSTEM_RESOURCE_BUNDLE_NAME) == bundleName;
138 }
139
140 #ifdef TOKEN_SYNC_ENABLE
InitDmCallback(void)141 void AccessTokenInfoManager::InitDmCallback(void)
142 {
143 std::function<void()> runner = []() {
144 std::string name = "AtmInfoMgrInit";
145 pthread_setname_np(pthread_self(), name.substr(0, MAX_PTHREAD_NAME_LEN).c_str());
146 std::shared_ptr<AccessTokenDmInitCallback> ptrDmInitCallback = std::make_shared<AccessTokenDmInitCallback>();
147 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(ACCESS_TOKEN_PACKAGE_NAME,
148 ptrDmInitCallback);
149 if (ret != ERR_OK) {
150 LOGE(ATM_DOMAIN, ATM_TAG, "Initialize: InitDeviceManager error, result: %{public}d", ret);
151 }
152 LOGI(ATM_DOMAIN, ATM_TAG, "device manager part init end");
153 return;
154 };
155 std::thread initThread(runner);
156 initThread.detach();
157 }
158 #endif
159
AddHapInfoToCache(const GenericValues & tokenValue,const std::vector<GenericValues> & permStateRes,const std::vector<GenericValues> & extendedPermRes)160 int32_t AccessTokenInfoManager::AddHapInfoToCache(const GenericValues& tokenValue,
161 const std::vector<GenericValues>& permStateRes, const std::vector<GenericValues>& extendedPermRes)
162 {
163 AccessTokenID tokenId = static_cast<AccessTokenID>(tokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID));
164 std::string bundle = tokenValue.GetString(TokenFiledConst::FIELD_BUNDLE_NAME);
165 int result = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP);
166 if (result != RET_SUCCESS) {
167 LOGE(ATM_DOMAIN, ATM_TAG, "TokenId %{public}u add id failed, error=%{public}d.", tokenId, result);
168 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR,
169 "RegisterTokenId fail, " + bundle + std::to_string(tokenId), result);
170 return result;
171 }
172 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>();
173 result = hap->RestoreHapTokenInfo(tokenId, tokenValue, permStateRes, extendedPermRes);
174 if (result != RET_SUCCESS) {
175 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
176 LOGE(ATM_DOMAIN, ATM_TAG, "TokenId %{public}u restore failed.", tokenId);
177 return result;
178 }
179
180 AccessTokenID oriTokenId = 0;
181 result = AddHapTokenInfo(hap, oriTokenId);
182 if (result != RET_SUCCESS) {
183 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
184 LOGE(ATM_DOMAIN, ATM_TAG, "TokenId %{public}u add failed.", tokenId);
185 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR,
186 "AddHapTokenInfo fail, " + bundle + std::to_string(tokenId), result);
187 return result;
188 }
189
190 AccessTokenIDEx tokenIdEx = {0};
191 tokenIdEx.tokenIdExStruct.tokenID = tokenId;
192 tokenIdEx.tokenIdExStruct.tokenAttr = hap->GetAttr();
193
194 HapDfxInfo dfxInfo;
195 dfxInfo.sceneCode = AddHapSceneCode::INIT;
196 dfxInfo.tokenId = tokenId;
197 dfxInfo.oriTokenId = oriTokenId;
198 dfxInfo.tokenIdEx = tokenIdEx;
199 dfxInfo.userID = hap->GetUserID();
200 dfxInfo.bundleName = hap->GetBundleName();
201 dfxInfo.instIndex = hap->GetInstIndex();
202 ReportSysEventAddHap(RET_SUCCESS, dfxInfo, false);
203
204 LOGI(ATM_DOMAIN, ATM_TAG,
205 " Restore hap token %{public}u bundle name %{public}s user %{public}d,"
206 " permSize %{public}d, inst %{public}d ok!",
207 tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetReqPermissionSize(), hap->GetInstIndex());
208
209 return RET_SUCCESS;
210 }
211
InitHapTokenInfos(uint32_t & hapSize,std::map<int32_t,TokenIdInfo> & tokenIdAplMap)212 void AccessTokenInfoManager::InitHapTokenInfos(uint32_t& hapSize, std::map<int32_t, TokenIdInfo>& tokenIdAplMap)
213 {
214 GenericValues conditionValue;
215 std::vector<GenericValues> hapTokenRes;
216 std::vector<GenericValues> permStateRes;
217 std::vector<GenericValues> extendedPermRes;
218 int32_t ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, hapTokenRes);
219 if (ret != RET_SUCCESS) {
220 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load hap from db fail.", ret);
221 }
222 ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue, permStateRes);
223 if (ret != RET_SUCCESS) {
224 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load perm state from db fail.", ret);
225 }
226 ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_PERMISSION_EXTEND_VALUE, conditionValue,
227 extendedPermRes);
228 if (ret != RET_SUCCESS) { // extendedPermRes may be empty
229 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load exetended value from db fail.", ret);
230 }
231 for (const GenericValues& tokenValue : hapTokenRes) {
232 int32_t tokenId = tokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
233 TokenIdInfo tokenIdInfo;
234 tokenIdInfo.apl = tokenValue.GetInt(TokenFiledConst::FIELD_APL);
235 tokenIdInfo.isSystemApp = tokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ATTR) == SYSTEM_APP;
236 ret = AddHapInfoToCache(tokenValue, permStateRes, extendedPermRes);
237 if (ret != RET_SUCCESS) {
238 continue;
239 }
240 hapSize++;
241 tokenIdAplMap[tokenId] = tokenIdInfo;
242 }
243 }
244
GetHapUniqueStr(const int & userID,const std::string & bundleName,const int & instIndex) const245 std::string AccessTokenInfoManager::GetHapUniqueStr(const int& userID,
246 const std::string& bundleName, const int& instIndex) const
247 {
248 return bundleName + "&" + std::to_string(userID) + "&" + std::to_string(instIndex);
249 }
250
GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner> & info) const251 std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner>& info) const
252 {
253 if (info == nullptr) {
254 return std::string("");
255 }
256 return GetHapUniqueStr(info->GetUserID(), info->GetBundleName(), info->GetInstIndex());
257 }
258
AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner> & info,AccessTokenID & oriTokenId)259 int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner>& info, AccessTokenID& oriTokenId)
260 {
261 if (info == nullptr) {
262 LOGE(ATM_DOMAIN, ATM_TAG, "Token info is null.");
263 return AccessTokenError::ERR_PARAM_INVALID;
264 }
265 AccessTokenID id = info->GetTokenID();
266 AccessTokenID idRemoved = INVALID_TOKENID;
267 {
268 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
269 if (hapTokenInfoMap_.count(id) > 0) {
270 LOGC(ATM_DOMAIN, ATM_TAG, "Token %{public}u info has exist.", id);
271 return AccessTokenError::ERR_TOKENID_HAS_EXISTED;
272 }
273
274 if (!info->IsRemote()) {
275 std::string hapUniqueKey = GetHapUniqueStr(info);
276 auto iter = hapTokenIdMap_.find(hapUniqueKey);
277 if (iter != hapTokenIdMap_.end()) {
278 LOGI(ATM_DOMAIN, ATM_TAG, "Token %{public}u Unique info has exist, update.", id);
279 idRemoved = iter->second;
280 }
281 hapTokenIdMap_[hapUniqueKey] = id;
282 }
283 hapTokenInfoMap_[id] = info;
284 }
285 if (idRemoved != INVALID_TOKENID) {
286 oriTokenId = idRemoved;
287 (void)RemoveHapTokenInfo(idRemoved);
288 }
289 // add hap to kernel
290 int32_t userId = info->GetUserID();
291 {
292 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
293 if (!permPolicyList_.empty() &&
294 (std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userId) != inactiveUserList_.end())) {
295 LOGI(ATM_DOMAIN, ATM_TAG, "Execute user policy.");
296 PermissionManager::GetInstance().AddHapPermToKernel(id, permPolicyList_);
297 return RET_SUCCESS;
298 }
299 }
300 PermissionManager::GetInstance().AddHapPermToKernel(id, std::vector<std::string>());
301 return RET_SUCCESS;
302 }
303
GetHapTokenInfoInnerFromDb(AccessTokenID id)304 std::shared_ptr<HapTokenInfoInner> AccessTokenInfoManager::GetHapTokenInfoInnerFromDb(AccessTokenID id)
305 {
306 GenericValues conditionValue;
307 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(id));
308
309 std::vector<GenericValues> hapTokenResults;
310 int32_t ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, hapTokenResults);
311 if (ret != RET_SUCCESS || hapTokenResults.empty()) {
312 LOGC(ATM_DOMAIN, ATM_TAG, "Failed to find Id(%{public}u) from hap_token_table, err: %{public}d, "
313 "hapSize: %{public}zu, mapSize: %{public}zu.", id, ret, hapTokenResults.size(), hapTokenInfoMap_.size());
314 return nullptr;
315 }
316
317 std::vector<GenericValues> permStateRes;
318 ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue, permStateRes);
319 if (ret != RET_SUCCESS) {
320 LOGC(ATM_DOMAIN, ATM_TAG, "Failed to find Id(%{public}u) from perm_state_table, err: %{public}d, "
321 "mapSize: %{public}zu.", id, ret, hapTokenInfoMap_.size());
322 return nullptr;
323 }
324
325 std::vector<GenericValues> extendedPermRes;
326 ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_PERMISSION_EXTEND_VALUE, conditionValue,
327 extendedPermRes);
328 if (ret != RET_SUCCESS) { // extendedPermRes may be empty
329 LOGC(ATM_DOMAIN, ATM_TAG, "Failed to find Id(%{public}u) from perm_extend_value_table, err: %{public}d, "
330 "mapSize: %{public}zu.", id, ret, hapTokenInfoMap_.size());
331 return nullptr;
332 }
333
334 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>();
335 ret = hap->RestoreHapTokenInfo(id, hapTokenResults[0], permStateRes, extendedPermRes);
336 if (ret != RET_SUCCESS) {
337 LOGC(ATM_DOMAIN, ATM_TAG, "Id %{public}u restore failed, err: %{public}d, mapSize: %{public}zu.",
338 id, ret, hapTokenInfoMap_.size());
339 return nullptr;
340 }
341
342 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
343 (void)AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_HAP);
344 hapTokenIdMap_[GetHapUniqueStr(hap)] = id;
345 hapTokenInfoMap_[id] = hap;
346 PermissionManager::GetInstance().AddHapPermToKernel(id, std::vector<std::string>());
347 LOGI(ATM_DOMAIN, ATM_TAG, " Token %{public}u is not found in map(mapSize: %{public}zu), begin load from DB,"
348 " restore bundle %{public}s user %{public}d, idx %{public}d, permSize %{public}d.", id, hapTokenInfoMap_.size(),
349 hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex(), hap->GetReqPermissionSize());
350 return hap;
351 }
352
GetHapTokenInfoInner(AccessTokenID id)353 std::shared_ptr<HapTokenInfoInner> AccessTokenInfoManager::GetHapTokenInfoInner(AccessTokenID id)
354 {
355 {
356 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
357 auto iter = hapTokenInfoMap_.find(id);
358 if (iter != hapTokenInfoMap_.end()) {
359 return iter->second;
360 }
361 }
362 return GetHapTokenInfoInnerFromDb(id);
363 }
364
GetHapTokenDlpType(AccessTokenID id)365 int32_t AccessTokenInfoManager::GetHapTokenDlpType(AccessTokenID id)
366 {
367 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
368 auto iter = hapTokenInfoMap_.find(id);
369 if ((iter != hapTokenInfoMap_.end()) && (iter->second != nullptr)) {
370 return iter->second->GetDlpType();
371 }
372 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid, mapSize: %{public}zu.", id, hapTokenInfoMap_.size());
373 return BUTT_DLP_TYPE;
374 }
375
IsTokenIdExist(AccessTokenID id)376 bool AccessTokenInfoManager::IsTokenIdExist(AccessTokenID id)
377 {
378 {
379 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
380 if (hapTokenInfoMap_.count(id) != 0) {
381 return true;
382 }
383 }
384 {
385 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
386 if (nativeTokenInfoMap_.count(id) != 0) {
387 return true;
388 }
389 }
390 return false;
391 }
392
GetTokenIDByUserID(int32_t userID,std::unordered_set<AccessTokenID> & tokenIdList)393 int32_t AccessTokenInfoManager::GetTokenIDByUserID(int32_t userID, std::unordered_set<AccessTokenID>& tokenIdList)
394 {
395 GenericValues conditionValue;
396 std::vector<GenericValues> tokenIDResults;
397 conditionValue.Put(TokenFiledConst::FIELD_USER_ID, userID);
398
399 int32_t ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, tokenIDResults);
400 if (ret != RET_SUCCESS) {
401 LOGE(ATM_DOMAIN, ATM_TAG, "UserID(%{public}d) find tokenID failed, ret: %{public}d.", userID, ret);
402 return ret;
403 }
404 if (tokenIDResults.empty()) {
405 LOGE(ATM_DOMAIN, ATM_TAG, "UserID(%{public}d) find tokenID empty.", userID);
406 return RET_SUCCESS;
407 }
408
409 for (const GenericValues& tokenIDResult : tokenIDResults) {
410 AccessTokenID tokenId = (AccessTokenID)tokenIDResult.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
411 tokenIdList.emplace(tokenId);
412 }
413 return RET_SUCCESS;
414 }
415
GetHapTokenInfo(AccessTokenID tokenID,HapTokenInfo & info)416 int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& info)
417 {
418 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
419 if (infoPtr == nullptr) {
420 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid.", tokenID);
421 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
422 }
423 infoPtr->TranslateToHapTokenInfo(info);
424 return RET_SUCCESS;
425 }
426
GetNativeTokenInfo(AccessTokenID tokenID,NativeTokenInfoBase & info)427 int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoBase& info)
428 {
429 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
430 auto iter = nativeTokenInfoMap_.find(tokenID);
431 if (iter == nativeTokenInfoMap_.end()) {
432 LOGE(ATM_DOMAIN, ATM_TAG, "Id %{public}u is not exist.", tokenID);
433 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
434 }
435 info.apl = iter->second.apl;
436 info.processName = iter->second.processName;
437 return RET_SUCCESS;
438 }
439
RemoveHapTokenInfo(AccessTokenID id)440 int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id)
441 {
442 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
443 if (type != TOKEN_HAP) {
444 LOGC(ATM_DOMAIN, ATM_TAG, "Token %{public}u is not hap.", id);
445 return ERR_PARAM_INVALID;
446 }
447 std::shared_ptr<HapTokenInfoInner> info;
448 {
449 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
450 // remove hap to kernel
451 PermissionManager::GetInstance().RemovePermFromKernel(id);
452 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
453
454 if (hapTokenInfoMap_.count(id) == 0) {
455 LOGC(ATM_DOMAIN, ATM_TAG, "Hap token %{public}u no exist.", id);
456 return ERR_TOKENID_NOT_EXIST;
457 }
458
459 info = hapTokenInfoMap_[id];
460 if (info == nullptr) {
461 LOGC(ATM_DOMAIN, ATM_TAG, "Hap token %{public}u is null.", id);
462 return ERR_TOKEN_INVALID;
463 }
464 if (info->IsRemote()) {
465 LOGC(ATM_DOMAIN, ATM_TAG, "Remote hap token %{public}u can not delete.", id);
466 return ERR_IDENTITY_CHECK_FAILED;
467 }
468 std::string HapUniqueKey = GetHapUniqueStr(info);
469 auto iter = hapTokenIdMap_.find(HapUniqueKey);
470 if ((iter != hapTokenIdMap_.end()) && (iter->second == id)) {
471 hapTokenIdMap_.erase(HapUniqueKey);
472 }
473 hapTokenInfoMap_.erase(id);
474 }
475 int32_t ret = RemoveHapTokenInfoFromDb(info);
476 if (ret != RET_SUCCESS) {
477 LOGC(ATM_DOMAIN, ATM_TAG, "Remove info from db failed, ret is %{public}d", ret);
478 }
479
480 LOGI(ATM_DOMAIN, ATM_TAG, "Remove hap token %{public}u ok!", id);
481 PermissionStateNotify(info, id);
482 #ifdef TOKEN_SYNC_ENABLE
483 TokenModifyNotifier::GetInstance().NotifyTokenDelete(id);
484 #endif
485
486 return RET_SUCCESS;
487 }
488
RemoveNativeTokenInfo(AccessTokenID id)489 int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id)
490 {
491 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
492 if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) {
493 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is not native or shell.", id);
494 return ERR_PARAM_INVALID;
495 }
496
497 {
498 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
499 if (nativeTokenInfoMap_.count(id) == 0) {
500 LOGE(ATM_DOMAIN, ATM_TAG, "Native token %{public}u is null.", id);
501 return ERR_TOKENID_NOT_EXIST;
502 }
503
504 nativeTokenInfoMap_.erase(id);
505 }
506 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
507 LOGI(ATM_DOMAIN, ATM_TAG, "Remove native token %{public}u ok!", id);
508
509 // remove native to kernel
510 PermissionManager::GetInstance().RemovePermFromKernel(id);
511 return RET_SUCCESS;
512 }
513
CheckHapInfoParam(const HapInfoParams & info,const HapPolicy & policy)514 int32_t AccessTokenInfoManager::CheckHapInfoParam(const HapInfoParams& info, const HapPolicy& policy)
515 {
516 if ((!DataValidator::IsUserIdValid(info.userID)) || (!DataValidator::IsBundleNameValid(info.bundleName)) ||
517 (!DataValidator::IsAppIDDescValid(info.appIDDesc)) || (!DataValidator::IsDomainValid(policy.domain)) ||
518 (!DataValidator::IsDlpTypeValid(info.dlpType)) || (info.isRestore && info.tokenID == INVALID_TOKENID) ||
519 !DataValidator::IsAclExtendedMapSizeValid(policy.aclExtendedMap)) {
520 LOGC(ATM_DOMAIN, ATM_TAG, "Hap token param failed");
521 return AccessTokenError::ERR_PARAM_INVALID;
522 }
523
524 for (const auto& extendValue : policy.aclExtendedMap) {
525 if (!IsDefinedPermission(extendValue.first)) {
526 continue;
527 }
528 if (!DataValidator::IsAclExtendedMapContentValid(extendValue.first, extendValue.second)) {
529 LOGC(ATM_DOMAIN, ATM_TAG, "Acl extended content is invalid.");
530 return AccessTokenError::ERR_PARAM_INVALID;
531 }
532 }
533 return ERR_OK;
534 }
535
ReportAddHapIdChange(const std::shared_ptr<HapTokenInfoInner> & hapInfo,AccessTokenID oriTokenId)536 void AccessTokenInfoManager::ReportAddHapIdChange(const std::shared_ptr<HapTokenInfoInner>& hapInfo,
537 AccessTokenID oriTokenId)
538 {
539 HapDfxInfo dfxInfo;
540 dfxInfo.sceneCode = AddHapSceneCode::TOKEN_ID_CHANGE;
541 dfxInfo.tokenId = hapInfo->GetTokenID();
542 dfxInfo.oriTokenId = oriTokenId;
543 dfxInfo.userID = hapInfo->GetUserID();
544 dfxInfo.bundleName = hapInfo->GetBundleName();
545 dfxInfo.instIndex = hapInfo->GetInstIndex();
546 ReportSysEventAddHap(RET_SUCCESS, dfxInfo, false);
547 }
548
RegisterTokenId(const HapInfoParams & info,AccessTokenID & tokenId)549 int32_t AccessTokenInfoManager::RegisterTokenId(const HapInfoParams& info, AccessTokenID& tokenId)
550 {
551 int32_t res = RET_SUCCESS;
552
553 if (info.isRestore) {
554 LOGI(ATM_DOMAIN, ATM_TAG, "IsRestore is true, tokenId is %{public}u.", info.tokenID);
555
556 res = AccessTokenIDManager::GetInstance().RegisterTokenId(info.tokenID, TOKEN_HAP);
557 if (res != RET_SUCCESS) {
558 LOGC(ATM_DOMAIN, ATM_TAG, "Token Id register failed, errCode is %{public}d.", res);
559 return res;
560 }
561
562 tokenId = info.tokenID;
563 } else {
564 int32_t dlpFlag = (info.dlpType > DLP_COMMON) ? 1 : 0;
565 int32_t cloneFlag = ((dlpFlag == 0) && (info.instIndex) > 0) ? 1 : 0;
566 tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP, dlpFlag, cloneFlag);
567 if (tokenId == 0) {
568 LOGC(ATM_DOMAIN, ATM_TAG, "Token Id create failed");
569 return ERR_TOKENID_CREATE_FAILED;
570 }
571 }
572
573 return res;
574 }
575
AddTokenIdToUndefValues(AccessTokenID tokenId,std::vector<GenericValues> & undefValues)576 void AccessTokenInfoManager::AddTokenIdToUndefValues(AccessTokenID tokenId, std::vector<GenericValues>& undefValues)
577 {
578 for (auto& value : undefValues) {
579 value.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenId));
580 }
581 }
582
CreateHapTokenInfo(const HapInfoParams & info,const HapPolicy & policy,AccessTokenIDEx & tokenIdEx,std::vector<GenericValues> & undefValues)583 int AccessTokenInfoManager::CreateHapTokenInfo(const HapInfoParams& info, const HapPolicy& policy,
584 AccessTokenIDEx& tokenIdEx, std::vector<GenericValues>& undefValues)
585 {
586 if (CheckHapInfoParam(info, policy) != ERR_OK) {
587 return AccessTokenError::ERR_PARAM_INVALID;
588 }
589 AccessTokenID tokenId;
590 int32_t ret = RegisterTokenId(info, tokenId);
591 if (ret != RET_SUCCESS) {
592 return ret;
593 }
594 AddTokenIdToUndefValues(tokenId, undefValues);
595 #ifdef SUPPORT_SANDBOX_APP
596 std::shared_ptr<HapTokenInfoInner> tokenInfo;
597 HapPolicy policyNew = policy;
598 if (info.dlpType != DLP_COMMON) {
599 DlpPermissionSetManager::GetInstance().UpdatePermStateWithDlpInfo(info.dlpType, policyNew.permStateList);
600 }
601 tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policyNew);
602 #else
603 std::shared_ptr<HapTokenInfoInner> tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policy);
604 #endif
605 ret = AddHapTokenInfoToDb(tokenInfo, info.appIDDesc, policy, false, undefValues);
606 if (ret != RET_SUCCESS) {
607 LOGC(ATM_DOMAIN, ATM_TAG, "AddHapTokenInfoToDb failed, errCode is %{public}d.", ret);
608 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
609 return ret;
610 }
611
612 AccessTokenID oriTokenID = 0;
613 ret = AddHapTokenInfo(tokenInfo, oriTokenID);
614 if (ret != RET_SUCCESS) {
615 LOGC(ATM_DOMAIN, ATM_TAG, "%{public}s add token info failed", info.bundleName.c_str());
616 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
617 (void)RemoveHapTokenInfoFromDb(tokenInfo);
618 return ret;
619 }
620
621 if (oriTokenID != 0) {
622 ReportAddHapIdChange(tokenInfo, oriTokenID);
623 }
624
625 LOGI(ATM_DOMAIN, ATM_TAG,
626 "Create hap token %{public}u bundleName %{public}s user %{public}d inst %{public}d isRestore %{public}d ok",
627 tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex(), info.isRestore);
628 (void)AllocAccessTokenIDEx(info, tokenId, tokenIdEx);
629 return RET_SUCCESS;
630 }
631
AllocAccessTokenIDEx(const HapInfoParams & info,AccessTokenID tokenId,AccessTokenIDEx & tokenIdEx)632 int AccessTokenInfoManager::AllocAccessTokenIDEx(
633 const HapInfoParams& info, AccessTokenID tokenId, AccessTokenIDEx& tokenIdEx)
634 {
635 tokenIdEx.tokenIdExStruct.tokenID = tokenId;
636 if (info.isSystemApp) {
637 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
638 }
639 if (info.isAtomicService) {
640 tokenIdEx.tokenIdExStruct.tokenAttr |= ATOMIC_SERVICE_FLAG;
641 }
642 return RET_SUCCESS;
643 }
644
GetHapTokenID(int32_t userID,const std::string & bundleName,int32_t instIndex)645 AccessTokenIDEx AccessTokenInfoManager::GetHapTokenID(int32_t userID, const std::string& bundleName, int32_t instIndex)
646 {
647 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
648 std::string HapUniqueKey = GetHapUniqueStr(userID, bundleName, instIndex);
649 AccessTokenIDEx tokenIdEx = {0};
650 auto iter = hapTokenIdMap_.find(HapUniqueKey);
651 if (iter != hapTokenIdMap_.end()) {
652 AccessTokenID tokenId = iter->second;
653 auto infoIter = hapTokenInfoMap_.find(tokenId);
654 if (infoIter != hapTokenInfoMap_.end()) {
655 if (infoIter->second == nullptr) {
656 LOGE(ATM_DOMAIN, ATM_TAG, "HapTokenInfoInner is nullptr");
657 return tokenIdEx;
658 }
659 HapTokenInfo info = infoIter->second->GetHapInfoBasic();
660 tokenIdEx.tokenIdExStruct.tokenID = info.tokenID;
661 tokenIdEx.tokenIdExStruct.tokenAttr = info.tokenAttr;
662 }
663 }
664 return tokenIdEx;
665 }
666
GetNativePermissionList(const NativeTokenInfoBase & native,std::vector<uint32_t> & opCodeList,std::vector<bool> & statusList)667 void AccessTokenInfoManager::GetNativePermissionList(const NativeTokenInfoBase& native,
668 std::vector<uint32_t>& opCodeList, std::vector<bool>& statusList)
669 {
670 // need to process aclList
671 for (const auto& state : native.permStateList) {
672 uint32_t code;
673 // add IsPermissionReqValid to filter invalid permission
674 if (TransferPermissionToOpcode(state.permissionName, code)) {
675 opCodeList.emplace_back(code);
676 statusList.emplace_back(state.grantStatus == PERMISSION_GRANTED);
677 }
678 }
679 }
680
InitNativeTokenInfos(const std::vector<NativeTokenInfoBase> & tokenInfos)681 void AccessTokenInfoManager::InitNativeTokenInfos(const std::vector<NativeTokenInfoBase>& tokenInfos)
682 {
683 for (const auto& info: tokenInfos) {
684 AccessTokenID tokenId = info.tokenID;
685 std::string process = info.processName;
686 // add tokenId to cache
687 ATokenTypeEnum type = TokenIDAttributes::GetTokenIdTypeEnum(tokenId);
688 int32_t res = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, type);
689 if (res != RET_SUCCESS && res != ERR_TOKENID_HAS_EXISTED) {
690 LOGE(ATM_DOMAIN, ATM_TAG, "Token id register fail, res is %{public}d.", res);
691 ReportSysEventServiceStartError(INIT_NATIVE_TOKENINFO_ERROR,
692 "RegisterTokenId fail, " + process + std::to_string(tokenId), res);
693 continue;
694 }
695 std::vector<uint32_t> opCodeList;
696 std::vector<bool> statusList;
697 GetNativePermissionList(info, opCodeList, statusList);
698 // add native token info to cache
699 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
700 NativeTokenInfoCache cache;
701 cache.processName = process;
702 cache.apl = static_cast<ATokenAplEnum>(info.apl);
703 cache.opCodeList = opCodeList;
704 cache.statusList = statusList;
705
706 nativeTokenInfoMap_[tokenId] = cache;
707 PermissionManager::GetInstance().AddNativePermToKernel(tokenId, cache.opCodeList, cache.statusList);
708 LOGI(ATM_DOMAIN, ATM_TAG,
709 "Init native token %{public}u process name %{public}s, permSize %{public}zu ok!",
710 tokenId, process.c_str(), info.permStateList.size());
711 }
712 }
713
UpdateHapToken(AccessTokenIDEx & tokenIdEx,const UpdateHapInfoParams & info,const std::vector<PermissionStatus> & permStateList,const HapPolicy & hapPolicy,std::vector<GenericValues> & undefValues)714 int32_t AccessTokenInfoManager::UpdateHapToken(AccessTokenIDEx& tokenIdEx, const UpdateHapInfoParams& info,
715 const std::vector<PermissionStatus>& permStateList, const HapPolicy& hapPolicy,
716 std::vector<GenericValues>& undefValues)
717 {
718 AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID;
719 if (!DataValidator::IsAppIDDescValid(info.appIDDesc)) {
720 LOGC(ATM_DOMAIN, ATM_TAG, "Token %{public}u parm format error!", tokenID);
721 return AccessTokenError::ERR_PARAM_INVALID;
722 }
723 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
724 if (infoPtr == nullptr) {
725 LOGC(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid, can not update!", tokenID);
726 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
727 }
728
729 if (infoPtr->IsRemote()) {
730 LOGC(ATM_DOMAIN, ATM_TAG, "Remote hap token %{public}u can not update!", tokenID);
731 return ERR_IDENTITY_CHECK_FAILED;
732 }
733 if (info.isSystemApp) {
734 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
735 } else {
736 tokenIdEx.tokenIdExStruct.tokenAttr &= ~SYSTEM_APP_FLAG;
737 }
738 if (info.isAtomicService) {
739 tokenIdEx.tokenIdExStruct.tokenAttr |= ATOMIC_SERVICE_FLAG;
740 } else {
741 tokenIdEx.tokenIdExStruct.tokenAttr &= ~ATOMIC_SERVICE_FLAG;
742 }
743 {
744 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
745 infoPtr->Update(info, permStateList, hapPolicy);
746 }
747
748 AddTokenIdToUndefValues(tokenID, undefValues);
749 int32_t ret = AddHapTokenInfoToDb(infoPtr, info.appIDDesc, hapPolicy, true, undefValues);
750 if (ret != RET_SUCCESS) {
751 LOGC(ATM_DOMAIN, ATM_TAG, "Add hap info %{public}u to db failed!", tokenID);
752 return ret;
753 }
754 LOGI(ATM_DOMAIN, ATM_TAG, "Token %{public}u bundle name %{public}s user %{public}d \
755 inst %{public}d tokenAttr %{public}d update ok!", tokenID, infoPtr->GetBundleName().c_str(),
756 infoPtr->GetUserID(), infoPtr->GetInstIndex(), infoPtr->GetHapInfoBasic().tokenAttr);
757
758 #ifdef TOKEN_SYNC_ENABLE
759 TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID);
760 #endif
761 // update hap to kernel
762 UpdateHapToKernel(tokenID, infoPtr->GetUserID());
763 return RET_SUCCESS;
764 }
765
UpdateHapToKernel(AccessTokenID tokenID,int32_t userId)766 void AccessTokenInfoManager::UpdateHapToKernel(AccessTokenID tokenID, int32_t userId)
767 {
768 {
769 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
770 if (!permPolicyList_.empty() &&
771 (std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userId) != inactiveUserList_.end())) {
772 LOGI(ATM_DOMAIN, ATM_TAG, "Execute user policy.");
773 PermissionManager::GetInstance().AddHapPermToKernel(tokenID, permPolicyList_);
774 return;
775 }
776 }
777 PermissionManager::GetInstance().AddHapPermToKernel(tokenID, std::vector<std::string>());
778 }
779
780 #ifdef TOKEN_SYNC_ENABLE
GetHapTokenSync(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)781 int AccessTokenInfoManager::GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync)
782 {
783 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
784 if (infoPtr == nullptr || infoPtr->IsRemote()) {
785 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid.", tokenID);
786 return ERR_IDENTITY_CHECK_FAILED;
787 }
788 hapSync.baseInfo = infoPtr->GetHapInfoBasic();
789 return infoPtr->GetPermissionStateList(hapSync.permStateList);
790 }
791
GetHapTokenInfoFromRemote(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)792 int AccessTokenInfoManager::GetHapTokenInfoFromRemote(AccessTokenID tokenID,
793 HapTokenInfoForSync& hapSync)
794 {
795 int ret = GetHapTokenSync(tokenID, hapSync);
796 TokenModifyNotifier::GetInstance().AddHapTokenObservation(tokenID);
797 return ret;
798 }
799
UpdateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)800 int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
801 {
802 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(mapID);
803 if (infoPtr == nullptr || !infoPtr->IsRemote()) {
804 LOGI(ATM_DOMAIN, ATM_TAG, "Token %{public}u is null or not remote, can not update!", mapID);
805 return ERR_IDENTITY_CHECK_FAILED;
806 }
807 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
808 infoPtr->UpdateRemoteHapTokenInfo(mapID, hapSync.baseInfo, hapSync.permStateList);
809 // update remote hap to kernel
810 PermissionManager::GetInstance().AddHapPermToKernel(mapID, std::vector<std::string>());
811 return RET_SUCCESS;
812 }
813
CreateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)814 int AccessTokenInfoManager::CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
815 {
816 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>(mapID, hapSync);
817 hap->SetRemote(true);
818
819 AccessTokenID oriTokenId = 0;
820 int ret = AddHapTokenInfo(hap, oriTokenId);
821 if (ret != RET_SUCCESS) {
822 LOGE(ATM_DOMAIN, ATM_TAG, "Add local token failed, err: %{public}d.", ret);
823 return ret;
824 }
825
826 HapDfxInfo dfxInfo;
827 dfxInfo.sceneCode = AddHapSceneCode::MAP;
828 dfxInfo.tokenId = hap->GetTokenID();
829 dfxInfo.oriTokenId = oriTokenId;
830 dfxInfo.userID = hap->GetUserID();
831 dfxInfo.bundleName = hap->GetBundleName();
832 dfxInfo.instIndex = hap->GetInstIndex();
833 ReportSysEventAddHap(RET_SUCCESS, dfxInfo, false);
834
835 return RET_SUCCESS;
836 }
837
IsRemoteHapTokenValid(const std::string & deviceID,const HapTokenInfoForSync & hapSync)838 bool AccessTokenInfoManager::IsRemoteHapTokenValid(const std::string& deviceID, const HapTokenInfoForSync& hapSync)
839 {
840 std::string errReason;
841 if (!DataValidator::IsDeviceIdValid(deviceID)) {
842 errReason = "respond deviceID error";
843 } else if (!DataValidator::IsUserIdValid(hapSync.baseInfo.userID)) {
844 errReason = "respond userID error";
845 } else if (!DataValidator::IsBundleNameValid(hapSync.baseInfo.bundleName)) {
846 errReason = "respond bundleName error";
847 } else if (!DataValidator::IsTokenIDValid(hapSync.baseInfo.tokenID)) {
848 errReason = "respond tokenID error";
849 } else if (!DataValidator::IsDlpTypeValid(hapSync.baseInfo.dlpType)) {
850 errReason = "respond dlpType error";
851 } else if (hapSync.baseInfo.ver != DEFAULT_TOKEN_VERSION) {
852 errReason = "respond version error";
853 } else if (TokenIDAttributes::GetTokenIdTypeEnum(hapSync.baseInfo.tokenID) != TOKEN_HAP) {
854 errReason = "respond token type error";
855 } else {
856 return true;
857 }
858
859 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
860 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_RESPONSE_ERROR,
861 "REMOTE_ID", ConstantCommon::EncryptDevId(deviceID), "ERROR_REASON", errReason);
862 return false;
863 }
864
SetRemoteHapTokenInfo(const std::string & deviceID,HapTokenInfoForSync & hapSync)865 int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync)
866 {
867 if (!IsRemoteHapTokenValid(deviceID, hapSync)) {
868 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
869 return ERR_IDENTITY_CHECK_FAILED;
870 }
871
872 AccessTokenID remoteID = hapSync.baseInfo.tokenID;
873 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID);
874 if (mapID != 0) {
875 LOGI(ATM_DOMAIN, ATM_TAG, "Device %{public}s token %{public}u update exist remote hap token %{public}u.",
876 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
877 // update remote token mapping id
878 hapSync.baseInfo.tokenID = mapID;
879 return UpdateRemoteHapTokenInfo(mapID, hapSync);
880 }
881
882 mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID);
883 if (mapID == 0) {
884 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s token %{public}u map failed.",
885 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID);
886 return ERR_TOKEN_MAP_FAILED;
887 }
888
889 // update remote token mapping id
890 hapSync.baseInfo.tokenID = mapID;
891 int ret = CreateRemoteHapTokenInfo(mapID, hapSync);
892 if (ret != RET_SUCCESS) {
893 int result = AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID);
894 if (result != RET_SUCCESS) {
895 LOGE(ATM_DOMAIN, ATM_TAG, "remove device map token id failed");
896 }
897 LOGI(ATM_DOMAIN, ATM_TAG, "Device %{public}s token %{public}u map to local token %{public}u failed.",
898 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
899 return ret;
900 }
901 LOGI(ATM_DOMAIN, ATM_TAG, "Device %{public}s token %{public}u map to local token %{public}u success.",
902 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
903 return RET_SUCCESS;
904 }
905
DeleteRemoteToken(const std::string & deviceID,AccessTokenID tokenID)906 int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID)
907 {
908 if (!DataValidator::IsDeviceIdValid(deviceID)) {
909 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s parms invalid.",
910 ConstantCommon::EncryptDevId(deviceID).c_str());
911 return AccessTokenError::ERR_PARAM_INVALID;
912 }
913 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
914 if (mapID == 0) {
915 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s tokenId %{public}u is not mapped.",
916 ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID);
917 return ERR_TOKEN_MAP_FAILED;
918 }
919
920 ATokenTypeEnum type = TokenIDAttributes::GetTokenIdTypeEnum(mapID);
921 if (type == TOKEN_HAP) {
922 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
923 if (hapTokenInfoMap_.count(mapID) == 0) {
924 LOGE(ATM_DOMAIN, ATM_TAG, "Hap token %{public}u no exist.", mapID);
925 return ERR_TOKEN_INVALID;
926 }
927 hapTokenInfoMap_.erase(mapID);
928 } else if ((type == TOKEN_NATIVE) || (type == TOKEN_SHELL)) {
929 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
930 if (nativeTokenInfoMap_.count(mapID) == 0) {
931 LOGE(ATM_DOMAIN, ATM_TAG, "Native token %{public}u is null.", mapID);
932 return ERR_TOKEN_INVALID;
933 }
934 nativeTokenInfoMap_.erase(mapID);
935 } else {
936 LOGE(ATM_DOMAIN, ATM_TAG, "Mapping tokenId %{public}u type is unknown.", mapID);
937 }
938
939 return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID);
940 }
941
GetRemoteNativeTokenID(const std::string & deviceID,AccessTokenID tokenID)942 AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID)
943 {
944 if ((!DataValidator::IsDeviceIdValid(deviceID)) || (tokenID == 0) ||
945 ((TokenIDAttributes::GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) &&
946 (TokenIDAttributes::GetTokenIdTypeEnum(tokenID) != TOKEN_SHELL))) {
947 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s parms invalid.",
948 ConstantCommon::EncryptDevId(deviceID).c_str());
949 return 0;
950 }
951 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
952 }
953
DeleteRemoteDeviceTokens(const std::string & deviceID)954 int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID)
955 {
956 if (!DataValidator::IsDeviceIdValid(deviceID)) {
957 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s parms invalid.",
958 ConstantCommon::EncryptDevId(deviceID).c_str());
959 return AccessTokenError::ERR_PARAM_INVALID;
960 }
961 std::vector<AccessTokenID> remoteTokens;
962 int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens);
963 if (ret != RET_SUCCESS) {
964 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s have no remote token.",
965 ConstantCommon::EncryptDevId(deviceID).c_str());
966 return ret;
967 }
968 for (AccessTokenID remoteID : remoteTokens) {
969 ret = DeleteRemoteToken(deviceID, remoteID);
970 if (ret != RET_SUCCESS) {
971 LOGE(ATM_DOMAIN, ATM_TAG, "delete remote token failed! deviceId=%{public}s, remoteId=%{public}d.", \
972 deviceID.c_str(), remoteID);
973 }
974 }
975 return ret;
976 }
977
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)978 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
979 AccessTokenID remoteTokenID)
980 {
981 if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) {
982 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s parms invalid.",
983 ConstantCommon::EncryptDevId(remoteDeviceID).c_str());
984 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
985 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
986 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", "deviceID error");
987 return 0;
988 }
989 uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
990 int result = SetFirstCallerTokenID(fullTokenId); // for debug
991 LOGI(ATM_DOMAIN, ATM_TAG, "Set first caller %{public}" PRIu64 "., ret is %{public}d", fullTokenId, result);
992
993 std::string remoteUdid;
994 DistributedHardware::DeviceManager::GetInstance().GetUdidByNetworkId(ACCESS_TOKEN_PACKAGE_NAME, remoteDeviceID,
995 remoteUdid);
996 LOGI(ATM_DOMAIN, ATM_TAG, "Device %{public}s remoteUdid.", ConstantCommon::EncryptDevId(remoteUdid).c_str());
997 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid,
998 remoteTokenID);
999 if (mapID != 0) {
1000 return mapID;
1001 }
1002 int ret = TokenModifyNotifier::GetInstance().GetRemoteHapTokenInfo(remoteUdid, remoteTokenID);
1003 if (ret != RET_SUCCESS) {
1004 LOGE(ATM_DOMAIN, ATM_TAG, "Device %{public}s token %{public}u sync failed",
1005 ConstantCommon::EncryptDevId(remoteUdid).c_str(), remoteTokenID);
1006 std::string errorReason = "token sync call error, error number is " + std::to_string(ret);
1007 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
1008 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
1009 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", errorReason);
1010 return 0;
1011 }
1012
1013 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, remoteTokenID);
1014 }
1015 #else
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)1016 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
1017 AccessTokenID remoteTokenID)
1018 {
1019 LOGE(ATM_DOMAIN, ATM_TAG, "Tokensync is disable, check dependent components");
1020 return 0;
1021 }
1022 #endif
1023
GetInstance()1024 AccessTokenInfoManager& AccessTokenInfoManager::GetInstance()
1025 {
1026 static AccessTokenInfoManager* instance = nullptr;
1027 if (instance == nullptr) {
1028 std::lock_guard<std::recursive_mutex> lock(g_instanceMutex);
1029 if (instance == nullptr) {
1030 AccessTokenInfoManager* tmp = new (std::nothrow) AccessTokenInfoManager();
1031 instance = std::move(tmp);
1032 }
1033 }
1034 return *instance;
1035 }
1036
GeneratePermExtendValues(AccessTokenID tokenID,const std::vector<PermissionWithValue> kernelPermList,std::vector<GenericValues> & permExtendValues)1037 static void GeneratePermExtendValues(AccessTokenID tokenID, const std::vector<PermissionWithValue> kernelPermList,
1038 std::vector<GenericValues>& permExtendValues)
1039 {
1040 for (auto& extendValue : kernelPermList) {
1041 GenericValues genericValues;
1042 genericValues.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1043 genericValues.Put(TokenFiledConst::FIELD_PERMISSION_NAME, extendValue.permissionName);
1044 genericValues.Put(TokenFiledConst::FIELD_VALUE, extendValue.value);
1045 permExtendValues.emplace_back(genericValues);
1046 }
1047 }
1048
GetUserGrantPermFromDef(const std::vector<PermissionDef> & permList,AccessTokenID tokenID,std::vector<GenericValues> & permDefValues)1049 static void GetUserGrantPermFromDef(const std::vector<PermissionDef>& permList, AccessTokenID tokenID,
1050 std::vector<GenericValues>& permDefValues)
1051 {
1052 for (const auto& def : permList) {
1053 GenericValues value;
1054 value.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1055 DataTranslator::TranslationIntoGenericValues(def, value);
1056 permDefValues.emplace_back(value);
1057 }
1058 }
1059
GenerateAddInfoToVec(AtmDataType type,const std::vector<GenericValues> & addValues,std::vector<AddInfo> & addInfoVec)1060 void AccessTokenInfoManager::GenerateAddInfoToVec(AtmDataType type, const std::vector<GenericValues>& addValues,
1061 std::vector<AddInfo>& addInfoVec)
1062 {
1063 AddInfo addInfo;
1064 addInfo.addType = type;
1065 addInfo.addValues = addValues;
1066 addInfoVec.emplace_back(addInfo);
1067 }
1068
GenerateDelInfoToVec(AtmDataType type,const GenericValues & delValue,std::vector<DelInfo> & delInfoVec)1069 void AccessTokenInfoManager::GenerateDelInfoToVec(AtmDataType type, const GenericValues& delValue,
1070 std::vector<DelInfo>& delInfoVec)
1071 {
1072 DelInfo delInfo;
1073 delInfo.delType = type;
1074 delInfo.delValue = delValue;
1075 delInfoVec.emplace_back(delInfo);
1076 }
1077
AddHapTokenInfoToDb(const std::shared_ptr<HapTokenInfoInner> & hapInfo,const std::string & appId,const HapPolicy & policy,bool isUpdate,const std::vector<GenericValues> & undefValues)1078 int AccessTokenInfoManager::AddHapTokenInfoToDb(const std::shared_ptr<HapTokenInfoInner>& hapInfo,
1079 const std::string& appId, const HapPolicy& policy, bool isUpdate, const std::vector<GenericValues>& undefValues)
1080 {
1081 if (hapInfo == nullptr) {
1082 LOGC(ATM_DOMAIN, ATM_TAG, "Token info is null!");
1083 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1084 }
1085 if (hapInfo->IsRemote()) {
1086 LOGC(ATM_DOMAIN, ATM_TAG, "It is a remote hap!");
1087 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1088 }
1089 AccessTokenID tokenID = hapInfo->GetTokenID();
1090 bool isSystemRes = IsSystemResource(hapInfo->GetBundleName());
1091
1092 std::vector<AddInfo> addInfoVec;
1093 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_HAP_UNDEFINE_INFO, undefValues, addInfoVec);
1094
1095 std::vector<GenericValues> hapInfoValues; // get new hap token info from cache
1096 hapInfo->StoreHapInfo(hapInfoValues, appId, policy.apl);
1097 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_HAP_INFO, hapInfoValues, addInfoVec);
1098
1099 std::vector<GenericValues> permStateValues; // get new permission status from cache if exist
1100 hapInfo->StorePermissionPolicy(permStateValues);
1101 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, permStateValues, addInfoVec);
1102
1103 std::vector<PermissionWithValue> extendedPermList;
1104 PermissionDataBrief::GetInstance().GetExtendedValueList(tokenID, extendedPermList);
1105 std::vector<GenericValues> permExtendValues; // get new extend permission value
1106 GeneratePermExtendValues(tokenID, extendedPermList, permExtendValues);
1107 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_EXTEND_VALUE, permExtendValues, addInfoVec);
1108
1109 if (isSystemRes) {
1110 std::vector<GenericValues> permDefValues;
1111 GetUserGrantPermFromDef(policy.permList, tokenID, permDefValues);
1112 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, permDefValues, addInfoVec);
1113 }
1114
1115 std::vector<DelInfo> delInfoVec;
1116 GenericValues delValue;
1117 delValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1118 if (isUpdate) { // udapte: delete and add; otherwise add only
1119 for (auto const& addInfo : addInfoVec) {
1120 GenerateDelInfoToVec(addInfo.addType, delValue, delInfoVec);
1121 }
1122 }
1123
1124 return AccessTokenDbOperator::DeleteAndInsertValues(delInfoVec, addInfoVec);
1125 }
1126
RemoveHapTokenInfoFromDb(const std::shared_ptr<HapTokenInfoInner> & info)1127 int AccessTokenInfoManager::RemoveHapTokenInfoFromDb(const std::shared_ptr<HapTokenInfoInner>& info)
1128 {
1129 AccessTokenID tokenID = info->GetTokenID();
1130 GenericValues condition;
1131 condition.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1132
1133 std::vector<DelInfo> delInfoVec;
1134 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_HAP_INFO, condition, delInfoVec);
1135 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, condition, delInfoVec);
1136 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_EXTEND_VALUE, condition, delInfoVec);
1137 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_HAP_UNDEFINE_INFO, condition, delInfoVec);
1138
1139 if (IsSystemResource(info->GetBundleName())) {
1140 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, condition, delInfoVec);
1141 }
1142
1143 std::vector<AddInfo> addInfoVec;
1144 int32_t ret = AccessTokenDbOperator::DeleteAndInsertValues(delInfoVec, addInfoVec);
1145 if (ret != RET_SUCCESS) {
1146 LOGC(ATM_DOMAIN, ATM_TAG, "Id %{public}d DeleteAndInsertHap failed, ret %{public}d.", tokenID, ret);
1147 return ret;
1148 }
1149 return RET_SUCCESS;
1150 }
1151
PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner> & info,AccessTokenID id)1152 void AccessTokenInfoManager::PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner>& info, AccessTokenID id)
1153 {
1154 std::vector<std::string> permissionList;
1155 int32_t userId = info->GetUserID();
1156 {
1157 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1158 if (!permPolicyList_.empty() &&
1159 (std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userId) != inactiveUserList_.end())) {
1160 LOGI(ATM_DOMAIN, ATM_TAG, "Execute user policy.");
1161 HapTokenInfoInner::GetGrantedPermByTokenId(id, permPolicyList_, permissionList);
1162 } else {
1163 std::vector<std::string> emptyList;
1164 HapTokenInfoInner::GetGrantedPermByTokenId(id, emptyList, permissionList);
1165 }
1166 }
1167 if (permissionList.size() != 0) {
1168 PermissionManager::GetInstance().ParamUpdate(permissionList[0], 0, true);
1169 }
1170 for (const auto& permissionName : permissionList) {
1171 CallbackManager::GetInstance().ExecuteCallbackAsync(
1172 id, permissionName, PermStateChangeType::STATE_CHANGE_REVOKED);
1173 }
1174 }
1175
GetHapAppIdByTokenId(AccessTokenID tokenID,std::string & appId)1176 int32_t AccessTokenInfoManager::GetHapAppIdByTokenId(AccessTokenID tokenID, std::string& appId)
1177 {
1178 GenericValues conditionValue;
1179 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1180 std::vector<GenericValues> hapTokenResults;
1181 int32_t ret = AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, hapTokenResults);
1182 if (ret != RET_SUCCESS) {
1183 LOGE(ATM_DOMAIN, ATM_TAG,
1184 "Failed to find Id(%{public}u) from hap_token_table, err: %{public}d.", tokenID, ret);
1185 return ret;
1186 }
1187
1188 if (hapTokenResults.empty()) {
1189 LOGE(ATM_DOMAIN, ATM_TAG, "Id(%{public}u) is not in hap_token_table.", tokenID);
1190 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1191 }
1192 std::string result = hapTokenResults[0].GetString(TokenFiledConst::FIELD_APP_ID);
1193 if (!DataValidator::IsAppIDDescValid(result)) {
1194 LOGE(ATM_DOMAIN, ATM_TAG, "TokenID: 0x%{public}x appID is error.", tokenID);
1195 return AccessTokenError::ERR_PARAM_INVALID;
1196 }
1197 appId = result;
1198 return RET_SUCCESS;
1199 }
1200
GetNativeTokenId(const std::string & processName)1201 AccessTokenID AccessTokenInfoManager::GetNativeTokenId(const std::string& processName)
1202 {
1203 AccessTokenID tokenID = INVALID_TOKENID;
1204 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1205 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); ++iter) {
1206 if (iter->second.processName == processName) {
1207 tokenID = iter->first;
1208 break;
1209 }
1210 }
1211 return tokenID;
1212 }
1213
DumpHapTokenInfoByTokenId(const AccessTokenID tokenId,std::string & dumpInfo)1214 void AccessTokenInfoManager::DumpHapTokenInfoByTokenId(const AccessTokenID tokenId, std::string& dumpInfo)
1215 {
1216 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(tokenId);
1217 if (type == TOKEN_HAP) {
1218 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenId);
1219 if (infoPtr != nullptr) {
1220 dumpInfo = infoPtr->ToString();
1221 }
1222 } else if (type == TOKEN_NATIVE || type == TOKEN_SHELL) {
1223 dumpInfo = NativeTokenToString(tokenId);
1224 } else {
1225 dumpInfo.append("invalid tokenId");
1226 }
1227 }
1228
DumpHapTokenInfoByBundleName(const std::string & bundleName,std::string & dumpInfo)1229 void AccessTokenInfoManager::DumpHapTokenInfoByBundleName(const std::string& bundleName, std::string& dumpInfo)
1230 {
1231 Utils::UniqueReadGuard<Utils::RWLock> hapInfoGuard(this->hapTokenInfoLock_);
1232 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
1233 if (iter->second != nullptr) {
1234 if (bundleName != iter->second->GetBundleName()) {
1235 continue;
1236 }
1237 dumpInfo = iter->second->ToString();
1238 dumpInfo.append("\n");
1239 }
1240 }
1241 }
1242
DumpAllHapTokenname(std::string & dumpInfo)1243 void AccessTokenInfoManager::DumpAllHapTokenname(std::string& dumpInfo)
1244 {
1245 LOGD(ATM_DOMAIN, ATM_TAG, "Get all hap token name.");
1246
1247 Utils::UniqueReadGuard<Utils::RWLock> hapInfoGuard(this->hapTokenInfoLock_);
1248 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
1249 if (iter->second != nullptr) {
1250 dumpInfo += std::to_string(iter->second->GetTokenID()) + ": " + iter->second->GetBundleName();
1251 dumpInfo.append("\n");
1252 }
1253 }
1254 }
1255
DumpNativeTokenInfoByProcessName(const std::string & processName,std::string & dumpInfo)1256 void AccessTokenInfoManager::DumpNativeTokenInfoByProcessName(const std::string& processName, std::string& dumpInfo)
1257 {
1258 dumpInfo = NativeTokenToString(GetNativeTokenId(processName));
1259 }
1260
DumpAllNativeTokenName(std::string & dumpInfo)1261 void AccessTokenInfoManager::DumpAllNativeTokenName(std::string& dumpInfo)
1262 {
1263 LOGD(ATM_DOMAIN, ATM_TAG, "Get all native token name.");
1264
1265 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1266 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1267 dumpInfo += std::to_string(iter->first) + ": " + iter->second.processName;
1268 dumpInfo.append("\n");
1269 }
1270 }
1271
DumpTokenInfo(const AtmToolsParamInfo & info,std::string & dumpInfo)1272 void AccessTokenInfoManager::DumpTokenInfo(const AtmToolsParamInfo& info, std::string& dumpInfo)
1273 {
1274 if (info.tokenId != 0) {
1275 DumpHapTokenInfoByTokenId(info.tokenId, dumpInfo);
1276 return;
1277 }
1278
1279 if ((!info.bundleName.empty()) && (info.bundleName.length() > 0)) {
1280 DumpHapTokenInfoByBundleName(info.bundleName, dumpInfo);
1281 return;
1282 }
1283
1284 if ((!info.processName.empty()) && (info.processName.length() > 0)) {
1285 DumpNativeTokenInfoByProcessName(info.processName, dumpInfo);
1286 return;
1287 }
1288
1289 DumpAllHapTokenname(dumpInfo);
1290 DumpAllNativeTokenName(dumpInfo);
1291 }
1292
1293
ClearUserGrantedPermissionState(AccessTokenID tokenID)1294 void AccessTokenInfoManager::ClearUserGrantedPermissionState(AccessTokenID tokenID)
1295 {
1296 if (ClearUserGrantedPermission(tokenID) != RET_SUCCESS) {
1297 return;
1298 }
1299 std::vector<AccessTokenID> tokenIdList;
1300 GetRelatedSandBoxHapList(tokenID, tokenIdList);
1301 for (const auto& id : tokenIdList) {
1302 (void)ClearUserGrantedPermission(id);
1303 }
1304 // DFX
1305 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "CLEAR_USER_PERMISSION_STATE",
1306 HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "TOKENID", tokenID,
1307 "TOKENID_LEN", static_cast<uint32_t>(tokenIdList.size()));
1308 }
1309
ClearUserGrantedPermission(AccessTokenID id)1310 int32_t AccessTokenInfoManager::ClearUserGrantedPermission(AccessTokenID id)
1311 {
1312 std::shared_ptr<HapTokenInfoInner> infoPtr = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(id);
1313 if (infoPtr == nullptr) {
1314 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid.", id);
1315 return ERR_PARAM_INVALID;
1316 }
1317 if (infoPtr->IsRemote()) {
1318 LOGE(ATM_DOMAIN, ATM_TAG, "It is a remote hap token %{public}u!", id);
1319 return ERR_IDENTITY_CHECK_FAILED;
1320 }
1321 std::vector<std::string> grantedPermListBefore;
1322 std::vector<std::string> emptyList;
1323 HapTokenInfoInner::GetGrantedPermByTokenId(id, emptyList, grantedPermListBefore);
1324
1325 // reset permission.
1326 int32_t ret = infoPtr->ResetUserGrantPermissionStatus();
1327 if (ret != RET_SUCCESS) {
1328 return ret;
1329 }
1330
1331 std::vector<std::string> grantedPermListAfter;
1332 HapTokenInfoInner::GetGrantedPermByTokenId(id, emptyList, grantedPermListAfter);
1333
1334 {
1335 int32_t userId = infoPtr->GetUserID();
1336 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1337 if (!permPolicyList_.empty() &&
1338 (std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userId) != inactiveUserList_.end())) {
1339 PermissionManager::GetInstance().AddHapPermToKernel(id, permPolicyList_);
1340 PermissionManager::GetInstance().NotifyUpdatedPermList(grantedPermListBefore, grantedPermListAfter, id);
1341 return RET_SUCCESS;
1342 }
1343 }
1344 PermissionManager::GetInstance().AddHapPermToKernel(id, std::vector<std::string>());
1345 LOGI(ATM_DOMAIN, ATM_TAG,
1346 "grantedPermListBefore size %{public}zu, grantedPermListAfter size %{public}zu!",
1347 grantedPermListBefore.size(), grantedPermListAfter.size());
1348 PermissionManager::GetInstance().NotifyUpdatedPermList(grantedPermListBefore, grantedPermListAfter, id);
1349 return RET_SUCCESS;
1350 }
1351
IsPermissionRestrictedByUserPolicy(AccessTokenID id,const std::string & permissionName)1352 bool AccessTokenInfoManager::IsPermissionRestrictedByUserPolicy(AccessTokenID id, const std::string& permissionName)
1353 {
1354 std::shared_ptr<HapTokenInfoInner> infoPtr = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(id);
1355 if (infoPtr == nullptr) {
1356 LOGE(ATM_DOMAIN, ATM_TAG, "Token %{public}u is invalid.", id);
1357 return true;
1358 }
1359 int32_t userId = infoPtr->GetUserID();
1360 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1361 if ((std::find(permPolicyList_.begin(), permPolicyList_.end(), permissionName) != permPolicyList_.end()) &&
1362 (std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userId) != inactiveUserList_.end())) {
1363 LOGI(ATM_DOMAIN, ATM_TAG, "id %{public}u perm %{public}s.", id, permissionName.c_str());
1364 return true;
1365 }
1366 return false;
1367 }
1368
GetRelatedSandBoxHapList(AccessTokenID tokenId,std::vector<AccessTokenID> & tokenIdList)1369 void AccessTokenInfoManager::GetRelatedSandBoxHapList(AccessTokenID tokenId, std::vector<AccessTokenID>& tokenIdList)
1370 {
1371 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1372
1373 auto infoIter = hapTokenInfoMap_.find(tokenId);
1374 if (infoIter == hapTokenInfoMap_.end()) {
1375 return;
1376 }
1377 if (infoIter->second == nullptr) {
1378 LOGE(ATM_DOMAIN, ATM_TAG, "HapTokenInfoInner is nullptr.");
1379 return;
1380 }
1381 std::string bundleName = infoIter->second->GetBundleName();
1382 int32_t userID = infoIter->second->GetUserID();
1383 int32_t index = infoIter->second->GetInstIndex();
1384 int32_t dlpType = infoIter->second->GetDlpType();
1385 // the permissions of a common application whose index is not equal 0 are managed independently.
1386 if ((dlpType == DLP_COMMON) && (index != 0)) {
1387 return;
1388 }
1389
1390 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); ++iter) {
1391 if (iter->second == nullptr) {
1392 continue;
1393 }
1394 if ((bundleName == iter->second->GetBundleName()) && (userID == iter->second->GetUserID()) &&
1395 (tokenId != iter->second->GetTokenID())) {
1396 if ((iter->second->GetDlpType() == DLP_COMMON) && (iter->second->GetInstIndex() != 0)) {
1397 continue;
1398 }
1399 tokenIdList.emplace_back(iter->second->GetTokenID());
1400 }
1401 }
1402 }
1403
SetPermDialogCap(AccessTokenID tokenID,bool enable)1404 int32_t AccessTokenInfoManager::SetPermDialogCap(AccessTokenID tokenID, bool enable)
1405 {
1406 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1407 auto infoIter = hapTokenInfoMap_.find(tokenID);
1408 if ((infoIter == hapTokenInfoMap_.end()) || (infoIter->second == nullptr)) {
1409 LOGE(ATM_DOMAIN, ATM_TAG, "HapTokenInfoInner is nullptr.");
1410 return ERR_TOKENID_NOT_EXIST;
1411 }
1412 infoIter->second->SetPermDialogForbidden(enable);
1413
1414 if (!UpdateCapStateToDatabase(tokenID, enable)) {
1415 return RET_FAILED;
1416 }
1417
1418 return RET_SUCCESS;
1419 }
1420
ParseUserPolicyInfo(const std::vector<UserState> & userList,const std::vector<std::string> & permList,std::map<int32_t,bool> & changedUserList)1421 int32_t AccessTokenInfoManager::ParseUserPolicyInfo(const std::vector<UserState>& userList,
1422 const std::vector<std::string>& permList, std::map<int32_t, bool>& changedUserList)
1423 {
1424 if (!permPolicyList_.empty()) {
1425 LOGE(ATM_DOMAIN, ATM_TAG, "UserPolicy has been initialized.");
1426 return ERR_USER_POLICY_INITIALIZED;
1427 }
1428 for (const auto &permission : permList) {
1429 if (std::find(permPolicyList_.begin(), permPolicyList_.end(), permission) == permPolicyList_.end()) {
1430 permPolicyList_.emplace_back(permission);
1431 }
1432 }
1433
1434 if (permPolicyList_.empty()) {
1435 LOGE(ATM_DOMAIN, ATM_TAG, "permList is invalid.");
1436 return ERR_PARAM_INVALID;
1437 }
1438 for (const auto &userInfo : userList) {
1439 if (userInfo.userId < 0) {
1440 LOGW(ATM_DOMAIN, ATM_TAG, "userId %{public}d is invalid.", userInfo.userId);
1441 continue;
1442 }
1443 if (userInfo.isActive) {
1444 LOGI(ATM_DOMAIN, ATM_TAG, "userid %{public}d is active.", userInfo.userId);
1445 continue;
1446 }
1447 inactiveUserList_.emplace_back(userInfo.userId);
1448 changedUserList[userInfo.userId] = false;
1449 }
1450
1451 return RET_SUCCESS;
1452 }
1453
ParseUserPolicyInfo(const std::vector<UserState> & userList,std::map<int32_t,bool> & changedUserList)1454 int32_t AccessTokenInfoManager::ParseUserPolicyInfo(const std::vector<UserState>& userList,
1455 std::map<int32_t, bool>& changedUserList)
1456 {
1457 if (permPolicyList_.empty()) {
1458 LOGE(ATM_DOMAIN, ATM_TAG, "UserPolicy has been initialized.");
1459 return ERR_USER_POLICY_NOT_INITIALIZED;
1460 }
1461 for (const auto &userInfo : userList) {
1462 if (userInfo.userId < 0) {
1463 LOGW(ATM_DOMAIN, ATM_TAG, "UserId %{public}d is invalid.", userInfo.userId);
1464 continue;
1465 }
1466 auto iter = std::find(inactiveUserList_.begin(), inactiveUserList_.end(), userInfo.userId);
1467 // the userid is changed to foreground
1468 if ((iter != inactiveUserList_.end() && userInfo.isActive)) {
1469 inactiveUserList_.erase(iter);
1470 changedUserList[userInfo.userId] = userInfo.isActive;
1471 }
1472 // the userid is changed to background
1473 if ((iter == inactiveUserList_.end() && !userInfo.isActive)) {
1474 changedUserList[userInfo.userId] = userInfo.isActive;
1475 inactiveUserList_.emplace_back(userInfo.userId);
1476 }
1477 }
1478 return RET_SUCCESS;
1479 }
1480
GetGoalHapList(std::map<AccessTokenID,bool> & tokenIdList,std::map<int32_t,bool> & changedUserList)1481 void AccessTokenInfoManager::GetGoalHapList(std::map<AccessTokenID, bool>& tokenIdList,
1482 std::map<int32_t, bool>& changedUserList)
1483 {
1484 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1485 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); ++iter) {
1486 AccessTokenID tokenId = iter->first;
1487 std::shared_ptr<HapTokenInfoInner> infoPtr = iter->second;
1488 if (infoPtr == nullptr) {
1489 LOGE(ATM_DOMAIN, ATM_TAG, "TokenId infoPtr is null.");
1490 continue;
1491 }
1492 auto userInfo = changedUserList.find(infoPtr->GetUserID());
1493 if (userInfo != changedUserList.end()) {
1494 // Record the policy status of hap (active or not).
1495 tokenIdList[tokenId] = userInfo->second;
1496 }
1497 }
1498 return;
1499 }
1500
UpdatePermissionStateToKernel(const std::map<AccessTokenID,bool> & tokenIdList)1501 int32_t AccessTokenInfoManager::UpdatePermissionStateToKernel(const std::map<AccessTokenID, bool>& tokenIdList)
1502 {
1503 for (auto iter = tokenIdList.begin(); iter != tokenIdList.end(); ++iter) {
1504 AccessTokenID tokenId = iter->first;
1505 bool isActive = iter->second;
1506 // refresh under userPolicyLock_
1507 {
1508 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1509 std::map<std::string, bool> refreshedPermList;
1510 HapTokenInfoInner::RefreshPermStateToKernel(permPolicyList_, isActive, tokenId, refreshedPermList);
1511
1512 if (refreshedPermList.size() != 0) {
1513 PermissionManager::GetInstance().ParamUpdate(std::string(), 0, true);
1514 }
1515 for (auto perm = refreshedPermList.begin(); perm != refreshedPermList.end(); ++perm) {
1516 PermStateChangeType change = perm->second ?
1517 PermStateChangeType::STATE_CHANGE_GRANTED : PermStateChangeType::STATE_CHANGE_REVOKED;
1518 CallbackManager::GetInstance().ExecuteCallbackAsync(tokenId, perm->first, change);
1519 }
1520 }
1521 }
1522 return RET_SUCCESS;
1523 }
1524
UpdatePermissionStateToKernel(const std::vector<std::string> & permCodeList,const std::map<AccessTokenID,bool> & tokenIdList)1525 int32_t AccessTokenInfoManager::UpdatePermissionStateToKernel(const std::vector<std::string>& permCodeList,
1526 const std::map<AccessTokenID, bool>& tokenIdList)
1527 {
1528 for (auto iter = tokenIdList.begin(); iter != tokenIdList.end(); ++iter) {
1529 AccessTokenID tokenId = iter->first;
1530 bool isActive = iter->second;
1531 std::map<std::string, bool> refreshedPermList;
1532 HapTokenInfoInner::RefreshPermStateToKernel(permCodeList, isActive, tokenId, refreshedPermList);
1533
1534 if (refreshedPermList.size() != 0) {
1535 PermissionManager::GetInstance().ParamUpdate(std::string(), 0, true);
1536 }
1537 for (auto perm = refreshedPermList.begin(); perm != refreshedPermList.end(); ++perm) {
1538 LOGI(ATM_DOMAIN, ATM_TAG, "Perm %{public}s refreshed by user policy, isActive %{public}d.",
1539 perm->first.c_str(), perm->second);
1540 PermStateChangeType change = perm->second ?
1541 PermStateChangeType::STATE_CHANGE_GRANTED : PermStateChangeType::STATE_CHANGE_REVOKED;
1542 CallbackManager::GetInstance().ExecuteCallbackAsync(tokenId, perm->first, change);
1543 }
1544 }
1545 return RET_SUCCESS;
1546 }
1547
InitUserPolicy(const std::vector<UserState> & userList,const std::vector<std::string> & permList)1548 int32_t AccessTokenInfoManager::InitUserPolicy(
1549 const std::vector<UserState>& userList, const std::vector<std::string>& permList)
1550 {
1551 std::map<AccessTokenID, bool> tokenIdList;
1552 {
1553 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1554 std::map<int32_t, bool> changedUserList;
1555 int32_t ret = ParseUserPolicyInfo(userList, permList, changedUserList);
1556 if (ret != RET_SUCCESS) {
1557 return ret;
1558 }
1559 if (changedUserList.empty()) {
1560 LOGI(ATM_DOMAIN, ATM_TAG, "changedUserList is empty.");
1561 return ret;
1562 }
1563 GetGoalHapList(tokenIdList, changedUserList);
1564 }
1565 return UpdatePermissionStateToKernel(tokenIdList);
1566 }
1567
UpdateUserPolicy(const std::vector<UserState> & userList)1568 int32_t AccessTokenInfoManager::UpdateUserPolicy(const std::vector<UserState>& userList)
1569 {
1570 std::map<AccessTokenID, bool> tokenIdList;
1571 {
1572 std::map<int32_t, bool> changedUserList;
1573 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1574 int32_t ret = ParseUserPolicyInfo(userList, changedUserList);
1575 if (ret != RET_SUCCESS) {
1576 return ret;
1577 }
1578 if (changedUserList.empty()) {
1579 LOGI(ATM_DOMAIN, ATM_TAG, "changedUserList is empty.");
1580 return ret;
1581 }
1582 GetGoalHapList(tokenIdList, changedUserList);
1583 }
1584 return UpdatePermissionStateToKernel(tokenIdList);
1585 }
1586
ClearUserPolicy()1587 int32_t AccessTokenInfoManager::ClearUserPolicy()
1588 {
1589 std::map<AccessTokenID, bool> tokenIdList;
1590 std::vector<std::string> permList;
1591 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->userPolicyLock_);
1592 if (permPolicyList_.empty()) {
1593 LOGW(ATM_DOMAIN, ATM_TAG, "UserPolicy has been cleared.");
1594 return RET_SUCCESS;
1595 }
1596 permList.assign(permPolicyList_.begin(), permPolicyList_.end());
1597 std::map<int32_t, bool> changedUserList;
1598 for (const auto &userId : inactiveUserList_) {
1599 // All user comes to be active for permission manager.
1600 changedUserList[userId] = true;
1601 }
1602 GetGoalHapList(tokenIdList, changedUserList);
1603 int32_t ret = UpdatePermissionStateToKernel(permList, tokenIdList);
1604 // Lock range is large. While The number of ClearUserPolicy function calls is very small.
1605 if (ret == RET_SUCCESS) {
1606 permPolicyList_.clear();
1607 inactiveUserList_.clear();
1608 }
1609 return ret;
1610 }
1611
GetPermDialogCap(AccessTokenID tokenID)1612 bool AccessTokenInfoManager::GetPermDialogCap(AccessTokenID tokenID)
1613 {
1614 if (tokenID == INVALID_TOKENID) {
1615 LOGE(ATM_DOMAIN, ATM_TAG, "Invalid tokenId.");
1616 return true;
1617 }
1618 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1619 auto infoIter = hapTokenInfoMap_.find(tokenID);
1620 if ((infoIter == hapTokenInfoMap_.end()) || (infoIter->second == nullptr)) {
1621 LOGE(ATM_DOMAIN, ATM_TAG, "TokenId is not exist in map.");
1622 return true;
1623 }
1624 return infoIter->second->IsPermDialogForbidden();
1625 }
1626
UpdateCapStateToDatabase(AccessTokenID tokenID,bool enable)1627 bool AccessTokenInfoManager::UpdateCapStateToDatabase(AccessTokenID tokenID, bool enable)
1628 {
1629 GenericValues modifyValue;
1630 modifyValue.Put(TokenFiledConst::FIELD_FORBID_PERM_DIALOG, enable);
1631
1632 GenericValues conditionValue;
1633 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1634
1635 int32_t res = AccessTokenDbOperator::Modify(AtmDataType::ACCESSTOKEN_HAP_INFO, modifyValue, conditionValue);
1636 if (res != 0) {
1637 LOGE(ATM_DOMAIN, ATM_TAG,
1638 "Update tokenID %{public}u permissionDialogForbidden %{public}d to database failed", tokenID, enable);
1639 return false;
1640 }
1641
1642 return true;
1643 }
1644
VerifyNativeAccessToken(AccessTokenID tokenID,const std::string & permissionName)1645 int AccessTokenInfoManager::VerifyNativeAccessToken(AccessTokenID tokenID, const std::string& permissionName)
1646 {
1647 if (!IsDefinedPermission(permissionName)) {
1648 LOGE(ATM_DOMAIN, ATM_TAG, "No definition for permission: %{public}s!", permissionName.c_str());
1649 return PERMISSION_DENIED;
1650 }
1651 uint32_t code;
1652 if (!TransferPermissionToOpcode(permissionName, code)) {
1653 LOGE(ATM_DOMAIN, ATM_TAG, "Invalid perm(%{public}s)", permissionName.c_str());
1654 return PERMISSION_DENIED;
1655 }
1656
1657 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1658 auto iter = nativeTokenInfoMap_.find(tokenID);
1659 if (iter == nativeTokenInfoMap_.end()) {
1660 LOGE(ATM_DOMAIN, ATM_TAG, "Id %{public}u is not exist.", tokenID);
1661 return PERMISSION_DENIED;
1662 }
1663
1664 NativeTokenInfoCache cache = iter->second;
1665 for (size_t i = 0; i < cache.opCodeList.size(); ++i) {
1666 if (code == cache.opCodeList[i]) {
1667 return cache.statusList[i] ? PERMISSION_GRANTED : PERMISSION_DENIED;
1668 }
1669 }
1670
1671 return PERMISSION_DENIED;
1672 }
1673
VerifyAccessToken(AccessTokenID tokenID,const std::string & permissionName)1674 int32_t AccessTokenInfoManager::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName)
1675 {
1676 if (tokenID == INVALID_TOKENID) {
1677 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_CHECK",
1678 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", VERIFY_TOKEN_ID_ERROR, "CALLER_TOKENID",
1679 static_cast<AccessTokenID>(IPCSkeleton::GetCallingTokenID()), "PERMISSION_NAME", permissionName);
1680 LOGE(ATM_DOMAIN, ATM_TAG, "TokenID is invalid");
1681 return PERMISSION_DENIED;
1682 }
1683
1684 if (!PermissionValidator::IsPermissionNameValid(permissionName)) {
1685 LOGE(ATM_DOMAIN, ATM_TAG, "PermissionName: %{public}s, invalid params!", permissionName.c_str());
1686 return PERMISSION_DENIED;
1687 }
1688
1689 ATokenTypeEnum tokenType = TokenIDAttributes::GetTokenIdTypeEnum(tokenID);
1690 if ((tokenType == TOKEN_NATIVE) || (tokenType == TOKEN_SHELL)) {
1691 return VerifyNativeAccessToken(tokenID, permissionName);
1692 }
1693 if (tokenType == TOKEN_HAP) {
1694 return PermissionManager::GetInstance().VerifyHapAccessToken(tokenID, permissionName);
1695 }
1696 LOGE(ATM_DOMAIN, ATM_TAG, "TokenID: %{public}d, invalid tokenType!", tokenID);
1697 return PERMISSION_DENIED;
1698 }
1699
AddPermRequestToggleStatusToDb(int32_t userID,const std::string & permissionName,int32_t status)1700 int32_t AccessTokenInfoManager::AddPermRequestToggleStatusToDb(
1701 int32_t userID, const std::string& permissionName, int32_t status)
1702 {
1703 GenericValues condition;
1704 condition.Put(TokenFiledConst::FIELD_USER_ID, userID);
1705 condition.Put(TokenFiledConst::FIELD_PERMISSION_NAME, permissionName);
1706
1707 std::vector<DelInfo> delInfoVec;
1708 GenerateDelInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_REQUEST_TOGGLE_STATUS, condition, delInfoVec);
1709
1710 std::vector<GenericValues> values;
1711 condition.Put(TokenFiledConst::FIELD_REQUEST_TOGGLE_STATUS, status);
1712 values.emplace_back(condition);
1713
1714 std::vector<AddInfo> addInfoVec;
1715 GenerateAddInfoToVec(AtmDataType::ACCESSTOKEN_PERMISSION_REQUEST_TOGGLE_STATUS, values, addInfoVec);
1716
1717 int32_t ret = AccessTokenDbOperator::DeleteAndInsertValues(delInfoVec, addInfoVec);
1718 if (ret != RET_SUCCESS) {
1719 LOGE(ATM_DOMAIN, ATM_TAG, "DeleteAndInsertHap failed, ret %{public}d.", ret);
1720 return ret;
1721 }
1722 return RET_SUCCESS;
1723 }
1724
SetPermissionRequestToggleStatus(const std::string & permissionName,uint32_t status,int32_t userID)1725 int32_t AccessTokenInfoManager::SetPermissionRequestToggleStatus(const std::string& permissionName, uint32_t status,
1726 int32_t userID)
1727 {
1728 if (userID == 0) {
1729 userID = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1730 }
1731
1732 LOGI(ATM_DOMAIN, ATM_TAG, "UserID=%{public}u, permission=%{public}s, status=%{public}d", userID,
1733 permissionName.c_str(), status);
1734 if (!PermissionValidator::IsUserIdValid(userID) ||
1735 !PermissionValidator::IsPermissionNameValid(permissionName) ||
1736 !PermissionValidator::IsToggleStatusValid(status)) {
1737 LOGE(ATM_DOMAIN, ATM_TAG, "Invalid parameter(userId=%{public}d, perm=%{public}s, status=%{public}d).",
1738 userID, permissionName.c_str(), status);
1739 return AccessTokenError::ERR_PARAM_INVALID;
1740 }
1741 if (!IsDefinedPermission(permissionName)) {
1742 LOGE(ATM_DOMAIN, ATM_TAG, "Permission=%{public}s is not defined.", permissionName.c_str());
1743 return AccessTokenError::ERR_PERMISSION_NOT_EXIST;
1744 }
1745 if (!IsUserGrantPermission(permissionName)) {
1746 LOGE(ATM_DOMAIN, ATM_TAG, "Only support permissions of user_grant to set.");
1747 return AccessTokenError::ERR_PARAM_INVALID;
1748 }
1749
1750 int32_t ret = AddPermRequestToggleStatusToDb(userID, permissionName, status);
1751 if (ret != RET_SUCCESS) {
1752 return ret;
1753 }
1754
1755 (void)HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERM_DIALOG_STATUS_INFO",
1756 HiviewDFX::HiSysEvent::EventType::STATISTIC, "USERID", userID, "PERMISSION_NAME", permissionName,
1757 "TOGGLE_STATUS", status);
1758
1759 return RET_SUCCESS;
1760 }
1761
FindPermRequestToggleStatusFromDb(int32_t userID,const std::string & permissionName)1762 int32_t AccessTokenInfoManager::FindPermRequestToggleStatusFromDb(int32_t userID, const std::string& permissionName)
1763 {
1764 std::vector<GenericValues> result;
1765 GenericValues conditionValue;
1766 conditionValue.Put(TokenFiledConst::FIELD_USER_ID, userID);
1767 conditionValue.Put(TokenFiledConst::FIELD_PERMISSION_NAME, permissionName);
1768
1769 (void)AccessTokenDbOperator::Find(AtmDataType::ACCESSTOKEN_PERMISSION_REQUEST_TOGGLE_STATUS, conditionValue,
1770 result);
1771 if (result.empty()) {
1772 // never set, return default status: CLOSED if APP_TRACKING_CONSENT
1773 return (permissionName == "ohos.permission.APP_TRACKING_CONSENT") ?
1774 PermissionRequestToggleStatus::CLOSED : PermissionRequestToggleStatus::OPEN;
1775 }
1776 return result[0].GetInt(TokenFiledConst::FIELD_REQUEST_TOGGLE_STATUS);
1777 }
1778
GetPermissionRequestToggleStatus(const std::string & permissionName,uint32_t & status,int32_t userID)1779 int32_t AccessTokenInfoManager::GetPermissionRequestToggleStatus(const std::string& permissionName, uint32_t& status,
1780 int32_t userID)
1781 {
1782 if (userID == 0) {
1783 userID = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1784 }
1785
1786 LOGI(ATM_DOMAIN, ATM_TAG, "UserID=%{public}u, permissionName=%{public}s", userID, permissionName.c_str());
1787 if (!PermissionValidator::IsUserIdValid(userID) ||
1788 !PermissionValidator::IsPermissionNameValid(permissionName)) {
1789 LOGE(ATM_DOMAIN, ATM_TAG, "Invalid parameter(userId=%{public}d, perm=%{public}s.",
1790 userID, permissionName.c_str());
1791 return AccessTokenError::ERR_PARAM_INVALID;
1792 }
1793 if (!IsDefinedPermission(permissionName)) {
1794 LOGE(ATM_DOMAIN, ATM_TAG, "Permission=%{public}s is not defined.", permissionName.c_str());
1795 return AccessTokenError::ERR_PERMISSION_NOT_EXIST;
1796 }
1797 if (!IsUserGrantPermission(permissionName)) {
1798 LOGE(ATM_DOMAIN, ATM_TAG, "Only support permissions of user_grant to get.");
1799 return AccessTokenError::ERR_PARAM_INVALID;
1800 }
1801
1802 status = static_cast<uint32_t>(FindPermRequestToggleStatusFromDb(userID, permissionName));
1803
1804 return 0;
1805 }
1806
1807
GetKernelPermissions(AccessTokenID tokenId,std::vector<PermissionWithValue> & kernelPermList)1808 int32_t AccessTokenInfoManager::GetKernelPermissions(
1809 AccessTokenID tokenId, std::vector<PermissionWithValue>& kernelPermList)
1810 {
1811 return PermissionDataBrief::GetInstance().GetKernelPermissions(tokenId, kernelPermList);
1812 }
1813
1814
GetReqPermissionByName(AccessTokenID tokenId,const std::string & permissionName,std::string & value)1815 int32_t AccessTokenInfoManager::GetReqPermissionByName(
1816 AccessTokenID tokenId, const std::string& permissionName, std::string& value)
1817 {
1818 return PermissionDataBrief::GetInstance().GetReqPermissionByName(
1819 tokenId, permissionName, value, true);
1820 }
1821
NativeTokenToString(AccessTokenID tokenID)1822 std::string AccessTokenInfoManager::NativeTokenToString(AccessTokenID tokenID)
1823 {
1824 std::vector<NativeTokenInfoBase> tokenInfos;
1825 LibraryLoader loader(CONFIG_PARSE_LIBPATH);
1826 ConfigPolicyLoaderInterface* policy = loader.GetObject<ConfigPolicyLoaderInterface>();
1827 if (policy == nullptr) {
1828 LOGE(ATM_DOMAIN, ATM_TAG, "Dlopen libaccesstoken_json_parse failed.");
1829 return "";
1830 }
1831 int32_t ret = policy->GetAllNativeTokenInfo(tokenInfos);
1832 if (ret != RET_SUCCESS || tokenInfos.empty()) {
1833 LOGE(ATM_DOMAIN, ATM_TAG, "Failed to load native from native json, err=%{public}d.", ret);
1834 return "";
1835 }
1836 auto iter = tokenInfos.begin();
1837 while (iter != tokenInfos.end()) {
1838 if (iter->tokenID == tokenID) {
1839 break;
1840 }
1841 ++iter;
1842 }
1843 if (iter == tokenInfos.end()) {
1844 LOGE(ATM_DOMAIN, ATM_TAG, "Id %{public}u is not exist.", tokenID);
1845 return "";
1846 }
1847 NativeTokenInfoBase native = *iter;
1848 return policy->DumpNativeTokenInfo(native);
1849 }
1850 } // namespace AccessToken
1851 } // namespace Security
1852 } // namespace OHOS
1853