1 /*
2 * Copyright (c) 2021-2023 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 <securec.h>
19 #include "accesstoken_dfx_define.h"
20 #include "accesstoken_id_manager.h"
21 #include "accesstoken_log.h"
22 #include "accesstoken_remote_token_manager.h"
23 #include "access_token_error.h"
24 #include "callback_manager.h"
25 #include "constant_common.h"
26 #include "data_storage.h"
27 #include "data_translator.h"
28 #include "data_validator.h"
29 #ifdef SUPPORT_SANDBOX_APP
30 #include "dlp_permission_set_manager.h"
31 #endif
32 #include "generic_values.h"
33 #include "hap_token_info_inner.h"
34 #include "permission_definition_cache.h"
35 #include "permission_manager.h"
36 #include "softbus_bus_center.h"
37 #include "token_field_const.h"
38
39 #ifdef TOKEN_SYNC_ENABLE
40 #include "token_modify_notifier.h"
41 #include "token_sync_kit.h"
42 #endif
43
44 namespace OHOS {
45 namespace Security {
46 namespace AccessToken {
47 namespace {
48 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManager"};
49 static const std::string ACCESS_TOKEN_PACKAGE_NAME = "ohos.security.distributed_token_sync";
50 static const unsigned int SYSTEM_APP_FLAG = 0x0001;
51 }
52
AccessTokenInfoManager()53 AccessTokenInfoManager::AccessTokenInfoManager() : tokenDataWorker_("TokenStore"), hasInited_(false) {}
54
~AccessTokenInfoManager()55 AccessTokenInfoManager::~AccessTokenInfoManager()
56 {
57 if (!hasInited_) {
58 return;
59 }
60 this->tokenDataWorker_.Stop();
61 this->hasInited_ = false;
62 }
63
Init()64 void AccessTokenInfoManager::Init()
65 {
66 OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->managerLock_);
67 if (hasInited_) {
68 return;
69 }
70
71 ACCESSTOKEN_LOG_INFO(LABEL, "init begin!");
72 InitHapTokenInfos();
73 InitNativeTokenInfos();
74 this->tokenDataWorker_.Start(1);
75 hasInited_ = true;
76 ACCESSTOKEN_LOG_INFO(LABEL, "Init success");
77 }
78
InitHapTokenInfos()79 void AccessTokenInfoManager::InitHapTokenInfos()
80 {
81 std::vector<GenericValues> hapTokenRes;
82 std::vector<GenericValues> permDefRes;
83 std::vector<GenericValues> permStateRes;
84
85 DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_HAP_INFO, hapTokenRes);
86 DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefRes);
87 DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes);
88
89 for (const GenericValues& tokenValue : hapTokenRes) {
90 AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
91 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP);
92 if (ret != RET_SUCCESS) {
93 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add id failed.", tokenId);
94 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_CHECK",
95 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", LOAD_DATABASE_ERROR,
96 "ERROR_REASON", "hap tokenID error");
97 continue;
98 }
99 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>();
100 ret = hap->RestoreHapTokenInfo(tokenId, tokenValue, permStateRes);
101 if (ret != RET_SUCCESS) {
102 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
103 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u restore failed.", tokenId);
104 continue;
105 }
106
107 ret = AddHapTokenInfo(hap);
108 if (ret != RET_SUCCESS) {
109 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
110 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId);
111 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_CHECK",
112 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", LOAD_DATABASE_ERROR,
113 "ERROR_REASON", "hap token has exist");
114 continue;
115 }
116 ACCESSTOKEN_LOG_INFO(LABEL,
117 " restore hap token %{public}u bundle name %{public}s user %{public}d inst %{public}d ok!",
118 tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex());
119 }
120 PermissionDefinitionCache::GetInstance().RestorePermDefInfo(permDefRes);
121 }
122
InitNativeTokenInfos()123 void AccessTokenInfoManager::InitNativeTokenInfos()
124 {
125 std::vector<GenericValues> nativeTokenResults;
126 std::vector<GenericValues> permStateRes;
127
128 DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenResults);
129 DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes);
130 for (const GenericValues& nativeTokenValue : nativeTokenResults) {
131 AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
132 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenId);
133 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, type);
134 if (ret != RET_SUCCESS) {
135 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_CHECK",
136 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", LOAD_DATABASE_ERROR,
137 "ERROR_REASON", "native tokenID error");
138 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId);
139 continue;
140 }
141 std::shared_ptr<NativeTokenInfoInner> native = std::make_shared<NativeTokenInfoInner>();
142
143 ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue, permStateRes);
144 if (ret != RET_SUCCESS) {
145 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
146 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u restore failed.", tokenId);
147 continue;
148 }
149
150 ret = AddNativeTokenInfo(native);
151 if (ret != RET_SUCCESS) {
152 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
153 ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId);
154 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_CHECK",
155 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", LOAD_DATABASE_ERROR,
156 "ERROR_REASON", "native tokenID error");
157 continue;
158 }
159 ACCESSTOKEN_LOG_INFO(LABEL,
160 "restore native token %{public}u process name %{public}s ok!",
161 tokenId, native->GetProcessName().c_str());
162 }
163 }
164
GetHapUniqueStr(const int & userID,const std::string & bundleName,const int & instIndex) const165 std::string AccessTokenInfoManager::GetHapUniqueStr(const int& userID,
166 const std::string& bundleName, const int& instIndex) const
167 {
168 return bundleName + "&" + std::to_string(userID) + "&" + std::to_string(instIndex);
169 }
170
GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner> & info) const171 std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner>& info) const
172 {
173 if (info == nullptr) {
174 return std::string("");
175 }
176 return GetHapUniqueStr(info->GetUserID(), info->GetBundleName(), info->GetInstIndex());
177 }
178
AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner> & info)179 int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner>& info)
180 {
181 if (info == nullptr) {
182 ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null.");
183 return AccessTokenError::ERR_PARAM_INVALID;
184 }
185 AccessTokenID id = info->GetTokenID();
186 AccessTokenID idRemoved = INVALID_TOKENID;
187 {
188 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
189 if (hapTokenInfoMap_.count(id) > 0) {
190 ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u info has exist.", id);
191 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
192 }
193
194 if (!info->IsRemote()) {
195 std::string HapUniqueKey = GetHapUniqueStr(info);
196 auto iter = hapTokenIdMap_.find(HapUniqueKey);
197 if (iter != hapTokenIdMap_.end()) {
198 ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u Unique info has exist, update.", id);
199 idRemoved = iter->second;
200 }
201 hapTokenIdMap_[HapUniqueKey] = id;
202 }
203 hapTokenInfoMap_[id] = info;
204 }
205 if (idRemoved != INVALID_TOKENID) {
206 RemoveHapTokenInfo(idRemoved);
207 }
208
209 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "ADD_HAP", HiviewDFX::HiSysEvent::EventType::STATISTIC,
210 "TOKENID", info->GetTokenID(), "USERID", info->GetUserID(), "BUNDLENAME", info->GetBundleName(),
211 "INSTINDEX", info->GetInstIndex());
212
213 return RET_SUCCESS;
214 }
215
AddNativeTokenInfo(const std::shared_ptr<NativeTokenInfoInner> & info)216 int AccessTokenInfoManager::AddNativeTokenInfo(const std::shared_ptr<NativeTokenInfoInner>& info)
217 {
218 if (info == nullptr) {
219 ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null.");
220 return AccessTokenError::ERR_PARAM_INVALID;
221 }
222
223 AccessTokenID id = info->GetTokenID();
224 std::string processName = info->GetProcessName();
225 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
226 if (nativeTokenInfoMap_.count(id) > 0) {
227 ACCESSTOKEN_LOG_ERROR(
228 LABEL, "token %{public}u has exist.", id);
229 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
230 }
231 if (!info->IsRemote()) {
232 if (nativeTokenIdMap_.count(processName) > 0) {
233 ACCESSTOKEN_LOG_ERROR(
234 LABEL, "token %{public}u process name %{public}s has exist.", id, processName.c_str());
235 return AccessTokenError::ERR_PROCESS_NOT_EXIST;
236 }
237 nativeTokenIdMap_[processName] = id;
238 }
239
240 ACCESSTOKEN_LOG_INFO(LABEL, "token info is added %{public}u.", id);
241 nativeTokenInfoMap_[id] = info;
242
243 return RET_SUCCESS;
244 }
245
GetHapTokenInfoInner(AccessTokenID id)246 std::shared_ptr<HapTokenInfoInner> AccessTokenInfoManager::GetHapTokenInfoInner(AccessTokenID id)
247 {
248 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
249 auto iter = hapTokenInfoMap_.find(id);
250 if (iter != hapTokenInfoMap_.end()) {
251 return iter->second;
252 }
253 ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u is invalid.", id);
254 return nullptr;
255 }
256
IsTokenIdExist(AccessTokenID id)257 bool AccessTokenInfoManager::IsTokenIdExist(AccessTokenID id)
258 {
259 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
260 return ((hapTokenInfoMap_.count(id) != 0) || (nativeTokenInfoMap_.count(id) != 0));
261 }
262
GetHapTokenInfo(AccessTokenID tokenID,HapTokenInfo & infoParcel)263 int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& infoParcel)
264 {
265 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
266 if (infoPtr == nullptr) {
267 ACCESSTOKEN_LOG_ERROR(
268 LABEL, "token %{public}u is invalid.", tokenID);
269 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
270 }
271 infoPtr->TranslateToHapTokenInfo(infoParcel);
272 return RET_SUCCESS;
273 }
274
GetHapPermissionPolicySet(AccessTokenID id)275 std::shared_ptr<PermissionPolicySet> AccessTokenInfoManager::GetHapPermissionPolicySet(AccessTokenID id)
276 {
277 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(id);
278 if (infoPtr == nullptr) {
279 ACCESSTOKEN_LOG_ERROR(
280 LABEL, "token %{public}u is invalid.", id);
281 return nullptr;
282 }
283 return infoPtr->GetHapInfoPermissionPolicySet();
284 }
285
GetNativeTokenInfoInner(AccessTokenID id)286 std::shared_ptr<NativeTokenInfoInner> AccessTokenInfoManager::GetNativeTokenInfoInner(AccessTokenID id)
287 {
288 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
289 auto iter = nativeTokenInfoMap_.find(id);
290 if (iter != nativeTokenInfoMap_.end()) {
291 return iter->second;
292 }
293
294 ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u is invalid.", id);
295 return nullptr;
296 }
297
GetNativeTokenInfo(AccessTokenID tokenID,NativeTokenInfo & infoParcel)298 int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& infoParcel)
299 {
300 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenID);
301 if (infoPtr == nullptr) {
302 ACCESSTOKEN_LOG_ERROR(
303 LABEL, "token %{public}u is invalid.", tokenID);
304 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
305 }
306
307 infoPtr->TranslateToNativeTokenInfo(infoParcel);
308 return RET_SUCCESS;
309 }
310
GetNativePermissionPolicySet(AccessTokenID id)311 std::shared_ptr<PermissionPolicySet> AccessTokenInfoManager::GetNativePermissionPolicySet(AccessTokenID id)
312 {
313 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(id);
314 if (infoPtr == nullptr) {
315 ACCESSTOKEN_LOG_ERROR(
316 LABEL, "token %{public}u is invalid.", id);
317 return nullptr;
318 }
319 return infoPtr->GetNativeInfoPermissionPolicySet();
320 }
321
RemoveHapTokenInfo(AccessTokenID id)322 int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id)
323 {
324 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
325 if (type != TOKEN_HAP) {
326 ACCESSTOKEN_LOG_ERROR(
327 LABEL, "token %{public}u is not hap.", id);
328 return RET_FAILED;
329 }
330 std::shared_ptr<HapTokenInfoInner> info;
331 // make sure that RemoveDefPermissions is called outside of the lock to avoid deadlocks.
332 PermissionManager::GetInstance().RemoveDefPermissions(id);
333 {
334 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
335 if (hapTokenInfoMap_.count(id) == 0) {
336 ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u no exist.", id);
337 return RET_FAILED;
338 }
339
340 info = hapTokenInfoMap_[id];
341 if (info == nullptr) {
342 ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u is null.", id);
343 return RET_FAILED;
344 }
345 if (info->IsRemote()) {
346 ACCESSTOKEN_LOG_ERROR(LABEL, "remote hap token %{public}u can not delete.", id);
347 return RET_FAILED;
348 }
349 std::string HapUniqueKey = GetHapUniqueStr(info);
350 auto iter = hapTokenIdMap_.find(HapUniqueKey);
351 if ((iter != hapTokenIdMap_.end()) && (iter->second == id)) {
352 hapTokenIdMap_.erase(HapUniqueKey);
353 }
354 hapTokenInfoMap_.erase(id);
355 }
356
357 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
358 ACCESSTOKEN_LOG_INFO(LABEL, "remove hap token %{public}u ok!", id);
359 RefreshTokenInfoIfNeeded();
360 PermissionStateNotify(info, id);
361 #ifdef TOKEN_SYNC_ENABLE
362 TokenModifyNotifier::GetInstance().NotifyTokenDelete(id);
363 #endif
364
365 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "DEL_HAP", HiviewDFX::HiSysEvent::EventType::STATISTIC,
366 "TOKENID", info->GetTokenID(), "USERID", info->GetUserID(), "BUNDLENAME", info->GetBundleName(),
367 "INSTINDEX", info->GetInstIndex());
368
369 return RET_SUCCESS;
370 }
371
RemoveNativeTokenInfo(AccessTokenID id)372 int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id)
373 {
374 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
375 if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) {
376 ACCESSTOKEN_LOG_ERROR(
377 LABEL, "token %{public}u is not hap.", id);
378 return RET_FAILED;
379 }
380
381 {
382 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
383 if (nativeTokenInfoMap_.count(id) == 0) {
384 ACCESSTOKEN_LOG_ERROR(LABEL, "native token %{public}u is null.", id);
385 return RET_FAILED;
386 }
387
388 std::shared_ptr<NativeTokenInfoInner> info = nativeTokenInfoMap_[id];
389 if (info->IsRemote()) {
390 ACCESSTOKEN_LOG_ERROR(LABEL, "remote native token %{public}u can not delete.", id);
391 return RET_FAILED;
392 }
393 std::string processName = nativeTokenInfoMap_[id]->GetProcessName();
394 if (nativeTokenIdMap_.count(processName) != 0) {
395 nativeTokenIdMap_.erase(processName);
396 }
397 nativeTokenInfoMap_.erase(id);
398 }
399 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
400 ACCESSTOKEN_LOG_INFO(LABEL, "remove native token %{public}u ok!", id);
401 RefreshTokenInfoIfNeeded();
402 return RET_SUCCESS;
403 }
404
405 #ifdef SUPPORT_SANDBOX_APP
GetPolicyCopied(const HapPolicyParams & policy,HapPolicyParams & policyNew)406 static void GetPolicyCopied(const HapPolicyParams& policy, HapPolicyParams& policyNew)
407 {
408 policyNew.apl = policy.apl;
409 policyNew.domain = policy.domain;
410
411 for (const auto& state : policy.permStateList) {
412 policyNew.permStateList.emplace_back(state);
413 }
414 for (const auto& def : policy.permList) {
415 policyNew.permList.emplace_back(def);
416 }
417 }
418 #endif
419
CreateHapTokenInfo(const HapInfoParams & info,const HapPolicyParams & policy,AccessTokenIDEx & tokenIdEx)420 int AccessTokenInfoManager::CreateHapTokenInfo(
421 const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx)
422 {
423 if ((!DataValidator::IsUserIdValid(info.userID)) || (!DataValidator::IsBundleNameValid(info.bundleName)) ||
424 (!DataValidator::IsAppIDDescValid(info.appIDDesc)) || (!DataValidator::IsDomainValid(policy.domain)) ||
425 (!DataValidator::IsDlpTypeValid(info.dlpType))) {
426 ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed");
427 return AccessTokenError::ERR_PARAM_INVALID;
428 }
429 AccessTokenID tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP, info.dlpType);
430 if (tokenId == 0) {
431 ACCESSTOKEN_LOG_INFO(LABEL, "token Id create failed");
432 return RET_FAILED;
433 }
434 #ifdef SUPPORT_SANDBOX_APP
435 std::shared_ptr<HapTokenInfoInner> tokenInfo;
436 if (info.dlpType != DLP_COMMON) {
437 HapPolicyParams policyNew;
438 GetPolicyCopied(policy, policyNew);
439 int32_t res = DlpPermissionSetManager::GetInstance().UpdatePermStateWithDlpInfo(
440 info.dlpType, policyNew.permStateList);
441 if (res != RET_SUCCESS) {
442 ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s update dlp permission failed", info.bundleName.c_str());
443 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
444 return RET_FAILED;
445 }
446 tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policyNew);
447 } else {
448 tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policy);
449 }
450 #else
451 std::shared_ptr<HapTokenInfoInner> tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policy);
452 #endif
453 int ret = AddHapTokenInfo(tokenInfo);
454 if (ret != RET_SUCCESS) {
455 ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s add token info failed", info.bundleName.c_str());
456 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
457 return RET_FAILED;
458 }
459 PermissionManager::GetInstance().AddDefPermissions(policy.permList, tokenId, false);
460 ACCESSTOKEN_LOG_INFO(LABEL, "create hap token %{public}u bundleName %{public}s user %{public}d inst %{public}d ok",
461 tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex());
462 AllocAccessTokenIDEx(info, tokenId, tokenIdEx);
463 RefreshTokenInfoIfNeeded();
464 return RET_SUCCESS;
465 }
466
AllocAccessTokenIDEx(const HapInfoParams & info,AccessTokenID tokenId,AccessTokenIDEx & tokenIdEx)467 int AccessTokenInfoManager::AllocAccessTokenIDEx(
468 const HapInfoParams& info, AccessTokenID tokenId, AccessTokenIDEx& tokenIdEx)
469 {
470 tokenIdEx.tokenIdExStruct.tokenID = tokenId;
471 if (info.isSystemApp) {
472 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
473 }
474 return RET_SUCCESS;
475 }
476
CheckNativeDCap(AccessTokenID tokenID,const std::string & dcap)477 int AccessTokenInfoManager::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap)
478 {
479 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenID);
480 if (infoPtr == nullptr) {
481 ACCESSTOKEN_LOG_ERROR(
482 LABEL, "token %{public}u is invalid.", tokenID);
483 return ERR_TOKENID_NOT_EXIST;
484 }
485
486 std::vector<std::string> dcaps = infoPtr->GetDcap();
487 for (auto iter = dcaps.begin(); iter != dcaps.end(); iter++) {
488 if (*iter == dcap) {
489 return RET_SUCCESS;
490 }
491 }
492 return ERR_CHECK_DCAP_FAIL;
493 }
494
GetHapTokenID(int32_t userID,const std::string & bundleName,int32_t instIndex)495 AccessTokenIDEx AccessTokenInfoManager::GetHapTokenID(int32_t userID, const std::string& bundleName, int32_t instIndex)
496 {
497 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
498 std::string HapUniqueKey = GetHapUniqueStr(userID, bundleName, instIndex);
499 AccessTokenIDEx tokenIdEx = {0};
500 auto iter = hapTokenIdMap_.find(HapUniqueKey);
501 if (iter != hapTokenIdMap_.end()) {
502 AccessTokenID tokenId = iter->second;
503 auto infoIter = hapTokenInfoMap_.find(tokenId);
504 if (infoIter != hapTokenInfoMap_.end()) {
505 if (infoIter->second == nullptr) {
506 ACCESSTOKEN_LOG_ERROR(LABEL, "HapTokenInfoInner is nullptr");
507 return tokenIdEx;
508 }
509 HapTokenInfo info = infoIter->second->GetHapInfoBasic();
510 tokenIdEx.tokenIdExStruct.tokenID = info.tokenID;
511 tokenIdEx.tokenIdExStruct.tokenAttr = info.tokenAttr;
512 }
513 }
514 return tokenIdEx;
515 }
516
TryUpdateExistNativeToken(const std::shared_ptr<NativeTokenInfoInner> & infoPtr)517 bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptr<NativeTokenInfoInner>& infoPtr)
518 {
519 if (infoPtr == nullptr) {
520 ACCESSTOKEN_LOG_WARN(LABEL, "info is null");
521 return false;
522 }
523
524 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
525 AccessTokenID id = infoPtr->GetTokenID();
526 std::string processName = infoPtr->GetProcessName();
527 bool idExist = (nativeTokenInfoMap_.count(id) > 0);
528 bool processExist = (nativeTokenIdMap_.count(processName) > 0);
529 // id is exist, but it is not this process, so neither update nor add.
530 if (idExist && !processExist) {
531 ACCESSTOKEN_LOG_ERROR(
532 LABEL, "token Id is exist, but process name is not exist, can not update.");
533 return true;
534 }
535
536 // this process is exist, but id is not same, perhaps libat lose his data, we need delete old, add new later.
537 if (!idExist && processExist) {
538 AccessTokenID idRemove = nativeTokenIdMap_[processName];
539 nativeTokenIdMap_.erase(processName);
540 if (nativeTokenInfoMap_.count(idRemove) > 0) {
541 nativeTokenInfoMap_.erase(idRemove);
542 }
543 AccessTokenIDManager::GetInstance().ReleaseTokenId(idRemove);
544 return false;
545 }
546
547 if (!idExist && !processExist) {
548 return false;
549 }
550
551 nativeTokenInfoMap_[id] = infoPtr;
552 return true;
553 }
554
ProcessNativeTokenInfos(const std::vector<std::shared_ptr<NativeTokenInfoInner>> & tokenInfos)555 void AccessTokenInfoManager::ProcessNativeTokenInfos(
556 const std::vector<std::shared_ptr<NativeTokenInfoInner>>& tokenInfos)
557 {
558 for (const auto& infoPtr: tokenInfos) {
559 if (infoPtr == nullptr) {
560 ACCESSTOKEN_LOG_WARN(LABEL, "token info from libat is null");
561 continue;
562 }
563 bool isUpdated = TryUpdateExistNativeToken(infoPtr);
564 if (!isUpdated) {
565 ACCESSTOKEN_LOG_INFO(LABEL,
566 "token %{public}u process name %{public}s is new, add to manager!",
567 infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str());
568 AccessTokenID id = infoPtr->GetTokenID();
569 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(id);
570 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, type);
571 if (ret != RET_SUCCESS) {
572 ACCESSTOKEN_LOG_ERROR(LABEL, "token Id register fail");
573 continue;
574 }
575 ret = AddNativeTokenInfo(infoPtr);
576 if (ret != RET_SUCCESS) {
577 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
578 ACCESSTOKEN_LOG_ERROR(LABEL,
579 "token %{public}u process name %{public}s add to manager failed!",
580 infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str());
581 }
582 }
583 }
584 RefreshTokenInfoIfNeeded();
585 }
586
UpdateHapToken(AccessTokenIDEx & tokenIdEx,bool isSystemApp,const std::string & appIDDesc,int32_t apiVersion,const HapPolicyParams & policy)587 int AccessTokenInfoManager::UpdateHapToken(AccessTokenIDEx& tokenIdEx,
588 bool isSystemApp, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy)
589 {
590 AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID;
591 if (!DataValidator::IsAppIDDescValid(appIDDesc)) {
592 ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u parm format error!", tokenID);
593 return AccessTokenError::ERR_PARAM_INVALID;
594 }
595 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
596 if (infoPtr == nullptr) {
597 ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u is null, can not update!", tokenID);
598 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
599 }
600
601 if (infoPtr->IsRemote()) {
602 ACCESSTOKEN_LOG_ERROR(LABEL, "remote hap token %{public}u can not update!", tokenID);
603 return RET_FAILED;
604 }
605 if (isSystemApp) {
606 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
607 } else {
608 tokenIdEx.tokenIdExStruct.tokenAttr &= ~SYSTEM_APP_FLAG;
609 }
610 {
611 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
612 infoPtr->Update(appIDDesc, apiVersion, policy, isSystemApp);
613 ACCESSTOKEN_LOG_INFO(LABEL,
614 "token %{public}u bundle name %{public}s user %{public}d inst %{public}d tokenAttr %{public}d update ok!",
615 tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex(),
616 infoPtr->GetHapInfoBasic().tokenAttr);
617 }
618 PermissionManager::GetInstance().AddDefPermissions(policy.permList, tokenID, true);
619 #ifdef TOKEN_SYNC_ENABLE
620 TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID);
621 #endif
622 RefreshTokenInfoIfNeeded();
623 return RET_SUCCESS;
624 }
625
626 #ifdef TOKEN_SYNC_ENABLE
GetHapTokenSync(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)627 int AccessTokenInfoManager::GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync)
628 {
629 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
630 if (infoPtr == nullptr || infoPtr->IsRemote()) {
631 ACCESSTOKEN_LOG_ERROR(
632 LABEL, "token %{public}u is invalid.", tokenID);
633 return RET_FAILED;
634 }
635 hapSync.baseInfo = infoPtr->GetHapInfoBasic();
636 std::shared_ptr<PermissionPolicySet> permSetPtr = infoPtr->GetHapInfoPermissionPolicySet();
637 if (permSetPtr == nullptr) {
638 ACCESSTOKEN_LOG_ERROR(
639 LABEL, "token %{public}u permSet is invalid.", tokenID);
640 return RET_FAILED;
641 }
642 permSetPtr->GetPermissionStateList(hapSync.permStateList);
643 return RET_SUCCESS;
644 }
645
GetHapTokenInfoFromRemote(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)646 int AccessTokenInfoManager::GetHapTokenInfoFromRemote(AccessTokenID tokenID,
647 HapTokenInfoForSync& hapSync)
648 {
649 int ret = GetHapTokenSync(tokenID, hapSync);
650 TokenModifyNotifier::GetInstance().AddHapTokenObservation(tokenID);
651 return ret;
652 }
653
GetAllNativeTokenInfo(std::vector<NativeTokenInfoForSync> & nativeTokenInfosRes)654 void AccessTokenInfoManager::GetAllNativeTokenInfo(
655 std::vector<NativeTokenInfoForSync>& nativeTokenInfosRes)
656 {
657 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
658 for (const auto& nativeTokenInner : nativeTokenInfoMap_) {
659 std::shared_ptr<NativeTokenInfoInner> nativeTokenInnerPtr = nativeTokenInner.second;
660 if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote()
661 || nativeTokenInnerPtr->GetDcap().empty()) {
662 continue;
663 }
664 NativeTokenInfoForSync token;
665 nativeTokenInnerPtr->TranslateToNativeTokenInfo(token.baseInfo);
666
667 std::shared_ptr<PermissionPolicySet> permSetPtr =
668 nativeTokenInnerPtr->GetNativeInfoPermissionPolicySet();
669 if (permSetPtr == nullptr) {
670 ACCESSTOKEN_LOG_ERROR(
671 LABEL, "token %{public}u permSet is invalid.", token.baseInfo.tokenID);
672 return;
673 }
674 permSetPtr->GetPermissionStateList(token.permStateList);
675
676 nativeTokenInfosRes.emplace_back(token);
677 }
678 return;
679 }
680
UpdateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)681 int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
682 {
683 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(mapID);
684 if (infoPtr == nullptr || !infoPtr->IsRemote()) {
685 ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u is null or not remote, can not update!", mapID);
686 return RET_FAILED;
687 }
688
689 std::shared_ptr<PermissionPolicySet> newPermPolicySet =
690 PermissionPolicySet::BuildPermissionPolicySet(mapID, hapSync.permStateList);
691
692 {
693 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
694 infoPtr->SetTokenBaseInfo(hapSync.baseInfo);
695 infoPtr->SetPermissionPolicySet(newPermPolicySet);
696 }
697 return RET_SUCCESS;
698 }
699
CreateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)700 int AccessTokenInfoManager::CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
701 {
702 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>(mapID,
703 hapSync.baseInfo, hapSync.permStateList);
704 hap->SetRemote(true);
705
706 int ret = AddHapTokenInfo(hap);
707 if (ret != RET_SUCCESS) {
708 ACCESSTOKEN_LOG_ERROR(LABEL, "add local token failed.");
709 return RET_FAILED;
710 }
711
712 return RET_SUCCESS;
713 }
714
IsRemoteHapTokenValid(const std::string & deviceID,const HapTokenInfoForSync & hapSync)715 bool AccessTokenInfoManager::IsRemoteHapTokenValid(const std::string& deviceID, const HapTokenInfoForSync& hapSync)
716 {
717 std::string errReason;
718 if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsDeviceIdValid(hapSync.baseInfo.deviceID)) {
719 errReason = "respond deviceID error";
720 } else if (!DataValidator::IsUserIdValid(hapSync.baseInfo.userID)) {
721 errReason = "respond userID error";
722 } else if (!DataValidator::IsBundleNameValid(hapSync.baseInfo.bundleName)) {
723 errReason = "respond bundleName error";
724 } else if (!DataValidator::IsAplNumValid(hapSync.baseInfo.apl)) {
725 errReason = "respond apl error";
726 } else if (!DataValidator::IsTokenIDValid(hapSync.baseInfo.tokenID)) {
727 errReason = "respond tokenID error";
728 } else if (!DataValidator::IsAppIDDescValid(hapSync.baseInfo.appID)) {
729 errReason = "respond appID error";
730 } else if (!DataValidator::IsDlpTypeValid(hapSync.baseInfo.dlpType)) {
731 errReason = "respond dlpType error";
732 } else if (hapSync.baseInfo.ver != DEFAULT_TOKEN_VERSION) {
733 errReason = "respond version error";
734 } else if (AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(hapSync.baseInfo.tokenID) != TOKEN_HAP) {
735 errReason = "respond token type error";
736 } else {
737 return true;
738 }
739
740 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
741 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_RESPONSE_ERROR,
742 "REMOTE_ID", ConstantCommon::EncryptDevId(deviceID), "ERROR_REASON", errReason);
743 return false;
744 }
745
SetRemoteHapTokenInfo(const std::string & deviceID,HapTokenInfoForSync & hapSync)746 int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync)
747 {
748 if (!IsRemoteHapTokenValid(deviceID, hapSync)) {
749 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
750 return RET_FAILED;
751 }
752
753 AccessTokenID remoteID = hapSync.baseInfo.tokenID;
754 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID);
755 if (mapID != 0) {
756 ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u update exist remote hap token %{public}u.",
757 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
758 // update remote token mapping id
759 hapSync.baseInfo.tokenID = mapID;
760 hapSync.baseInfo.deviceID = deviceID;
761 return UpdateRemoteHapTokenInfo(mapID, hapSync);
762 }
763
764 mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID);
765 if (mapID == 0) {
766 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u map failed.",
767 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID);
768 return RET_FAILED;
769 }
770
771 // update remote token mapping id
772 hapSync.baseInfo.tokenID = mapID;
773 hapSync.baseInfo.deviceID = deviceID;
774
775 if (CreateRemoteHapTokenInfo(mapID, hapSync) == RET_FAILED) {
776 AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID);
777 ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u failed.",
778 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
779 return RET_FAILED;
780 }
781 ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u success.",
782 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
783 return RET_SUCCESS;
784 }
785
SetRemoteNativeTokenInfo(const std::string & deviceID,std::vector<NativeTokenInfoForSync> & nativeTokenInfoList)786 int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID,
787 std::vector<NativeTokenInfoForSync>& nativeTokenInfoList)
788 {
789 if (!DataValidator::IsDeviceIdValid(deviceID)) {
790 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
791 return AccessTokenError::ERR_PARAM_INVALID;
792 }
793
794 for (NativeTokenInfoForSync& nativeToken : nativeTokenInfoList) {
795 AccessTokenID remoteID = nativeToken.baseInfo.tokenID;
796 auto encryptDevId = ConstantCommon::EncryptDevId(deviceID);
797 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(remoteID);
798 if (!DataValidator::IsAplNumValid(nativeToken.baseInfo.apl) ||
799 nativeToken.baseInfo.ver != DEFAULT_TOKEN_VERSION ||
800 !DataValidator::IsProcessNameValid(nativeToken.baseInfo.processName) ||
801 nativeToken.baseInfo.dcap.empty() ||
802 (type != TOKEN_NATIVE && type != TOKEN_SHELL)) {
803 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u is invalid.",
804 encryptDevId.c_str(), remoteID);
805 continue;
806 }
807
808 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID);
809 if (mapID != 0) {
810 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u has maped, no need update it.",
811 encryptDevId.c_str(), remoteID);
812 continue;
813 }
814
815 mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID);
816 if (mapID == 0) {
817 AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID);
818 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u map failed.",
819 encryptDevId.c_str(), remoteID);
820 continue;
821 }
822 nativeToken.baseInfo.tokenID = mapID;
823 ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u.",
824 encryptDevId.c_str(), remoteID, mapID);
825
826 std::shared_ptr<NativeTokenInfoInner> nativePtr =
827 std::make_shared<NativeTokenInfoInner>(nativeToken.baseInfo, nativeToken.permStateList);
828 nativePtr->SetRemote(true);
829 int ret = AddNativeTokenInfo(nativePtr);
830 if (ret != RET_SUCCESS) {
831 AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID);
832 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u add local token failed.",
833 encryptDevId.c_str(), remoteID);
834 continue;
835 }
836 ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map token %{public}u add success.",
837 encryptDevId.c_str(), remoteID, mapID);
838 }
839
840 return RET_SUCCESS;
841 }
842
DeleteRemoteToken(const std::string & deviceID,AccessTokenID tokenID)843 int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID)
844 {
845 if (!DataValidator::IsDeviceIdValid(deviceID)) {
846 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
847 return AccessTokenError::ERR_PARAM_INVALID;
848 }
849 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
850 if (mapID == 0) {
851 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u is not mapped",
852 ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID);
853 return RET_FAILED;
854 }
855
856 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(mapID);
857 if (type == TOKEN_HAP) {
858 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
859 if (hapTokenInfoMap_.count(mapID) == 0) {
860 ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u no exist.", mapID);
861 return RET_FAILED;
862 }
863 hapTokenInfoMap_.erase(mapID);
864 } else if ((type == TOKEN_NATIVE) || (type == TOKEN_SHELL)) {
865 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
866 if (nativeTokenInfoMap_.count(mapID) == 0) {
867 ACCESSTOKEN_LOG_ERROR(
868 LABEL, "native token %{public}u is null.", mapID);
869 return RET_FAILED;
870 }
871 nativeTokenInfoMap_.erase(mapID);
872 } else {
873 ACCESSTOKEN_LOG_ERROR(LABEL, "mapping tokenId %{public}u type is unknown", mapID);
874 }
875
876 return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID);
877 }
878
GetRemoteNativeTokenID(const std::string & deviceID,AccessTokenID tokenID)879 AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID)
880 {
881 if ((!DataValidator::IsDeviceIdValid(deviceID)) || (tokenID == 0) ||
882 ((AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) &&
883 (AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_SHELL))) {
884 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
885 return 0;
886 }
887 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
888 }
889
DeleteRemoteDeviceTokens(const std::string & deviceID)890 int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID)
891 {
892 if (!DataValidator::IsDeviceIdValid(deviceID)) {
893 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
894 return AccessTokenError::ERR_PARAM_INVALID;
895 }
896 std::vector<AccessTokenID> remoteTokens;
897 int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens);
898 if (ret != RET_SUCCESS) {
899 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s have no remote token",
900 ConstantCommon::EncryptDevId(deviceID).c_str());
901 return ret;
902 }
903 for (AccessTokenID remoteID : remoteTokens) {
904 DeleteRemoteToken(deviceID, remoteID);
905 }
906 return RET_SUCCESS;
907 }
908
GetUdidByNodeId(const std::string & nodeId)909 std::string AccessTokenInfoManager::GetUdidByNodeId(const std::string &nodeId)
910 {
911 uint8_t info[UDID_MAX_LENGTH + 1] = {0};
912
913 int32_t ret = ::GetNodeKeyInfo(
914 ACCESS_TOKEN_PACKAGE_NAME.c_str(), nodeId.c_str(), NodeDeviceInfoKey::NODE_KEY_UDID, info, UDID_MAX_LENGTH);
915 if (ret != RET_SUCCESS) {
916 ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret);
917 return "";
918 }
919 std::string udid(reinterpret_cast<char *>(info));
920 return udid;
921 }
922
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)923 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
924 AccessTokenID remoteTokenID)
925 {
926 if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) {
927 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid",
928 ConstantCommon::EncryptDevId(remoteDeviceID).c_str());
929 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
930 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
931 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", "deviceID error");
932 return 0;
933 }
934 std::string remoteUdid = GetUdidByNodeId(remoteDeviceID);
935 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s remoteUdid", ConstantCommon::EncryptDevId(remoteUdid).c_str());
936 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid,
937 remoteTokenID);
938 if (mapID != 0) {
939 return mapID;
940 }
941 int ret = TokenSyncKit::GetRemoteHapTokenInfo(remoteUdid, remoteTokenID);
942 if (ret != RET_SUCCESS) {
943 ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u sync failed",
944 ConstantCommon::EncryptDevId(remoteUdid).c_str(), remoteTokenID);
945 std::string errorReason = "token sync call error, error number is " + std::to_string(ret);
946 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
947 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
948 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", errorReason);
949 return 0;
950 }
951
952 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, remoteTokenID);
953 }
954 #else
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)955 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
956 AccessTokenID remoteTokenID)
957 {
958 ACCESSTOKEN_LOG_ERROR(LABEL, "tokensync is disable, check dependent components");
959 return 0;
960 }
961 #endif
962
GetInstance()963 AccessTokenInfoManager& AccessTokenInfoManager::GetInstance()
964 {
965 static AccessTokenInfoManager instance;
966 return instance;
967 }
968
StoreAllTokenInfo()969 void AccessTokenInfoManager::StoreAllTokenInfo()
970 {
971 std::vector<GenericValues> hapInfoValues;
972 std::vector<GenericValues> permDefValues;
973 std::vector<GenericValues> permStateValues;
974 std::vector<GenericValues> nativeTokenValues;
975 uint64_t lastestUpdateStamp = 0;
976 {
977 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
978 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
979 if (iter->second != nullptr) {
980 std::shared_ptr<HapTokenInfoInner>& hapInfo = iter->second;
981 hapInfo->StoreHapInfo(hapInfoValues, permStateValues);
982 if (hapInfo->permUpdateTimestamp_ > lastestUpdateStamp) {
983 lastestUpdateStamp = hapInfo->permUpdateTimestamp_;
984 }
985 }
986 }
987 }
988
989 {
990 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
991 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
992 if (iter->second != nullptr) {
993 iter->second->StoreNativeInfo(nativeTokenValues, permStateValues);
994 }
995 }
996 }
997
998 PermissionDefinitionCache::GetInstance().StorePermissionDef(permDefValues);
999
1000 DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_HAP_INFO, hapInfoValues);
1001 DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenValues);
1002 DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefValues);
1003 int res = DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateValues);
1004 PermissionManager::GetInstance().NotifyPermGrantStoreResult((res == 0), lastestUpdateStamp);
1005 }
1006
RefreshTokenInfoIfNeeded()1007 void AccessTokenInfoManager::RefreshTokenInfoIfNeeded()
1008 {
1009 if (tokenDataWorker_.GetCurTaskNum() > 1) {
1010 ACCESSTOKEN_LOG_INFO(LABEL, "has refresh task!");
1011 return;
1012 }
1013
1014 tokenDataWorker_.AddTask([]() {
1015 AccessTokenInfoManager::GetInstance().StoreAllTokenInfo();
1016
1017 // Sleep for one second to avoid frequent refresh of the database.
1018 std::this_thread::sleep_for(std::chrono::seconds(1));
1019 });
1020 }
PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner> & info,AccessTokenID id)1021 void AccessTokenInfoManager::PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner>& info, AccessTokenID id)
1022 {
1023 std::shared_ptr<PermissionPolicySet> policy = info->GetHapInfoPermissionPolicySet();
1024 if (policy == nullptr) {
1025 return;
1026 }
1027
1028 std::vector<std::string> permissionList;
1029 policy->GetDeletedPermissionListToNotify(permissionList);
1030 for (const auto& permissionName : permissionList) {
1031 CallbackManager::GetInstance().ExecuteCallbackAsync(id, permissionName, PermStateChangeType::REVOKED);
1032 PermissionManager::GetInstance().ParamUpdate(permissionName, 0, true);
1033 }
1034 }
1035
GetNativeTokenId(const std::string & processName)1036 AccessTokenID AccessTokenInfoManager::GetNativeTokenId(const std::string& processName)
1037 {
1038 AccessTokenID tokenID = INVALID_TOKENID;
1039 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1040 if (iter->second != nullptr && iter->second->GetProcessName() == processName) {
1041 tokenID = iter->first;
1042 break;
1043 }
1044 }
1045 return tokenID;
1046 }
1047
DumpTokenInfo(AccessTokenID tokenID,std::string & dumpInfo)1048 void AccessTokenInfoManager::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo)
1049 {
1050 ACCESSTOKEN_LOG_INFO(LABEL, "get hapTokenInfo");
1051 if (tokenID != 0) {
1052 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID);
1053 if (type == TOKEN_HAP) {
1054 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
1055 if (infoPtr != nullptr) {
1056 infoPtr->ToString(dumpInfo);
1057 }
1058 } else if (type == TOKEN_NATIVE || type == TOKEN_SHELL) {
1059 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenID);
1060 if (infoPtr != nullptr) {
1061 infoPtr->ToString(dumpInfo);
1062 }
1063 } else {
1064 dumpInfo.append("invalid tokenId");
1065 }
1066 return;
1067 }
1068
1069 Utils::UniqueReadGuard<Utils::RWLock> hapInfoGuard(this->hapTokenInfoLock_);
1070 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
1071 if (iter->second != nullptr) {
1072 iter->second->ToString(dumpInfo);
1073 dumpInfo.append("\n");
1074 }
1075 }
1076
1077 ACCESSTOKEN_LOG_INFO(LABEL, "get nativeTokenInfo");
1078 Utils::UniqueReadGuard<Utils::RWLock> nativeInfoGuard(this->nativeTokenInfoLock_);
1079 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1080 if (iter->second != nullptr) {
1081 iter->second->ToString(dumpInfo);
1082 dumpInfo.append("\n");
1083 }
1084 }
1085 }
1086 } // namespace AccessToken
1087 } // namespace Security
1088 } // namespace OHOS
1089