1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "accesstoken_info_manager.h"
17
18 #include <cinttypes>
19 #include <cstdint>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <securec.h>
23 #include "access_token.h"
24 #include "accesstoken_dfx_define.h"
25 #include "accesstoken_id_manager.h"
26 #include "accesstoken_log.h"
27 #include "accesstoken_remote_token_manager.h"
28 #include "access_token_error.h"
29 #include "atm_tools_param_info_parcel.h"
30 #include "callback_manager.h"
31 #include "constant_common.h"
32 #include "data_translator.h"
33 #include "data_validator.h"
34 #ifdef SUPPORT_SANDBOX_APP
35 #include "dlp_permission_set_manager.h"
36 #endif
37 #include "generic_values.h"
38 #include "hap_token_info_inner.h"
39 #include "hisysevent_adapter.h"
40 #include "ipc_skeleton.h"
41 #include "permission_definition_cache.h"
42 #include "permission_manager.h"
43 #include "access_token_db.h"
44 #include "token_field_const.h"
45 #include "token_setproc.h"
46 #ifdef TOKEN_SYNC_ENABLE
47 #include "token_modify_notifier.h"
48 #endif
49
50 namespace OHOS {
51 namespace Security {
52 namespace AccessToken {
53 namespace {
54 std::recursive_mutex g_instanceMutex;
55 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManager"};
56 static const unsigned int SYSTEM_APP_FLAG = 0x0001;
57 #ifdef TOKEN_SYNC_ENABLE
58 static const int MAX_PTHREAD_NAME_LEN = 15; // pthread name max length
59 static const std::string ACCESS_TOKEN_PACKAGE_NAME = "ohos.security.distributed_token_sync";
60 #endif
61 static const std::string DUMP_JSON_PATH = "/data/service/el1/public/access_token/nativetoken.log";
62 }
63
AccessTokenInfoManager()64 AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) {}
65
~AccessTokenInfoManager()66 AccessTokenInfoManager::~AccessTokenInfoManager()
67 {
68 if (!hasInited_) {
69 return;
70 }
71
72 #ifdef TOKEN_SYNC_ENABLE
73 int32_t ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(ACCESS_TOKEN_PACKAGE_NAME);
74 if (ret != ERR_OK) {
75 ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret);
76 }
77 #endif
78
79 this->hasInited_ = false;
80 }
81
Init()82 void AccessTokenInfoManager::Init()
83 {
84 OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->managerLock_);
85 if (hasInited_) {
86 return;
87 }
88
89 ACCESSTOKEN_LOG_INFO(LABEL, "Init begin!");
90 uint32_t hapSize = 0;
91 uint32_t nativeSize = 0;
92 InitHapTokenInfos(hapSize);
93 InitNativeTokenInfos(nativeSize);
94 uint32_t pefDefSize = PermissionDefinitionCache::GetInstance().GetDefPermissionsSize();
95 ReportSysEventServiceStart(getpid(), hapSize, nativeSize, pefDefSize);
96 ACCESSTOKEN_LOG_INFO(LABEL, "InitTokenInfo end, hapSize %{public}d, nativeSize %{public}d, pefDefSize %{public}d.",
97 hapSize, nativeSize, pefDefSize);
98
99 hasInited_ = true;
100 ACCESSTOKEN_LOG_INFO(LABEL, "Init success");
101 }
102
103 #ifdef TOKEN_SYNC_ENABLE
InitDmCallback(void)104 void AccessTokenInfoManager::InitDmCallback(void)
105 {
106 std::function<void()> runner = []() {
107 std::string name = "AtmInfoMgrInit";
108 pthread_setname_np(pthread_self(), name.substr(0, MAX_PTHREAD_NAME_LEN).c_str());
109 std::shared_ptr<AccessTokenDmInitCallback> ptrDmInitCallback = std::make_shared<AccessTokenDmInitCallback>();
110 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(ACCESS_TOKEN_PACKAGE_NAME,
111 ptrDmInitCallback);
112 if (ret != ERR_OK) {
113 ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret);
114 }
115 ACCESSTOKEN_LOG_INFO(LABEL, "device manager part init end");
116 return;
117 };
118 std::thread initThread(runner);
119 initThread.detach();
120 }
121 #endif
122
InitHapTokenInfos(uint32_t & hapSize)123 void AccessTokenInfoManager::InitHapTokenInfos(uint32_t& hapSize)
124 {
125 GenericValues conditionValue;
126 std::vector<GenericValues> hapTokenRes;
127 std::vector<GenericValues> permDefRes;
128 std::vector<GenericValues> permStateRes;
129 int32_t ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, hapTokenRes);
130 if (ret != RET_SUCCESS || hapTokenRes.empty()) {
131 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load hap from db fail.", ret);
132 }
133 ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, conditionValue, permDefRes);
134 if (ret != RET_SUCCESS || permDefRes.empty()) {
135 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load perm def from db fail.", ret);
136 }
137 ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue, permStateRes);
138 if (ret != RET_SUCCESS || permStateRes.empty()) {
139 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR, "Load perm state from db fail.", ret);
140 }
141 for (const GenericValues& tokenValue : hapTokenRes) {
142 AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
143 std::string bundle = tokenValue.GetString(TokenFiledConst::FIELD_BUNDLE_NAME);
144 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP);
145 if (ret != RET_SUCCESS) {
146 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId %{public}u add id failed, error=%{public}d.", tokenId, ret);
147 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR,
148 "RegisterTokenId fail, " + bundle + std::to_string(tokenId), ret);
149 continue;
150 }
151 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>();
152 ret = hap->RestoreHapTokenInfo(tokenId, tokenValue, permStateRes);
153 if (ret != RET_SUCCESS) {
154 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
155 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId %{public}u restore failed.", tokenId);
156 continue;
157 }
158
159 ret = AddHapTokenInfo(hap);
160 if (ret != RET_SUCCESS) {
161 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
162 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId %{public}u add failed.", tokenId);
163 ReportSysEventServiceStartError(INIT_HAP_TOKENINFO_ERROR,
164 "AddHapTokenInfo fail, " + bundle + std::to_string(tokenId), ret);
165 continue;
166 }
167 hapSize++;
168 ACCESSTOKEN_LOG_INFO(LABEL,
169 " Restore hap token %{public}u bundle name %{public}s user %{public}d,"
170 " permSize %{public}d, inst %{public}d ok!",
171 tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetReqPermissionSize(), hap->GetInstIndex());
172 }
173 PermissionDefinitionCache::GetInstance().RestorePermDefInfo(permDefRes);
174 }
175
InitNativeTokenInfos(uint32_t & nativeSize)176 void AccessTokenInfoManager::InitNativeTokenInfos(uint32_t& nativeSize)
177 {
178 GenericValues conditionValue;
179 std::vector<GenericValues> nativeTokenResults;
180 std::vector<GenericValues> permStateRes;
181 int32_t ret = AccessTokenDb::GetInstance().Find(
182 AtmDataType::ACCESSTOKEN_NATIVE_INFO, conditionValue, nativeTokenResults);
183 if (ret != RET_SUCCESS || nativeTokenResults.empty()) {
184 ReportSysEventServiceStartError(INIT_NATIVE_TOKENINFO_ERROR, "Load native from db fail.", ret);
185 }
186 ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue, permStateRes);
187 if (ret != RET_SUCCESS || permStateRes.empty()) {
188 ReportSysEventServiceStartError(INIT_NATIVE_TOKENINFO_ERROR, "Load perm state from db fail.", ret);
189 }
190 for (const GenericValues& nativeTokenValue : nativeTokenResults) {
191 AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(TokenFiledConst::FIELD_TOKEN_ID);
192 std::string process = nativeTokenValue.GetString(TokenFiledConst::FIELD_PROCESS_NAME);
193 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenId);
194 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, type);
195 if (ret != RET_SUCCESS) {
196 ReportSysEventServiceStartError(INIT_NATIVE_TOKENINFO_ERROR,
197 "RegisterTokenId fail, " + process + std::to_string(tokenId), ret);
198 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId %{public}u add failed, error=%{public}d.", tokenId, ret);
199 continue;
200 }
201 std::shared_ptr<NativeTokenInfoInner> native = std::make_shared<NativeTokenInfoInner>();
202
203 ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue, permStateRes);
204 if (ret != RET_SUCCESS) {
205 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
206 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId %{public}u restore failed.", tokenId);
207 continue;
208 }
209
210 ret = AddNativeTokenInfo(native);
211 if (ret != RET_SUCCESS) {
212 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
213 ACCESSTOKEN_LOG_ERROR(LABEL, "Id %{public}u add failed.", tokenId);
214 ReportSysEventServiceStartError(INIT_NATIVE_TOKENINFO_ERROR,
215 "AddNativeTokenInfo fail, " + process + std::to_string(tokenId), ret);
216 continue;
217 }
218 nativeSize++;
219 ACCESSTOKEN_LOG_INFO(LABEL,
220 "restore native token %{public}u process name %{public}s, permSize %{public}d ok!",
221 tokenId, native->GetProcessName().c_str(), native->GetReqPermissionSize());
222 }
223 }
224
GetHapUniqueStr(const int & userID,const std::string & bundleName,const int & instIndex) const225 std::string AccessTokenInfoManager::GetHapUniqueStr(const int& userID,
226 const std::string& bundleName, const int& instIndex) const
227 {
228 return bundleName + "&" + std::to_string(userID) + "&" + std::to_string(instIndex);
229 }
230
GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner> & info) const231 std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr<HapTokenInfoInner>& info) const
232 {
233 if (info == nullptr) {
234 return std::string("");
235 }
236 return GetHapUniqueStr(info->GetUserID(), info->GetBundleName(), info->GetInstIndex());
237 }
238
AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner> & info)239 int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr<HapTokenInfoInner>& info)
240 {
241 if (info == nullptr) {
242 ACCESSTOKEN_LOG_ERROR(LABEL, "Token info is null.");
243 return AccessTokenError::ERR_PARAM_INVALID;
244 }
245 AccessTokenID id = info->GetTokenID();
246 AccessTokenID idRemoved = INVALID_TOKENID;
247 {
248 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
249 if (hapTokenInfoMap_.count(id) > 0) {
250 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u info has exist.", id);
251 return AccessTokenError::ERR_TOKENID_HAS_EXISTED;
252 }
253
254 if (!info->IsRemote()) {
255 std::string hapUniqueKey = GetHapUniqueStr(info);
256 auto iter = hapTokenIdMap_.find(hapUniqueKey);
257 if (iter != hapTokenIdMap_.end()) {
258 ACCESSTOKEN_LOG_INFO(LABEL, "Token %{public}u Unique info has exist, update.", id);
259 idRemoved = iter->second;
260 }
261 hapTokenIdMap_[hapUniqueKey] = id;
262 }
263 hapTokenInfoMap_[id] = info;
264 }
265 if (idRemoved != INVALID_TOKENID) {
266 RemoveHapTokenInfo(idRemoved);
267 }
268 // add hap to kernel
269 std::shared_ptr<PermissionPolicySet> policySet = info->GetHapInfoPermissionPolicySet();
270 PermissionManager::GetInstance().AddPermToKernel(id, policySet);
271
272 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "ADD_HAP", HiviewDFX::HiSysEvent::EventType::STATISTIC,
273 "TOKENID", info->GetTokenID(), "USERID", info->GetUserID(), "BUNDLENAME", info->GetBundleName(),
274 "INSTINDEX", info->GetInstIndex());
275
276 return RET_SUCCESS;
277 }
278
AddNativeTokenInfo(const std::shared_ptr<NativeTokenInfoInner> & info)279 int AccessTokenInfoManager::AddNativeTokenInfo(const std::shared_ptr<NativeTokenInfoInner>& info)
280 {
281 if (info == nullptr) {
282 ACCESSTOKEN_LOG_ERROR(LABEL, "Token info is null.");
283 return AccessTokenError::ERR_PARAM_INVALID;
284 }
285
286 AccessTokenID id = info->GetTokenID();
287 std::string processName = info->GetProcessName();
288 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
289 if (nativeTokenInfoMap_.count(id) > 0) {
290 ACCESSTOKEN_LOG_ERROR(
291 LABEL, "Token %{public}u has exist.", id);
292 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
293 }
294 if (!info->IsRemote()) {
295 if (nativeTokenIdMap_.count(processName) > 0) {
296 ACCESSTOKEN_LOG_ERROR(
297 LABEL, "Token %{public}u process name %{public}s has exist.", id, processName.c_str());
298 return AccessTokenError::ERR_PROCESS_NOT_EXIST;
299 }
300 nativeTokenIdMap_[processName] = id;
301 }
302
303 ACCESSTOKEN_LOG_DEBUG(LABEL, "Token info is added %{public}u.", id);
304 nativeTokenInfoMap_[id] = info;
305
306 // add native to kernel
307 std::shared_ptr<PermissionPolicySet> policySet = info->GetNativeInfoPermissionPolicySet();
308 PermissionManager::GetInstance().AddPermToKernel(id, policySet);
309
310 return RET_SUCCESS;
311 }
312
GetHapTokenInfoInner(AccessTokenID id)313 std::shared_ptr<HapTokenInfoInner> AccessTokenInfoManager::GetHapTokenInfoInner(AccessTokenID id)
314 {
315 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
316 auto iter = hapTokenInfoMap_.find(id);
317 if (iter != hapTokenInfoMap_.end()) {
318 return iter->second;
319 }
320 GenericValues conditionValue;
321 if (PermissionDefinitionCache::GetInstance().IsHapPermissionDefEmpty()) {
322 std::vector<GenericValues> permDefRes;
323 AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, conditionValue, permDefRes);
324 PermissionDefinitionCache::GetInstance().RestorePermDefInfo(permDefRes); // restore all permission definition
325 ACCESSTOKEN_LOG_INFO(LABEL, "Restore perm def size: %{public}zu, mapSize: %{public}zu.",
326 permDefRes.size(), hapTokenInfoMap_.size());
327 }
328
329 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(id));
330 std::vector<GenericValues> hapTokenResults;
331 int32_t ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_HAP_INFO, conditionValue, hapTokenResults);
332 if (ret != RET_SUCCESS || hapTokenResults.empty()) {
333 ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to find Id(%{public}u) from hap_token_table, err: %{public}d, "
334 "hapSize: %{public}zu, mapSize: %{public}zu.", id, ret, hapTokenResults.size(), hapTokenInfoMap_.size());
335 return nullptr;
336 }
337 std::vector<GenericValues> permStateRes;
338 ret = AccessTokenDb::GetInstance().Find(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue, permStateRes);
339 if (ret != RET_SUCCESS) {
340 ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to find Id(%{public}u) from perm_state_table, err: %{public}d, "
341 "mapSize: %{public}zu.", id, ret, hapTokenInfoMap_.size());
342 return nullptr;
343 }
344
345 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>();
346 ret = hap->RestoreHapTokenInfo(id, hapTokenResults[0], permStateRes);
347 if (ret != RET_SUCCESS) {
348 ACCESSTOKEN_LOG_ERROR(LABEL, "Id %{public}u restore failed, err: %{public}d, mapSize: %{public}zu.",
349 id, ret, hapTokenInfoMap_.size());
350 return nullptr;
351 }
352 AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_HAP);
353 hapTokenIdMap_[GetHapUniqueStr(hap)] = id;
354 hapTokenInfoMap_[id] = hap;
355 std::shared_ptr<PermissionPolicySet> policySet = hap->GetHapInfoPermissionPolicySet();
356 PermissionManager::GetInstance().AddPermToKernel(id, policySet);
357 ACCESSTOKEN_LOG_INFO(LABEL, " Token %{public}u is not found in map(mapSize: %{public}zu), begin load from DB,"
358 " restore bundle %{public}s user %{public}d, idx %{public}d, permSize %{public}d.", id, hapTokenInfoMap_.size(),
359 hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex(), hap->GetReqPermissionSize());
360 return hap;
361 }
362
GetHapTokenDlpType(AccessTokenID id)363 int32_t AccessTokenInfoManager::GetHapTokenDlpType(AccessTokenID id)
364 {
365 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
366 auto iter = hapTokenInfoMap_.find(id);
367 if ((iter != hapTokenInfoMap_.end()) && (iter->second != nullptr)) {
368 return iter->second->GetDlpType();
369 }
370 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u is invalid, mapSize: %{public}zu.", id, hapTokenInfoMap_.size());
371 return BUTT_DLP_TYPE;
372 }
373
IsTokenIdExist(AccessTokenID id)374 bool AccessTokenInfoManager::IsTokenIdExist(AccessTokenID id)
375 {
376 {
377 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
378 if (hapTokenInfoMap_.count(id) != 0) {
379 return true;
380 }
381 }
382 {
383 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
384 if (nativeTokenInfoMap_.count(id) != 0) {
385 return true;
386 }
387 }
388 return false;
389 }
390
GetHapTokenInfo(AccessTokenID tokenID,HapTokenInfo & info)391 int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& info)
392 {
393 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
394 if (infoPtr == nullptr) {
395 ACCESSTOKEN_LOG_ERROR(
396 LABEL, "Token %{public}u is invalid.", tokenID);
397 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
398 }
399 infoPtr->TranslateToHapTokenInfo(info);
400 return RET_SUCCESS;
401 }
402
GetHapPermissionPolicySet(AccessTokenID id)403 std::shared_ptr<PermissionPolicySet> AccessTokenInfoManager::GetHapPermissionPolicySet(AccessTokenID id)
404 {
405 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(id);
406 if (infoPtr == nullptr) {
407 ACCESSTOKEN_LOG_ERROR(
408 LABEL, "Token %{public}u is invalid.", id);
409 return nullptr;
410 }
411 return infoPtr->GetHapInfoPermissionPolicySet();
412 }
413
GetNativeTokenInfoInner(AccessTokenID id)414 std::shared_ptr<NativeTokenInfoInner> AccessTokenInfoManager::GetNativeTokenInfoInner(AccessTokenID id)
415 {
416 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
417 auto iter = nativeTokenInfoMap_.find(id);
418 if (iter != nativeTokenInfoMap_.end()) {
419 return iter->second;
420 }
421
422 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u is invalid.", id);
423 return nullptr;
424 }
425
GetNativeTokenInfo(AccessTokenID tokenID,NativeTokenInfo & infoParcel)426 int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& infoParcel)
427 {
428 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenID);
429 if (infoPtr == nullptr) {
430 ACCESSTOKEN_LOG_ERROR(
431 LABEL, "Token %{public}u is invalid.", tokenID);
432 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
433 }
434
435 infoPtr->TranslateToNativeTokenInfo(infoParcel);
436 return RET_SUCCESS;
437 }
438
GetNativePermissionPolicySet(AccessTokenID id)439 std::shared_ptr<PermissionPolicySet> AccessTokenInfoManager::GetNativePermissionPolicySet(AccessTokenID id)
440 {
441 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(id);
442 if (infoPtr == nullptr) {
443 ACCESSTOKEN_LOG_ERROR(
444 LABEL, "Token %{public}u is invalid.", id);
445 return nullptr;
446 }
447 return infoPtr->GetNativeInfoPermissionPolicySet();
448 }
449
RemoveHapTokenInfo(AccessTokenID id)450 int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id)
451 {
452 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
453 if (type != TOKEN_HAP) {
454 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u is not hap.", id);
455 return ERR_PARAM_INVALID;
456 }
457 std::shared_ptr<HapTokenInfoInner> info;
458 // make sure that RemoveDefPermissions is called outside of the lock to avoid deadlocks.
459 PermissionManager::GetInstance().RemoveDefPermissions(id);
460 {
461 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
462 RemoveHapTokenInfoFromDb(id);
463 // remove hap to kernel
464 PermissionManager::GetInstance().RemovePermFromKernel(id);
465 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
466
467 if (hapTokenInfoMap_.count(id) == 0) {
468 ACCESSTOKEN_LOG_ERROR(LABEL, "Hap token %{public}u no exist.", id);
469 return ERR_TOKENID_NOT_EXIST;
470 }
471
472 info = hapTokenInfoMap_[id];
473 if (info == nullptr) {
474 ACCESSTOKEN_LOG_ERROR(LABEL, "Hap token %{public}u is null.", id);
475 return ERR_TOKEN_INVALID;
476 }
477 if (info->IsRemote()) {
478 ACCESSTOKEN_LOG_ERROR(LABEL, "Remote hap token %{public}u can not delete.", id);
479 return ERR_IDENTITY_CHECK_FAILED;
480 }
481 std::string HapUniqueKey = GetHapUniqueStr(info);
482 auto iter = hapTokenIdMap_.find(HapUniqueKey);
483 if ((iter != hapTokenIdMap_.end()) && (iter->second == id)) {
484 hapTokenIdMap_.erase(HapUniqueKey);
485 }
486 hapTokenInfoMap_.erase(id);
487 }
488
489 ACCESSTOKEN_LOG_INFO(LABEL, "Remove hap token %{public}u ok!", id);
490 PermissionStateNotify(info, id);
491 #ifdef TOKEN_SYNC_ENABLE
492 TokenModifyNotifier::GetInstance().NotifyTokenDelete(id);
493 #endif
494
495 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "DEL_HAP", HiviewDFX::HiSysEvent::EventType::STATISTIC,
496 "TOKENID", info->GetTokenID(), "USERID", info->GetUserID(), "BUNDLENAME", info->GetBundleName(),
497 "INSTINDEX", info->GetInstIndex());
498
499 return RET_SUCCESS;
500 }
501
RemoveNativeTokenInfo(AccessTokenID id)502 int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id)
503 {
504 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id);
505 if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) {
506 ACCESSTOKEN_LOG_ERROR(
507 LABEL, "Token %{public}u is not hap.", id);
508 return ERR_PARAM_INVALID;
509 }
510
511 {
512 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
513 if (nativeTokenInfoMap_.count(id) == 0) {
514 ACCESSTOKEN_LOG_ERROR(LABEL, "Native token %{public}u is null.", id);
515 return ERR_TOKENID_NOT_EXIST;
516 }
517
518 std::shared_ptr<NativeTokenInfoInner> info = nativeTokenInfoMap_[id];
519 if (info->IsRemote()) {
520 ACCESSTOKEN_LOG_ERROR(LABEL, "Remote native token %{public}u can not delete.", id);
521 return ERR_TOKEN_INVALID;
522 }
523 std::string processName = nativeTokenInfoMap_[id]->GetProcessName();
524 if (nativeTokenIdMap_.count(processName) != 0) {
525 nativeTokenIdMap_.erase(processName);
526 }
527 nativeTokenInfoMap_.erase(id);
528 }
529 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
530 ACCESSTOKEN_LOG_INFO(LABEL, "Remove native token %{public}u ok!", id);
531
532 if (!RemoveNativeInfoFromDatabase(id)) {
533 return AccessTokenError::ERR_DATABASE_OPERATE_FAILED;
534 }
535
536 // remove native to kernel
537 PermissionManager::GetInstance().RemovePermFromKernel(id);
538 return RET_SUCCESS;
539 }
540
541 #ifdef SUPPORT_SANDBOX_APP
GetPolicyCopied(const HapPolicyParams & policy,HapPolicyParams & policyNew)542 static void GetPolicyCopied(const HapPolicyParams& policy, HapPolicyParams& policyNew)
543 {
544 policyNew.apl = policy.apl;
545 policyNew.domain = policy.domain;
546
547 for (const auto& state : policy.permStateList) {
548 policyNew.permStateList.emplace_back(state);
549 }
550 for (const auto& def : policy.permList) {
551 policyNew.permList.emplace_back(def);
552 }
553 }
554 #endif
555
CheckHapInfoParam(const HapInfoParams & info,const HapPolicyParams & policy)556 int32_t AccessTokenInfoManager::CheckHapInfoParam(const HapInfoParams& info, const HapPolicyParams& policy)
557 {
558 if ((!DataValidator::IsUserIdValid(info.userID)) || (!DataValidator::IsBundleNameValid(info.bundleName)) ||
559 (!DataValidator::IsAppIDDescValid(info.appIDDesc)) || (!DataValidator::IsDomainValid(policy.domain)) ||
560 (!DataValidator::IsDlpTypeValid(info.dlpType)) || (info.isRestore && info.tokenID == INVALID_TOKENID)) {
561 ACCESSTOKEN_LOG_ERROR(LABEL, "Hap token param failed");
562 return AccessTokenError::ERR_PARAM_INVALID;
563 }
564 return ERR_OK;
565 }
566
CreateHapTokenInfo(const HapInfoParams & info,const HapPolicyParams & policy,AccessTokenIDEx & tokenIdEx)567 int AccessTokenInfoManager::CreateHapTokenInfo(
568 const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx)
569 {
570 if (CheckHapInfoParam(info, policy) != ERR_OK) {
571 return AccessTokenError::ERR_PARAM_INVALID;
572 }
573 AccessTokenID tokenId = info.tokenID;
574 if (info.isRestore) {
575 ACCESSTOKEN_LOG_INFO(LABEL, "isRestore is true, tokenId is %{public}u", tokenId);
576 int32_t res = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP);
577 if (res != RET_SUCCESS) {
578 ACCESSTOKEN_LOG_ERROR(LABEL, "Token Id register failed, res is %{public}d", res);
579 return res;
580 }
581 } else {
582 int32_t dlpFlag = (info.dlpType > DLP_COMMON) ? 1 : 0;
583 int32_t cloneFlag = ((dlpFlag == 0) && (info.instIndex) > 0) ? 1 : 0;
584 tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP, dlpFlag, cloneFlag);
585 if (tokenId == 0) {
586 ACCESSTOKEN_LOG_ERROR(LABEL, "Token Id create failed");
587 return ERR_TOKENID_CREATE_FAILED;
588 }
589 }
590 PermissionManager::GetInstance().AddDefPermissions(policy.permList, tokenId, false);
591 #ifdef SUPPORT_SANDBOX_APP
592 std::shared_ptr<HapTokenInfoInner> tokenInfo;
593 HapPolicyParams policyNew = policy;
594 if (info.dlpType != DLP_COMMON) {
595 GetPolicyCopied(policy, policyNew);
596 DlpPermissionSetManager::GetInstance().UpdatePermStateWithDlpInfo(info.dlpType, policyNew.permStateList);
597 }
598 tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policyNew);
599 #else
600 std::shared_ptr<HapTokenInfoInner> tokenInfo = std::make_shared<HapTokenInfoInner>(tokenId, info, policy);
601 #endif
602 int ret = AddHapTokenInfo(tokenInfo);
603 if (ret != RET_SUCCESS) {
604 ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s add token info failed", info.bundleName.c_str());
605 AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId);
606 PermissionManager::GetInstance().RemoveDefPermissions(tokenId);
607 return ret;
608 }
609 ACCESSTOKEN_LOG_INFO(LABEL,
610 "Create hap token %{public}u bundleName %{public}s user %{public}d inst %{public}d isRestore %{public}d ok",
611 tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex(), info.isRestore);
612 AllocAccessTokenIDEx(info, tokenId, tokenIdEx);
613 AddHapTokenInfoToDb(tokenId, tokenInfo);
614 return RET_SUCCESS;
615 }
616
AllocAccessTokenIDEx(const HapInfoParams & info,AccessTokenID tokenId,AccessTokenIDEx & tokenIdEx)617 int AccessTokenInfoManager::AllocAccessTokenIDEx(
618 const HapInfoParams& info, AccessTokenID tokenId, AccessTokenIDEx& tokenIdEx)
619 {
620 tokenIdEx.tokenIdExStruct.tokenID = tokenId;
621 if (info.isSystemApp) {
622 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
623 }
624 return RET_SUCCESS;
625 }
626
CheckNativeDCap(AccessTokenID tokenID,const std::string & dcap)627 int AccessTokenInfoManager::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap)
628 {
629 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenID);
630 if (infoPtr == nullptr) {
631 ACCESSTOKEN_LOG_ERROR(
632 LABEL, "Token %{public}u is invalid.", tokenID);
633 return ERR_TOKENID_NOT_EXIST;
634 }
635
636 std::vector<std::string> dcaps = infoPtr->GetDcap();
637 for (auto iter = dcaps.begin(); iter != dcaps.end(); iter++) {
638 if (*iter == dcap) {
639 return RET_SUCCESS;
640 }
641 }
642 return ERR_CHECK_DCAP_FAIL;
643 }
644
GetHapTokenID(int32_t userID,const std::string & bundleName,int32_t instIndex)645 AccessTokenIDEx AccessTokenInfoManager::GetHapTokenID(int32_t userID, const std::string& bundleName, int32_t instIndex)
646 {
647 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
648 std::string HapUniqueKey = GetHapUniqueStr(userID, bundleName, instIndex);
649 AccessTokenIDEx tokenIdEx = {0};
650 auto iter = hapTokenIdMap_.find(HapUniqueKey);
651 if (iter != hapTokenIdMap_.end()) {
652 AccessTokenID tokenId = iter->second;
653 auto infoIter = hapTokenInfoMap_.find(tokenId);
654 if (infoIter != hapTokenInfoMap_.end()) {
655 if (infoIter->second == nullptr) {
656 ACCESSTOKEN_LOG_ERROR(LABEL, "HapTokenInfoInner is nullptr");
657 return tokenIdEx;
658 }
659 HapTokenInfo info = infoIter->second->GetHapInfoBasic();
660 tokenIdEx.tokenIdExStruct.tokenID = info.tokenID;
661 tokenIdEx.tokenIdExStruct.tokenAttr = info.tokenAttr;
662 }
663 }
664 return tokenIdEx;
665 }
666
TryUpdateExistNativeToken(const std::shared_ptr<NativeTokenInfoInner> & infoPtr)667 bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptr<NativeTokenInfoInner>& infoPtr)
668 {
669 if (infoPtr == nullptr) {
670 ACCESSTOKEN_LOG_WARN(LABEL, "Info is null.");
671 return false;
672 }
673
674 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
675 AccessTokenID id = infoPtr->GetTokenID();
676 std::string processName = infoPtr->GetProcessName();
677 bool idExist = (nativeTokenInfoMap_.count(id) > 0);
678 bool processExist = (nativeTokenIdMap_.count(processName) > 0);
679 // id is exist, but it is not this process, so neither update nor add.
680 if (idExist && !processExist) {
681 ACCESSTOKEN_LOG_ERROR(
682 LABEL, "Token Id is exist, but process name is not exist, can not update.");
683 return true;
684 }
685
686 // this process is exist, but id is not same, perhaps libat lose his data, we need delete old, add new later.
687 if (!idExist && processExist) {
688 AccessTokenID idRemove = nativeTokenIdMap_[processName];
689 nativeTokenIdMap_.erase(processName);
690 if (nativeTokenInfoMap_.count(idRemove) > 0) {
691 nativeTokenInfoMap_.erase(idRemove);
692 }
693 AccessTokenIDManager::GetInstance().ReleaseTokenId(idRemove);
694 std::string errMsg = "processName=" + processName + ", newTokenID=" + std::to_string(id) +
695 ", oldTokenID=" + std::to_string(idRemove);
696 ReportSysEventServiceStartError(TOKENID_NOT_EQUAL, errMsg, TOKENID_NOT_EQUAL);
697 return false;
698 }
699
700 if (!idExist && !processExist) {
701 return false;
702 }
703
704 nativeTokenInfoMap_[id] = infoPtr;
705
706 // add native to kernel
707 std::shared_ptr<PermissionPolicySet> policySet = infoPtr->GetNativeInfoPermissionPolicySet();
708 PermissionManager::GetInstance().AddPermToKernel(id, policySet);
709 return true;
710 }
711
ProcessNativeTokenInfos(const std::vector<std::shared_ptr<NativeTokenInfoInner>> & tokenInfos)712 void AccessTokenInfoManager::ProcessNativeTokenInfos(
713 const std::vector<std::shared_ptr<NativeTokenInfoInner>>& tokenInfos)
714 {
715 for (const auto& infoPtr: tokenInfos) {
716 if (infoPtr == nullptr) {
717 ACCESSTOKEN_LOG_WARN(LABEL, "Token info from libat is null");
718 continue;
719 }
720 bool isUpdated = TryUpdateExistNativeToken(infoPtr);
721 if (!isUpdated) {
722 ACCESSTOKEN_LOG_INFO(LABEL,
723 "Token %{public}u process name %{public}s is new, add to manager!",
724 infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str());
725 AccessTokenID id = infoPtr->GetTokenID();
726 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(id);
727 int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, type);
728 if (ret != RET_SUCCESS) {
729 ACCESSTOKEN_LOG_ERROR(LABEL, "Token Id register fail");
730 continue;
731 }
732 ret = AddNativeTokenInfo(infoPtr);
733 if (ret != RET_SUCCESS) {
734 AccessTokenIDManager::GetInstance().ReleaseTokenId(id);
735 ACCESSTOKEN_LOG_ERROR(LABEL,
736 "Token %{public}u process name %{public}s add to manager failed!",
737 infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str());
738 }
739 }
740 }
741 AddAllNativeTokenInfoToDb();
742 }
743
UpdateHapToken(AccessTokenIDEx & tokenIdEx,const UpdateHapInfoParams & info,const std::vector<PermissionStateFull> & permStateList,ATokenAplEnum apl,const std::vector<PermissionDef> & permList)744 int32_t AccessTokenInfoManager::UpdateHapToken(AccessTokenIDEx& tokenIdEx, const UpdateHapInfoParams& info,
745 const std::vector<PermissionStateFull>& permStateList, ATokenAplEnum apl,
746 const std::vector<PermissionDef>& permList)
747 {
748 AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID;
749 if (!DataValidator::IsAppIDDescValid(info.appIDDesc)) {
750 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u parm format error!", tokenID);
751 return AccessTokenError::ERR_PARAM_INVALID;
752 }
753 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
754 if (infoPtr == nullptr) {
755 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u is invalid, can not update!", tokenID);
756 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
757 }
758
759 if (infoPtr->IsRemote()) {
760 ACCESSTOKEN_LOG_ERROR(LABEL, "Remote hap token %{public}u can not update!", tokenID);
761 return ERR_IDENTITY_CHECK_FAILED;
762 }
763 if (info.isSystemApp) {
764 tokenIdEx.tokenIdExStruct.tokenAttr |= SYSTEM_APP_FLAG;
765 } else {
766 tokenIdEx.tokenIdExStruct.tokenAttr &= ~SYSTEM_APP_FLAG;
767 }
768 {
769 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
770 infoPtr->Update(info, permStateList, apl);
771 ACCESSTOKEN_LOG_INFO(LABEL,
772 "Token %{public}u bundle name %{public}s user %{public}d inst %{public}d tokenAttr %{public}d update ok!",
773 tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex(),
774 infoPtr->GetHapInfoBasic().tokenAttr);
775 }
776 PermissionManager::GetInstance().AddDefPermissions(permList, tokenID, true);
777 #ifdef TOKEN_SYNC_ENABLE
778 TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID);
779 #endif
780 // update hap to kernel
781 std::shared_ptr<PermissionPolicySet> policySet = infoPtr->GetHapInfoPermissionPolicySet();
782 PermissionManager::GetInstance().AddPermToKernel(tokenID, policySet);
783 return ModifyHapTokenInfoFromDb(tokenID, infoPtr);
784 }
785
786 #ifdef TOKEN_SYNC_ENABLE
GetHapTokenSync(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)787 int AccessTokenInfoManager::GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync)
788 {
789 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenID);
790 if (infoPtr == nullptr || infoPtr->IsRemote()) {
791 ACCESSTOKEN_LOG_ERROR(
792 LABEL, "Token %{public}u is invalid.", tokenID);
793 return ERR_IDENTITY_CHECK_FAILED;
794 }
795 hapSync.baseInfo = infoPtr->GetHapInfoBasic();
796 std::shared_ptr<PermissionPolicySet> permSetPtr = infoPtr->GetHapInfoPermissionPolicySet();
797 if (permSetPtr == nullptr) {
798 ACCESSTOKEN_LOG_ERROR(
799 LABEL, "Token %{public}u permSet is invalid.", tokenID);
800 return ERR_TOKEN_INVALID;
801 }
802 permSetPtr->GetPermissionStateList(hapSync.permStateList);
803 return RET_SUCCESS;
804 }
805
GetHapTokenInfoFromRemote(AccessTokenID tokenID,HapTokenInfoForSync & hapSync)806 int AccessTokenInfoManager::GetHapTokenInfoFromRemote(AccessTokenID tokenID,
807 HapTokenInfoForSync& hapSync)
808 {
809 int ret = GetHapTokenSync(tokenID, hapSync);
810 TokenModifyNotifier::GetInstance().AddHapTokenObservation(tokenID);
811 return ret;
812 }
813
UpdateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)814 int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
815 {
816 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(mapID);
817 if (infoPtr == nullptr || !infoPtr->IsRemote()) {
818 ACCESSTOKEN_LOG_INFO(LABEL, "Token %{public}u is null or not remote, can not update!", mapID);
819 return ERR_IDENTITY_CHECK_FAILED;
820 }
821
822 std::shared_ptr<PermissionPolicySet> newPermPolicySet =
823 PermissionPolicySet::BuildPolicySetWithoutDefCheck(mapID, hapSync.permStateList);
824
825 {
826 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
827 infoPtr->SetTokenBaseInfo(hapSync.baseInfo);
828 infoPtr->SetPermissionPolicySet(newPermPolicySet);
829 }
830 // update remote hap to kernel
831 PermissionManager::GetInstance().AddPermToKernel(mapID, newPermPolicySet);
832 return RET_SUCCESS;
833 }
834
CreateRemoteHapTokenInfo(AccessTokenID mapID,HapTokenInfoForSync & hapSync)835 int AccessTokenInfoManager::CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync)
836 {
837 std::shared_ptr<HapTokenInfoInner> hap = std::make_shared<HapTokenInfoInner>(mapID, hapSync);
838 hap->SetRemote(true);
839
840 int ret = AddHapTokenInfo(hap);
841 if (ret != RET_SUCCESS) {
842 ACCESSTOKEN_LOG_ERROR(LABEL, "Add local token failed.");
843 return ret;
844 }
845
846 return RET_SUCCESS;
847 }
848
IsRemoteHapTokenValid(const std::string & deviceID,const HapTokenInfoForSync & hapSync)849 bool AccessTokenInfoManager::IsRemoteHapTokenValid(const std::string& deviceID, const HapTokenInfoForSync& hapSync)
850 {
851 std::string errReason;
852 if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsDeviceIdValid(hapSync.baseInfo.deviceID)) {
853 errReason = "respond deviceID error";
854 } else if (!DataValidator::IsUserIdValid(hapSync.baseInfo.userID)) {
855 errReason = "respond userID error";
856 } else if (!DataValidator::IsBundleNameValid(hapSync.baseInfo.bundleName)) {
857 errReason = "respond bundleName error";
858 } else if (!DataValidator::IsAplNumValid(hapSync.baseInfo.apl)) {
859 errReason = "respond apl error";
860 } else if (!DataValidator::IsTokenIDValid(hapSync.baseInfo.tokenID)) {
861 errReason = "respond tokenID error";
862 } else if (!DataValidator::IsAppIDDescValid(hapSync.baseInfo.appID)) {
863 errReason = "respond appID error";
864 } else if (!DataValidator::IsDlpTypeValid(hapSync.baseInfo.dlpType)) {
865 errReason = "respond dlpType error";
866 } else if (hapSync.baseInfo.ver != DEFAULT_TOKEN_VERSION) {
867 errReason = "respond version error";
868 } else if (AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(hapSync.baseInfo.tokenID) != TOKEN_HAP) {
869 errReason = "respond token type error";
870 } else {
871 return true;
872 }
873
874 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
875 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_RESPONSE_ERROR,
876 "REMOTE_ID", ConstantCommon::EncryptDevId(deviceID), "ERROR_REASON", errReason);
877 return false;
878 }
879
SetRemoteHapTokenInfo(const std::string & deviceID,HapTokenInfoForSync & hapSync)880 int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync)
881 {
882 if (!IsRemoteHapTokenValid(deviceID, hapSync)) {
883 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str());
884 return ERR_IDENTITY_CHECK_FAILED;
885 }
886
887 AccessTokenID remoteID = hapSync.baseInfo.tokenID;
888 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID);
889 if (mapID != 0) {
890 ACCESSTOKEN_LOG_INFO(LABEL, "Device %{public}s token %{public}u update exist remote hap token %{public}u.",
891 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
892 // update remote token mapping id
893 hapSync.baseInfo.tokenID = mapID;
894 hapSync.baseInfo.deviceID = deviceID;
895 return UpdateRemoteHapTokenInfo(mapID, hapSync);
896 }
897
898 mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID);
899 if (mapID == 0) {
900 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s token %{public}u map failed.",
901 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID);
902 return ERR_TOKEN_MAP_FAILED;
903 }
904
905 // update remote token mapping id
906 hapSync.baseInfo.tokenID = mapID;
907 hapSync.baseInfo.deviceID = deviceID;
908 int ret = CreateRemoteHapTokenInfo(mapID, hapSync);
909 if (ret != RET_SUCCESS) {
910 AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID);
911 ACCESSTOKEN_LOG_INFO(LABEL, "Device %{public}s token %{public}u map to local token %{public}u failed.",
912 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
913 return ret;
914 }
915 ACCESSTOKEN_LOG_INFO(LABEL, "Device %{public}s token %{public}u map to local token %{public}u success.",
916 ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID);
917 return RET_SUCCESS;
918 }
919
DeleteRemoteToken(const std::string & deviceID,AccessTokenID tokenID)920 int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID)
921 {
922 if (!DataValidator::IsDeviceIdValid(deviceID)) {
923 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s parms invalid.",
924 ConstantCommon::EncryptDevId(deviceID).c_str());
925 return AccessTokenError::ERR_PARAM_INVALID;
926 }
927 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
928 if (mapID == 0) {
929 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s tokenId %{public}u is not mapped.",
930 ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID);
931 return ERR_TOKEN_MAP_FAILED;
932 }
933
934 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(mapID);
935 if (type == TOKEN_HAP) {
936 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
937 if (hapTokenInfoMap_.count(mapID) == 0) {
938 ACCESSTOKEN_LOG_ERROR(LABEL, "Hap token %{public}u no exist.", mapID);
939 return ERR_TOKEN_INVALID;
940 }
941 hapTokenInfoMap_.erase(mapID);
942 } else if ((type == TOKEN_NATIVE) || (type == TOKEN_SHELL)) {
943 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
944 if (nativeTokenInfoMap_.count(mapID) == 0) {
945 ACCESSTOKEN_LOG_ERROR(
946 LABEL, "Native token %{public}u is null.", mapID);
947 return ERR_TOKEN_INVALID;
948 }
949 nativeTokenInfoMap_.erase(mapID);
950 } else {
951 ACCESSTOKEN_LOG_ERROR(LABEL, "Mapping tokenId %{public}u type is unknown.", mapID);
952 }
953
954 return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID);
955 }
956
GetRemoteNativeTokenID(const std::string & deviceID,AccessTokenID tokenID)957 AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID)
958 {
959 if ((!DataValidator::IsDeviceIdValid(deviceID)) || (tokenID == 0) ||
960 ((AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) &&
961 (AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_SHELL))) {
962 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s parms invalid.",
963 ConstantCommon::EncryptDevId(deviceID).c_str());
964 return 0;
965 }
966 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID);
967 }
968
DeleteRemoteDeviceTokens(const std::string & deviceID)969 int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID)
970 {
971 if (!DataValidator::IsDeviceIdValid(deviceID)) {
972 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s parms invalid.",
973 ConstantCommon::EncryptDevId(deviceID).c_str());
974 return AccessTokenError::ERR_PARAM_INVALID;
975 }
976 std::vector<AccessTokenID> remoteTokens;
977 int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens);
978 if (ret != RET_SUCCESS) {
979 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s have no remote token.",
980 ConstantCommon::EncryptDevId(deviceID).c_str());
981 return ret;
982 }
983 for (AccessTokenID remoteID : remoteTokens) {
984 DeleteRemoteToken(deviceID, remoteID);
985 }
986 return RET_SUCCESS;
987 }
988
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)989 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
990 AccessTokenID remoteTokenID)
991 {
992 if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) {
993 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s parms invalid.",
994 ConstantCommon::EncryptDevId(remoteDeviceID).c_str());
995 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
996 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
997 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", "deviceID error");
998 return 0;
999 }
1000 uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
1001 SetFirstCallerTokenID(fullTokenId);
1002 ACCESSTOKEN_LOG_INFO(LABEL, "Set first caller %{public}" PRIu64 ".", fullTokenId);
1003
1004 std::string remoteUdid;
1005 DistributedHardware::DeviceManager::GetInstance().GetUdidByNetworkId(ACCESS_TOKEN_PACKAGE_NAME, remoteDeviceID,
1006 remoteUdid);
1007 ACCESSTOKEN_LOG_INFO(LABEL, "Device %{public}s remoteUdid.", ConstantCommon::EncryptDevId(remoteUdid).c_str());
1008 AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid,
1009 remoteTokenID);
1010 if (mapID != 0) {
1011 return mapID;
1012 }
1013 int ret = TokenModifyNotifier::GetInstance().GetRemoteHapTokenInfo(remoteUdid, remoteTokenID);
1014 if (ret != RET_SUCCESS) {
1015 ACCESSTOKEN_LOG_ERROR(LABEL, "Device %{public}s token %{public}u sync failed",
1016 ConstantCommon::EncryptDevId(remoteUdid).c_str(), remoteTokenID);
1017 std::string errorReason = "token sync call error, error number is " + std::to_string(ret);
1018 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "PERMISSION_SYNC",
1019 HiviewDFX::HiSysEvent::EventType::FAULT, "CODE", TOKEN_SYNC_CALL_ERROR,
1020 "REMOTE_ID", ConstantCommon::EncryptDevId(remoteDeviceID), "ERROR_REASON", errorReason);
1021 return 0;
1022 }
1023
1024 return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, remoteTokenID);
1025 }
1026 #else
AllocLocalTokenID(const std::string & remoteDeviceID,AccessTokenID remoteTokenID)1027 AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID,
1028 AccessTokenID remoteTokenID)
1029 {
1030 ACCESSTOKEN_LOG_ERROR(LABEL, "Tokensync is disable, check dependent components");
1031 return 0;
1032 }
1033 #endif
1034
GetInstance()1035 AccessTokenInfoManager& AccessTokenInfoManager::GetInstance()
1036 {
1037 static AccessTokenInfoManager* instance = nullptr;
1038 if (instance == nullptr) {
1039 std::lock_guard<std::recursive_mutex> lock(g_instanceMutex);
1040 if (instance == nullptr) {
1041 instance = new AccessTokenInfoManager();
1042 }
1043 }
1044 return *instance;
1045 }
1046
AddAllNativeTokenInfoToDb(void)1047 int AccessTokenInfoManager::AddAllNativeTokenInfoToDb(void)
1048 {
1049 std::vector<GenericValues> permStateValues;
1050 std::vector<GenericValues> nativeTokenValues;
1051
1052 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1053 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1054 if (iter->second != nullptr) {
1055 iter->second->StoreNativeInfo(nativeTokenValues);
1056 iter->second->StorePermissionPolicy(permStateValues);
1057 }
1058 }
1059 ACCESSTOKEN_LOG_INFO(LABEL, "permStateValues %{public}zu, nativeTokenValues %{public}zu.",
1060 permStateValues.size(), nativeTokenValues.size());
1061 AccessTokenDb::GetInstance().Add(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, permStateValues);
1062 AccessTokenDb::GetInstance().Add(AtmDataType::ACCESSTOKEN_NATIVE_INFO, nativeTokenValues);
1063 return RET_SUCCESS;
1064 }
1065
ModifyHapTokenInfoFromDb(AccessTokenID tokenID,const std::shared_ptr<HapTokenInfoInner> & hapInner)1066 int AccessTokenInfoManager::ModifyHapTokenInfoFromDb(
1067 AccessTokenID tokenID, const std::shared_ptr<HapTokenInfoInner>& hapInner)
1068 {
1069 if (hapInner == nullptr) {
1070 ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u info is null!", tokenID);
1071 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1072 }
1073
1074 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->modifyLock_);
1075 // get new hap token info from cache
1076 std::vector<GenericValues> hapInfoValues;
1077 hapInner->StoreHapInfo(hapInfoValues); // only exsit one if empty something is wrong
1078 if (hapInfoValues.empty()) {
1079 ACCESSTOKEN_LOG_INFO(LABEL, "Hap token info is empty!");
1080 return AccessTokenError::ERR_PARAM_INVALID;
1081 }
1082
1083 // get new permission def from cache if exsits
1084 std::vector<GenericValues> permDefValues;
1085 PermissionDefinitionCache::GetInstance().StorePermissionDef(tokenID, permDefValues);
1086
1087 // get new permission def from cache if exsits
1088 std::vector<GenericValues> permStateValues;
1089 hapInner->StorePermissionPolicy(permStateValues);
1090
1091 return AccessTokenDb::GetInstance().DeleteAndInsertHap(tokenID, hapInfoValues, permDefValues,
1092 permStateValues);
1093 }
1094
ModifyHapPermStateFromDb(AccessTokenID tokenID,const std::string & permission,const std::shared_ptr<HapTokenInfoInner> & hapInfo)1095 int32_t AccessTokenInfoManager::ModifyHapPermStateFromDb(
1096 AccessTokenID tokenID, const std::string& permission, const std::shared_ptr<HapTokenInfoInner>& hapInfo)
1097 {
1098 std::vector<GenericValues> permStateValues;
1099 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->modifyLock_);
1100 if (hapInfo == nullptr) {
1101 ACCESSTOKEN_LOG_INFO(LABEL, "Token %{public}u info is null!", tokenID);
1102 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1103 }
1104 hapInfo->StorePermissionPolicy(permStateValues);
1105
1106 for (size_t i = 0; i < permStateValues.size(); i++) {
1107 if (permStateValues[i].GetString(TokenFiledConst::FIELD_PERMISSION_NAME) != permission) {
1108 continue;
1109 }
1110 GenericValues conditions;
1111 conditions.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1112 conditions.Put(TokenFiledConst::FIELD_PERMISSION_NAME, permission);
1113 AccessTokenDb::GetInstance().Modify(
1114 AtmDataType::ACCESSTOKEN_PERMISSION_STATE, permStateValues[i], conditions);
1115 }
1116 return RET_SUCCESS;
1117 }
1118
AddHapTokenInfoToDb(AccessTokenID tokenID,const std::shared_ptr<HapTokenInfoInner> & hapInfo)1119 int AccessTokenInfoManager::AddHapTokenInfoToDb(
1120 AccessTokenID tokenID, const std::shared_ptr<HapTokenInfoInner>& hapInfo)
1121 {
1122 std::vector<GenericValues> hapInfoValues;
1123 std::vector<GenericValues> permDefValues;
1124 std::vector<GenericValues> permStateValues;
1125 if (hapInfo == nullptr) {
1126 ACCESSTOKEN_LOG_ERROR(LABEL, "Token %{public}u info is null!", tokenID);
1127 return AccessTokenError::ERR_TOKENID_NOT_EXIST;
1128 }
1129 hapInfo->StoreHapInfo(hapInfoValues);
1130 hapInfo->StorePermissionPolicy(permStateValues);
1131
1132 PermissionDefinitionCache::GetInstance().StorePermissionDef(tokenID, permDefValues);
1133 AccessTokenDb::GetInstance().Add(AtmDataType::ACCESSTOKEN_HAP_INFO, hapInfoValues);
1134 AccessTokenDb::GetInstance().Add(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, permStateValues);
1135 AccessTokenDb::GetInstance().Add(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, permDefValues);
1136 return RET_SUCCESS;
1137 }
1138
RemoveHapTokenInfoFromDb(AccessTokenID tokenID)1139 int AccessTokenInfoManager::RemoveHapTokenInfoFromDb(AccessTokenID tokenID)
1140 {
1141 GenericValues values;
1142 values.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1143
1144 AccessTokenDb::GetInstance().Remove(AtmDataType::ACCESSTOKEN_HAP_INFO, values);
1145 AccessTokenDb::GetInstance().Remove(AtmDataType::ACCESSTOKEN_PERMISSION_DEF, values);
1146 AccessTokenDb::GetInstance().Remove(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, values);
1147 return RET_SUCCESS;
1148 }
1149
PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner> & info,AccessTokenID id)1150 void AccessTokenInfoManager::PermissionStateNotify(const std::shared_ptr<HapTokenInfoInner>& info, AccessTokenID id)
1151 {
1152 std::shared_ptr<PermissionPolicySet> policy = info->GetHapInfoPermissionPolicySet();
1153 if (policy == nullptr) {
1154 return;
1155 }
1156
1157 std::vector<std::string> permissionList;
1158 policy->GetDeletedPermissionListToNotify(permissionList);
1159 if (permissionList.size() != 0) {
1160 PermissionManager::GetInstance().ParamUpdate(permissionList[0], 0, true);
1161 }
1162 for (const auto& permissionName : permissionList) {
1163 CallbackManager::GetInstance().ExecuteCallbackAsync(
1164 id, permissionName, PermStateChangeType::STATE_CHANGE_REVOKED);
1165 }
1166 }
1167
GetNativeTokenId(const std::string & processName)1168 AccessTokenID AccessTokenInfoManager::GetNativeTokenId(const std::string& processName)
1169 {
1170 AccessTokenID tokenID = INVALID_TOKENID;
1171 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1172 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1173 if (iter->second != nullptr && iter->second->GetProcessName() == processName) {
1174 tokenID = iter->first;
1175 break;
1176 }
1177 }
1178 return tokenID;
1179 }
1180
DumpHapTokenInfoByTokenId(const AccessTokenID tokenId,std::string & dumpInfo)1181 void AccessTokenInfoManager::DumpHapTokenInfoByTokenId(const AccessTokenID tokenId, std::string& dumpInfo)
1182 {
1183 ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(tokenId);
1184 if (type == TOKEN_HAP) {
1185 std::shared_ptr<HapTokenInfoInner> infoPtr = GetHapTokenInfoInner(tokenId);
1186 if (infoPtr != nullptr) {
1187 infoPtr->ToString(dumpInfo);
1188 }
1189 } else if (type == TOKEN_NATIVE || type == TOKEN_SHELL) {
1190 std::shared_ptr<NativeTokenInfoInner> infoPtr = GetNativeTokenInfoInner(tokenId);
1191 if (infoPtr != nullptr) {
1192 infoPtr->ToString(dumpInfo);
1193 }
1194 } else {
1195 dumpInfo.append("invalid tokenId");
1196 }
1197 }
1198
DumpHapTokenInfoByBundleName(const std::string & bundleName,std::string & dumpInfo)1199 void AccessTokenInfoManager::DumpHapTokenInfoByBundleName(const std::string& bundleName, std::string& dumpInfo)
1200 {
1201 Utils::UniqueReadGuard<Utils::RWLock> hapInfoGuard(this->hapTokenInfoLock_);
1202 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
1203 if (iter->second != nullptr) {
1204 if (bundleName != iter->second->GetBundleName()) {
1205 continue;
1206 }
1207
1208 iter->second->ToString(dumpInfo);
1209 dumpInfo.append("\n");
1210 }
1211 }
1212 }
1213
DumpAllHapTokenInfo(std::string & dumpInfo)1214 void AccessTokenInfoManager::DumpAllHapTokenInfo(std::string& dumpInfo)
1215 {
1216 ACCESSTOKEN_LOG_DEBUG(LABEL, "Get all hap token info.");
1217
1218 Utils::UniqueReadGuard<Utils::RWLock> hapInfoGuard(this->hapTokenInfoLock_);
1219 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) {
1220 if (iter->second != nullptr) {
1221 iter->second->ToString(dumpInfo);
1222 dumpInfo.append("\n");
1223 }
1224 }
1225 }
1226
DumpNativeTokenInfoByProcessName(const std::string & processName,std::string & dumpInfo)1227 void AccessTokenInfoManager::DumpNativeTokenInfoByProcessName(const std::string& processName, std::string& dumpInfo)
1228 {
1229 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1230 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1231 if ((iter->second != nullptr) && (processName == iter->second->GetProcessName())) {
1232 iter->second->ToString(dumpInfo);
1233 dumpInfo.append("\n");
1234 break;
1235 }
1236 }
1237 }
1238
DumpAllNativeTokenInfo(std::string & dumpInfo)1239 void AccessTokenInfoManager::DumpAllNativeTokenInfo(std::string& dumpInfo)
1240 {
1241 ACCESSTOKEN_LOG_DEBUG(LABEL, "Get all native token info.");
1242
1243 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->nativeTokenInfoLock_);
1244 for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) {
1245 if (iter->second != nullptr) {
1246 iter->second->ToString(dumpInfo);
1247 dumpInfo.append("\n");
1248 }
1249 }
1250 }
1251
GetCurDumpTaskNum()1252 int32_t AccessTokenInfoManager::GetCurDumpTaskNum()
1253 {
1254 return dumpTaskNum_.load();
1255 }
1256
AddDumpTaskNum()1257 void AccessTokenInfoManager::AddDumpTaskNum()
1258 {
1259 dumpTaskNum_++;
1260 }
1261
ReduceDumpTaskNum()1262 void AccessTokenInfoManager::ReduceDumpTaskNum()
1263 {
1264 dumpTaskNum_--;
1265 }
1266
DumpToken()1267 void AccessTokenInfoManager::DumpToken()
1268 {
1269 ACCESSTOKEN_LOG_INFO(LABEL, "AccessToken Dump");
1270 int32_t fd = open(DUMP_JSON_PATH.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1271 if (fd < 0) {
1272 ACCESSTOKEN_LOG_ERROR(LABEL, "Open failed errno %{public}d.", errno);
1273 return;
1274 }
1275 std::string dumpStr;
1276 AtmToolsParamInfoParcel infoParcel;
1277 DumpTokenInfo(infoParcel.info, dumpStr);
1278 dprintf(fd, "%s\n", dumpStr.c_str());
1279 close(fd);
1280 }
1281
DumpTokenInfo(const AtmToolsParamInfo & info,std::string & dumpInfo)1282 void AccessTokenInfoManager::DumpTokenInfo(const AtmToolsParamInfo& info, std::string& dumpInfo)
1283 {
1284 if (info.tokenId != 0) {
1285 DumpHapTokenInfoByTokenId(info.tokenId, dumpInfo);
1286 return;
1287 }
1288
1289 if ((!info.bundleName.empty()) && (info.bundleName.length() > 0)) {
1290 DumpHapTokenInfoByBundleName(info.bundleName, dumpInfo);
1291 return;
1292 }
1293
1294 if ((!info.processName.empty()) && (info.processName.length() > 0)) {
1295 DumpNativeTokenInfoByProcessName(info.processName, dumpInfo);
1296 return;
1297 }
1298
1299 DumpAllHapTokenInfo(dumpInfo);
1300 DumpAllNativeTokenInfo(dumpInfo);
1301 }
1302
GetRelatedSandBoxHapList(AccessTokenID tokenId,std::vector<AccessTokenID> & tokenIdList)1303 void AccessTokenInfoManager::GetRelatedSandBoxHapList(AccessTokenID tokenId, std::vector<AccessTokenID>& tokenIdList)
1304 {
1305 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1306
1307 auto infoIter = hapTokenInfoMap_.find(tokenId);
1308 if (infoIter == hapTokenInfoMap_.end()) {
1309 return;
1310 }
1311 if (infoIter->second == nullptr) {
1312 ACCESSTOKEN_LOG_ERROR(LABEL, "HapTokenInfoInner is nullptr.");
1313 return;
1314 }
1315 std::string bundleName = infoIter->second->GetBundleName();
1316 int32_t userID = infoIter->second->GetUserID();
1317 int32_t index = infoIter->second->GetInstIndex();
1318 int32_t dlpType = infoIter->second->GetDlpType();
1319 // the permissions of a common application whose index is not equal 0 are managed independently.
1320 if ((dlpType == DLP_COMMON) && (index != 0)) {
1321 return;
1322 }
1323
1324 for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); ++iter) {
1325 if (iter->second == nullptr) {
1326 continue;
1327 }
1328 if ((bundleName == iter->second->GetBundleName()) && (userID == iter->second->GetUserID()) &&
1329 (tokenId != iter->second->GetTokenID())) {
1330 if ((iter->second->GetDlpType() == DLP_COMMON) && (iter->second->GetInstIndex() != 0)) {
1331 continue;
1332 }
1333 tokenIdList.emplace_back(iter->second->GetTokenID());
1334 }
1335 }
1336 }
1337
SetPermDialogCap(AccessTokenID tokenID,bool enable)1338 int32_t AccessTokenInfoManager::SetPermDialogCap(AccessTokenID tokenID, bool enable)
1339 {
1340 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1341 auto infoIter = hapTokenInfoMap_.find(tokenID);
1342 if ((infoIter == hapTokenInfoMap_.end()) || (infoIter->second == nullptr)) {
1343 ACCESSTOKEN_LOG_ERROR(LABEL, "HapTokenInfoInner is nullptr.");
1344 return ERR_TOKENID_NOT_EXIST;
1345 }
1346 infoIter->second->SetPermDialogForbidden(enable);
1347
1348 if (!UpdateCapStateToDatabase(tokenID, enable)) {
1349 return RET_FAILED;
1350 }
1351
1352 return RET_SUCCESS;
1353 }
1354
GetPermDialogCap(AccessTokenID tokenID)1355 bool AccessTokenInfoManager::GetPermDialogCap(AccessTokenID tokenID)
1356 {
1357 if (tokenID == INVALID_TOKENID) {
1358 ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid tokenId.");
1359 return true;
1360 }
1361 Utils::UniqueReadGuard<Utils::RWLock> infoGuard(this->hapTokenInfoLock_);
1362 auto infoIter = hapTokenInfoMap_.find(tokenID);
1363 if ((infoIter == hapTokenInfoMap_.end()) || (infoIter->second == nullptr)) {
1364 ACCESSTOKEN_LOG_ERROR(LABEL, "TokenId is not exist in map.");
1365 return true;
1366 }
1367 return infoIter->second->IsPermDialogForbidden();
1368 }
1369
UpdateStatesToDatabase(AccessTokenID tokenID,std::vector<PermissionStateFull> & stateChangeList)1370 bool AccessTokenInfoManager::UpdateStatesToDatabase(AccessTokenID tokenID,
1371 std::vector<PermissionStateFull>& stateChangeList)
1372 {
1373 for (const auto& state : stateChangeList) {
1374 GenericValues modifyValue;
1375 modifyValue.Put(TokenFiledConst::FIELD_GRANT_STATE, state.grantStatus[0]);
1376 modifyValue.Put(TokenFiledConst::FIELD_GRANT_FLAG, static_cast<int32_t>(state.grantFlags[0]));
1377
1378 GenericValues conditionValue;
1379 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1380 conditionValue.Put(TokenFiledConst::FIELD_PERMISSION_NAME, state.permissionName);
1381
1382 int32_t res = AccessTokenDb::GetInstance().Modify(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, modifyValue,
1383 conditionValue);
1384 if (res != 0) {
1385 ACCESSTOKEN_LOG_ERROR(LABEL, "Update tokenID %{public}u permission %{public}s to database failed",
1386 tokenID, state.permissionName.c_str());
1387 return false;
1388 }
1389 }
1390
1391 return true;
1392 }
1393
UpdateCapStateToDatabase(AccessTokenID tokenID,bool enable)1394 bool AccessTokenInfoManager::UpdateCapStateToDatabase(AccessTokenID tokenID, bool enable)
1395 {
1396 GenericValues modifyValue;
1397 modifyValue.Put(TokenFiledConst::FIELD_FORBID_PERM_DIALOG, enable);
1398
1399 GenericValues conditionValue;
1400 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1401
1402 int32_t res = AccessTokenDb::GetInstance().Modify(AtmDataType::ACCESSTOKEN_HAP_INFO, modifyValue, conditionValue);
1403 if (res != 0) {
1404 ACCESSTOKEN_LOG_ERROR(LABEL,
1405 "Update tokenID %{public}u permissionDialogForbidden %{public}d to database failed", tokenID, enable);
1406 return false;
1407 }
1408
1409 return true;
1410 }
1411
RemoveNativeInfoFromDatabase(AccessTokenID tokenID)1412 bool AccessTokenInfoManager::RemoveNativeInfoFromDatabase(AccessTokenID tokenID)
1413 {
1414 GenericValues conditionValue;
1415 conditionValue.Put(TokenFiledConst::FIELD_TOKEN_ID, static_cast<int32_t>(tokenID));
1416
1417 int32_t res = AccessTokenDb::GetInstance().Remove(AtmDataType::ACCESSTOKEN_NATIVE_INFO, conditionValue);
1418 if (res != 0) {
1419 ACCESSTOKEN_LOG_ERROR(LABEL, "Remove tokenID %{public}u from table native_token_info failed.", tokenID);
1420 return false;
1421 }
1422
1423 res = AccessTokenDb::GetInstance().Remove(AtmDataType::ACCESSTOKEN_PERMISSION_STATE, conditionValue);
1424 if (res != 0) {
1425 ACCESSTOKEN_LOG_ERROR(LABEL, "Remove tokenID %{public}u from table permission_state failed.", tokenID);
1426 return false;
1427 }
1428
1429 return true;
1430 }
1431 } // namespace AccessToken
1432 } // namespace Security
1433 } // namespace OHOS
1434