• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 "code_sign_test_common.h"
17 #include <sstream>
18 #include "accesstoken_kit.h"
19 #include "ipc_skeleton.h"
20 #include "token_setproc.h"
21 
22 namespace OHOS {
23 namespace Security {
24 namespace CodeSign {
25 using namespace OHOS::Security::AccessToken;
26 
27 namespace {
28     static uint64_t g_shellTokenID = IPCSkeleton::GetSelfTokenID();
29 }
30 
GetTokenId(const AtmToolsParamInfo & info)31 static uint64_t GetTokenId(const AtmToolsParamInfo &info)
32 {
33     std::string dumpInfo;
34     AccessTokenKit::DumpTokenInfo(info, dumpInfo);
35     size_t pos = dumpInfo.find("\"tokenID\": ");
36     if (pos == std::string::npos) {
37         return 0;
38     }
39     pos += std::string("\"tokenID\": ").length();
40     std::string numStr;
41     while (pos < dumpInfo.length() && std::isdigit(dumpInfo[pos])) {
42         numStr += dumpInfo[pos];
43         ++pos;
44     }
45 
46     std::istringstream iss(numStr);
47     uint64_t tokenID;
48     iss >> tokenID;
49     return tokenID;
50 }
51 
GetTokenIdFromProcess(const std::string & process)52 uint64_t GetTokenIdFromProcess(const std::string &process)
53 {
54     auto tokenId = IPCSkeleton::GetSelfTokenID();
55     SetSelfTokenID(g_shellTokenID); // only shell can dump tokenid
56 
57     AtmToolsParamInfo info;
58     info.processName = process;
59     auto res = GetTokenId(info);
60 
61     SetSelfTokenID(tokenId);
62     return res;
63 }
64 
MockTokenId(const std::string & process)65 bool MockTokenId(const std::string &process)
66 {
67     auto mockTokenId = GetTokenIdFromProcess(process);
68     if (mockTokenId == 0) {
69         return false;
70     }
71     if (SetSelfTokenID(mockTokenId) != 0) {
72         return false;
73     }
74     return IPCSkeleton::GetSelfTokenID() != 0;
75 }
76 } // namespace CodeSign
77 } // namespace Security
78 } // namespace OHOS
79