• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 "privacy_manager_service.h"
17 
18 #include <cinttypes>
19 #include <cstring>
20 
21 #include "accesstoken_log.h"
22 #include "constant_common.h"
23 #include "constant.h"
24 #include "ipc_skeleton.h"
25 #include "permission_record_manager.h"
26 #ifdef SECURITY_COMPONENT_ENHANCE_ENABLE
27 #include "privacy_sec_comp_enhance_agent.h"
28 #endif
29 #ifdef POWER_MANAGER_ENABLE
30 #include "privacy_power_shutdown_callback.h"
31 #include "shutdown/shutdown_client.h"
32 #include "system_ability_definition.h"
33 #endif
34 #include "string_ex.h"
35 
36 namespace OHOS {
37 namespace Security {
38 namespace AccessToken {
39 namespace {
40 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
41     LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerService"
42 };
43 }
44 
45 const bool REGISTER_RESULT =
46     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<PrivacyManagerService>::GetInstance().get());
47 
PrivacyManagerService()48 PrivacyManagerService::PrivacyManagerService()
49     : SystemAbility(SA_ID_PRIVACY_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START)
50 {
51     ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService()");
52 }
53 
~PrivacyManagerService()54 PrivacyManagerService::~PrivacyManagerService()
55 {
56     ACCESSTOKEN_LOG_INFO(LABEL, "~PrivacyManagerService()");
57 }
58 
OnStart()59 void PrivacyManagerService::OnStart()
60 {
61     if (state_ == ServiceRunningState::STATE_RUNNING) {
62         ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService has already started!");
63         return;
64     }
65     if (!Initialize()) {
66         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize");
67         return;
68     }
69 
70 #ifdef POWER_MANAGER_ENABLE
71     AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
72 #endif
73 
74     state_ = ServiceRunningState::STATE_RUNNING;
75     bool ret = Publish(DelayedSingleton<PrivacyManagerService>::GetInstance().get());
76     if (!ret) {
77         ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!");
78         return;
79     }
80     ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, PrivacyManagerService start successfully!");
81 }
82 
OnStop()83 void PrivacyManagerService::OnStop()
84 {
85     ACCESSTOKEN_LOG_INFO(LABEL, "stop service");
86     state_ = ServiceRunningState::STATE_NOT_START;
87 
88 #ifdef POWER_MANAGER_ENABLE
89     if (powerShutDownCallback_ != nullptr) {
90         PowerMgr::ShutdownClient::GetInstance().UnRegisterShutdownCallback(powerShutDownCallback_);
91         powerShutDownCallback_ = nullptr;
92     }
93 #endif
94 }
95 
AddPermissionUsedRecord(AccessTokenID tokenId,const std::string & permissionName,int32_t successCount,int32_t failCount,bool asyncMode)96 int32_t PrivacyManagerService::AddPermissionUsedRecord(AccessTokenID tokenId, const std::string& permissionName,
97     int32_t successCount, int32_t failCount, bool asyncMode)
98 {
99     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, permissionName: %{public}s, successCount: %{public}d, \
100         failCount: %{public}d, asyncMode: %{public}d",
101         tokenId, permissionName.c_str(), successCount, failCount, asyncMode);
102     return PermissionRecordManager::GetInstance().AddPermissionUsedRecord(
103         tokenId, permissionName, successCount, failCount);
104 }
105 
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName)106 int32_t PrivacyManagerService::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
107 {
108     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, permissionName: %{public}s", tokenId, permissionName.c_str());
109     return PermissionRecordManager::GetInstance().StartUsingPermission(tokenId, permissionName);
110 }
111 
StartUsingPermission(AccessTokenID tokenId,const std::string & permissionName,const sptr<IRemoteObject> & callback)112 int32_t PrivacyManagerService::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName,
113     const sptr<IRemoteObject>& callback)
114 {
115     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, permissionName: %{public}s", tokenId, permissionName.c_str());
116     return PermissionRecordManager::GetInstance().StartUsingPermission(tokenId, permissionName, callback);
117 }
118 
StopUsingPermission(AccessTokenID tokenId,const std::string & permissionName)119 int32_t PrivacyManagerService::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
120 {
121     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, permissionName: %{public}s", tokenId, permissionName.c_str());
122     return PermissionRecordManager::GetInstance().StopUsingPermission(tokenId, permissionName);
123 }
124 
RemovePermissionUsedRecords(AccessTokenID tokenId,const std::string & deviceID)125 int32_t PrivacyManagerService::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID)
126 {
127     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, deviceID: %{public}s", tokenId, deviceID.c_str());
128     PermissionRecordManager::GetInstance().RemovePermissionUsedRecords(tokenId, deviceID);
129     return Constant::SUCCESS;
130 }
131 
GetPermissionUsedRecords(const PermissionUsedRequestParcel & request,PermissionUsedResultParcel & result)132 int32_t PrivacyManagerService::GetPermissionUsedRecords(
133     const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result)
134 {
135     std::string permissionList;
136     for (const auto& perm : request.request.permissionList) {
137         permissionList.append(perm);
138         permissionList.append(" ");
139     }
140     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, beginTime: %{public}" PRId64 ", endTime: %{public}" PRId64
141         ", flag: %{public}d, perm: %{public}s", request.request.tokenId, request.request.beginTimeMillis,
142         request.request.endTimeMillis, request.request.flag, permissionList.c_str());
143 
144     PermissionUsedResult permissionRecord;
145     int32_t ret =  PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request.request, permissionRecord);
146     result.result = permissionRecord;
147     return ret;
148 }
149 
GetPermissionUsedRecords(const PermissionUsedRequestParcel & request,const sptr<OnPermissionUsedRecordCallback> & callback)150 int32_t PrivacyManagerService::GetPermissionUsedRecords(
151     const PermissionUsedRequestParcel& request, const sptr<OnPermissionUsedRecordCallback>& callback)
152 {
153     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d", request.request.tokenId);
154     return PermissionRecordManager::GetInstance().GetPermissionUsedRecordsAsync(request.request, callback);
155 }
156 
RegisterPermActiveStatusCallback(std::vector<std::string> & permList,const sptr<IRemoteObject> & callback)157 int32_t PrivacyManagerService::RegisterPermActiveStatusCallback(
158     std::vector<std::string>& permList, const sptr<IRemoteObject>& callback)
159 {
160     return PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback(permList, callback);
161 }
162 
163 #ifdef SECURITY_COMPONENT_ENHANCE_ENABLE
RegisterSecCompEnhance(const SecCompEnhanceDataParcel & enhanceParcel)164 int32_t PrivacyManagerService::RegisterSecCompEnhance(const SecCompEnhanceDataParcel& enhanceParcel)
165 {
166     ACCESSTOKEN_LOG_INFO(LABEL, "pid: %{public}d", enhanceParcel.enhanceData.pid);
167     return PrivacySecCompEnhanceAgent::GetInstance().RegisterSecCompEnhance(enhanceParcel.enhanceData);
168 }
169 
GetSecCompEnhance(int32_t pid,SecCompEnhanceDataParcel & enhanceParcel)170 int32_t PrivacyManagerService::GetSecCompEnhance(int32_t pid, SecCompEnhanceDataParcel& enhanceParcel)
171 {
172     SecCompEnhanceData enhanceData;
173     int32_t res = PrivacySecCompEnhanceAgent::GetInstance().GetSecCompEnhance(pid, enhanceData);
174     if (res != RET_SUCCESS) {
175         ACCESSTOKEN_LOG_WARN(LABEL, "pid: %{public}d get enhance failed ", pid);
176         return res;
177     }
178 
179     enhanceParcel.enhanceData = enhanceData;
180     return RET_SUCCESS;
181 }
182 
GetSpecialSecCompEnhance(const std::string & bundleName,std::vector<SecCompEnhanceDataParcel> & enhanceParcelList)183 int32_t PrivacyManagerService::GetSpecialSecCompEnhance(const std::string& bundleName,
184     std::vector<SecCompEnhanceDataParcel>& enhanceParcelList)
185 {
186     std::vector<SecCompEnhanceData> enhanceList;
187     PrivacySecCompEnhanceAgent::GetInstance().GetSpecialSecCompEnhance(bundleName, enhanceList);
188     for (const auto& enhance : enhanceList) {
189         SecCompEnhanceDataParcel parcel;
190         parcel.enhanceData = enhance;
191         enhanceParcelList.emplace_back(parcel);
192     }
193 
194     return RET_SUCCESS;
195 }
196 #endif
197 
ResponseDumpCommand(int32_t fd,const std::vector<std::u16string> & args)198 int32_t PrivacyManagerService::ResponseDumpCommand(int32_t fd, const std::vector<std::u16string>& args)
199 {
200     if (args.size() < 2) { // 2 :need two args 0:command 1:tokenId
201         return ERR_INVALID_VALUE;
202     }
203     long long tokenId = atoll(static_cast<const char*>(Str16ToStr8(args.at(1)).c_str()));
204     PermissionUsedRequest request;
205     if (tokenId <= 0) {
206         return ERR_INVALID_VALUE;
207     }
208     request.tokenId = static_cast<uint32_t>(tokenId);
209     request.flag = FLAG_PERMISSION_USAGE_SUMMARY;
210     PermissionUsedResult result;
211     if (PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request, result) != 0) {
212         return ERR_INVALID_VALUE;
213     }
214     std::string infos;
215     if (result.bundleRecords.empty() || result.bundleRecords[0].permissionRecords.empty()) {
216         dprintf(fd, "No Record \n");
217         return ERR_OK;
218     }
219     for (size_t index = 0; index < result.bundleRecords[0].permissionRecords.size(); index++) {
220         infos.append(R"(  "permissionRecord": [)");
221         infos.append("\n");
222         infos.append(R"(    "bundleName": )" + result.bundleRecords[0].bundleName + ",\n");
223         infos.append(R"(    "isRemote": )" + std::to_string(result.bundleRecords[0].isRemote) + ",\n");
224         infos.append(R"(    "permissionName": ")" + result.bundleRecords[0].permissionRecords[index].permissionName +
225                     R"(")" + ",\n");
226         time_t lastAccessTime = static_cast<time_t>(result.bundleRecords[0].permissionRecords[index].lastAccessTime);
227         infos.append(R"(    "lastAccessTime": )" + std::to_string(lastAccessTime) + ",\n");
228         infos.append(R"(    "lastAccessDuration": )" +
229                     std::to_string(result.bundleRecords[0].permissionRecords[index].lastAccessDuration) + ",\n");
230         infos.append(R"(    "accessCount": ")" +
231                     std::to_string(result.bundleRecords[0].permissionRecords[index].accessCount) + R"(")" + ",\n");
232         infos.append("  ]");
233         infos.append("\n");
234     }
235     dprintf(fd, "%s\n", infos.c_str());
236     return ERR_OK;
237 }
238 
Dump(int32_t fd,const std::vector<std::u16string> & args)239 int32_t PrivacyManagerService::Dump(int32_t fd, const std::vector<std::u16string>& args)
240 {
241     if (fd < 0) {
242         ACCESSTOKEN_LOG_ERROR(LABEL, "Dump fd invalid value");
243         return ERR_INVALID_VALUE;
244     }
245     int32_t ret = ERR_OK;
246     dprintf(fd, "Privacy Dump:\n");
247     if (args.size() == 0) {
248         dprintf(fd, "please use hidumper -s said -a '-h' command help\n");
249         return ret;
250     }
251     std::string arg0 = Str16ToStr8(args.at(0));
252     if (arg0.compare("-h") == 0) {
253         dprintf(fd, "Usage:\n");
254         dprintf(fd, "       -h: command help\n");
255         dprintf(fd, "       -t <TOKEN_ID>: according to specific token id dump permission used records\n");
256     } else if (arg0.compare("-t") == 0) {
257         ret = PrivacyManagerService::ResponseDumpCommand(fd, args);
258     } else {
259         dprintf(fd, "please use hidumper -s said -a '-h' command help\n");
260         ret = ERR_INVALID_VALUE;
261     }
262     return ret;
263 }
264 
UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject> & callback)265 int32_t PrivacyManagerService::UnRegisterPermActiveStatusCallback(const sptr<IRemoteObject>& callback)
266 {
267     return PermissionRecordManager::GetInstance().UnRegisterPermActiveStatusCallback(callback);
268 }
269 
IsAllowedUsingPermission(AccessTokenID tokenId,const std::string & permissionName)270 bool PrivacyManagerService::IsAllowedUsingPermission(AccessTokenID tokenId, const std::string& permissionName)
271 {
272     ACCESSTOKEN_LOG_INFO(LABEL, "tokenId: %{public}d, permissionName: %{public}s", tokenId, permissionName.c_str());
273     return PermissionRecordManager::GetInstance().IsAllowedUsingPermission(tokenId, permissionName);
274 }
275 
276 #ifdef POWER_MANAGER_ENABLE
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)277 void PrivacyManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
278 {
279     ACCESSTOKEN_LOG_INFO(LABEL, "systemAbilityId is %{public}d", systemAbilityId);
280 
281     if (systemAbilityId == POWER_MANAGER_SERVICE_ID) {
282         if (powerShutDownCallback_ == nullptr) {
283             powerShutDownCallback_ = new(std::nothrow) PrivacyPowerShutDownCallback();
284             if (powerShutDownCallback_ == nullptr) {
285                 ACCESSTOKEN_LOG_ERROR(LABEL, "failed to new shutdown callback.");
286                 return;
287             }
288 
289             PowerMgr::ShutdownClient::GetInstance().RegisterShutdownCallback(powerShutDownCallback_,
290                 PowerMgr::ShutdownPriority::HIGH);
291 
292             ACCESSTOKEN_LOG_INFO(LABEL, "register power shutdown callback complete!");
293         }
294     }
295 }
296 #endif
297 
Initialize() const298 bool PrivacyManagerService::Initialize() const
299 {
300     PermissionRecordManager::GetInstance().Init();
301     return true;
302 }
303 } // namespace AccessToken
304 } // namespace Security
305 } // namespace OHOS
306