1 /*
2 * Copyright (c) 2023-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 "permission_utils.h"
17
18 #include "accesstoken_kit.h"
19 #include "cs_hisysevent.h"
20 #include "parameter.h"
21 #include "ipc_skeleton.h"
22 #include "log.h"
23
24 namespace OHOS {
25 namespace Security {
26 namespace CodeSign {
27 const std::vector<std::string> CERTIFICATE_CALLERS = {"key_enable"};
28 const std::vector<std::string> SIGN_CALLERS = {"compiler_service"};
29 constexpr int32_t VALUE_MAX_LEN = 32;
30 const char* ACCESS_TOKEN_SERVICE_INIT_KEY = "accesstoken.permission.init";
31 bool g_isAtmInited = false;
32
IsValidCallerOfCert()33 bool PermissionUtils::IsValidCallerOfCert()
34 {
35 AccessToken::AccessTokenID callerTokenId = IPCSkeleton::GetCallingTokenID();
36 if (VerifyCallingProcess(CERTIFICATE_CALLERS, callerTokenId)) {
37 return true;
38 }
39 ReportInvalidCaller("Cert", callerTokenId);
40 return false;
41 }
42
IsValidCallerOfLocalCodeSign()43 bool PermissionUtils::IsValidCallerOfLocalCodeSign()
44 {
45 AccessToken::AccessTokenID callerTokenId = IPCSkeleton::GetCallingTokenID();
46 if (VerifyCallingProcess(SIGN_CALLERS, callerTokenId)) {
47 return true;
48 }
49 ReportInvalidCaller("Sign", callerTokenId);
50 return false;
51 }
52
HasATMInitilized()53 bool PermissionUtils::HasATMInitilized()
54 {
55 char value[VALUE_MAX_LEN] = {0};
56 int32_t ret = GetParameter(ACCESS_TOKEN_SERVICE_INIT_KEY, "", value, VALUE_MAX_LEN - 1);
57 if ((ret < 0) || (static_cast<uint64_t>(std::atoll(value)) != 0)) {
58 g_isAtmInited = true;
59 return true;
60 }
61 return false;
62 }
63
VerifyCallingProcess(const std::vector<std::string> & validCallers,const AccessToken::AccessTokenID & callerTokenId)64 bool PermissionUtils::VerifyCallingProcess(const std::vector<std::string> &validCallers,
65 const AccessToken::AccessTokenID &callerTokenId)
66 {
67 if (!g_isAtmInited && !HasATMInitilized()) {
68 LOG_DEBUG("AccessTokenManager has not started yet.");
69 return true;
70 }
71 for (const auto &caller: validCallers) {
72 AccessToken::AccessTokenID tokenId = AccessToken::AccessTokenKit::GetNativeTokenId(caller);
73 if (tokenId == callerTokenId) {
74 return true;
75 }
76 }
77 LOG_ERROR("Invalid caller.");
78 return false;
79 }
80 }
81 }
82 }