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