1 /*
2 * Copyright (c) 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 #define LOG_TAG "BundleChecker"
16
17 #include "bundle_checker.h"
18 #include <memory>
19 #include "accesstoken_kit.h"
20 #include "hap_token_info.h"
21 #include "log_print.h"
22 #include "utils/crypto.h"
23 namespace OHOS {
24 namespace DistributedData {
25 using namespace Security::AccessToken;
26 __attribute__((used)) BundleChecker BundleChecker::instance_;
BundleChecker()27 BundleChecker::BundleChecker() noexcept
28 {
29 CheckerManager::GetInstance().RegisterPlugin(
30 "BundleChecker", [this]() -> auto { return this; });
31 }
32
~BundleChecker()33 BundleChecker::~BundleChecker()
34 {
35 }
36
Initialize()37 void BundleChecker::Initialize()
38 {
39 }
40
SetTrustInfo(const CheckerManager::Trust & trust)41 bool BundleChecker::SetTrustInfo(const CheckerManager::Trust &trust)
42 {
43 trusts_[trust.bundleName] = trust.appId;
44 return true;
45 }
46
GetAppId(const CheckerManager::StoreInfo & info)47 std::string BundleChecker::GetAppId(const CheckerManager::StoreInfo &info)
48 {
49 if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) {
50 return "";
51 }
52 HapTokenInfo tokenInfo;
53 auto result = AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo);
54 if (result != RET_SUCCESS) {
55 ZLOGE("token:0x%{public}x, result:%{public}d", info.tokenId, result);
56 return "";
57 }
58 if (!info.bundleName.empty() && tokenInfo.bundleName != info.bundleName) {
59 ZLOGE("bundlename:%{public}s <-> %{public}s", info.bundleName.c_str(), tokenInfo.bundleName.c_str());
60 return "";
61 }
62 auto it = trusts_.find(info.bundleName);
63 if (it != trusts_.end() && (it->second == tokenInfo.appID)) {
64 return info.bundleName;
65 }
66 ZLOGD("bundleName:%{public}s, appId:%{public}s", info.bundleName.c_str(), tokenInfo.appID.c_str());
67 return Crypto::Sha256(tokenInfo.appID);
68 }
69
IsValid(const CheckerManager::StoreInfo & info)70 bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info)
71 {
72 if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) {
73 return false;
74 }
75
76 HapTokenInfo tokenInfo;
77 if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) {
78 return false;
79 }
80
81 return tokenInfo.bundleName == info.bundleName;
82 }
83 } // namespace DistributedData
84 } // namespace OHOS