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