• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 "security_collector_manager_service.h"
17 #include <thread>
18 #include <atomic>
19 #include <cinttypes>
20 #include "hisysevent.h"
21 #include "iservice_registry.h"
22 #include "accesstoken_kit.h"
23 #include "ipc_skeleton.h"
24 #include "system_ability_definition.h"
25 #include "security_collector_define.h"
26 #include "security_collector_log.h"
27 #include "data_collection.h"
28 #include "sg_collect_client.h"
29 #include "security_collector_subscriber_manager.h"
30 #include "security_collector_run_manager.h"
31 #include "security_collector_manager_callback_proxy.h"
32 #include "ffrt.h"
33 #include "event_define.h"
34 #include "tokenid_kit.h"
35 
36 namespace OHOS::Security::SecurityCollector {
37 namespace {
38     constexpr char COLLECT_EVENT_PERMISSION[] = "ohos.permission.COLLECT_SECURITY_EVENT";
39     constexpr char QUERY_EVENT_PERMISSION[] = "ohos.permission.QUERY_SECURITY_EVENT";
40     constexpr const char* CALLER_PID = "CALLER_PID";
41     constexpr const char* EVENT_VERSION = "EVENT_VERSION";
42     constexpr const char* SC_EVENT_ID = "EVENT_ID";
43     constexpr const char* SUB_RET = "SUB_RET";
44     constexpr const char* UNSUB_RET = "UNSUB_RET";
45     constexpr const int SLEEP_INTERVAL = 5000;
46     std::atomic<uint32_t> g_refCount = 0;
47 }
48 
49 REGISTER_SYSTEM_ABILITY_BY_ID(SecurityCollectorManagerService, SECURITY_COLLECTOR_MANAGER_SA_ID, true);
50 
SecurityCollectorManagerService(int32_t saId,bool runOnCreate)51 SecurityCollectorManagerService::SecurityCollectorManagerService(int32_t saId, bool runOnCreate)
52     : SystemAbility(saId, runOnCreate)
53 {
54     LOGW("%{public}s", __func__);
55 }
56 
57 // LCOV_EXCL_START
OnStart()58 void SecurityCollectorManagerService::OnStart()
59 {
60     LOGI("%{public}s", __func__);
61     auto handler = [this] (const sptr<IRemoteObject> &remote) { CleanSubscriber(remote); };
62     SecurityCollectorSubscriberManager::GetInstance().SetUnsubscribeHandler(handler);
63     auto task = []() {
64         while (true) {
65             ffrt::this_task::sleep_for(std::chrono::milliseconds(SLEEP_INTERVAL));
66             if (g_refCount.load() != 0) {
67                 continue;
68             }
69             LOGI("Unload security collector manager SA begin.");
70             auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
71             if (registry == nullptr) {
72                 LOGE("GetSystemAbilityManager error.");
73                 break;
74             }
75             registry->UnloadSystemAbility(SECURITY_COLLECTOR_MANAGER_SA_ID);
76             LOGI("Unload security collector manager SA end.");
77             break;
78         }
79     };
80     ffrt::submit(task);
81     if (!Publish(this)) {
82         LOGE("Publish error");
83     }
84 }
85 
OnStop()86 void SecurityCollectorManagerService::OnStop()
87 {}
88 // LCOV_EXCL_STOP
89 
Dump(int fd,const std::vector<std::u16string> & args)90 int SecurityCollectorManagerService::Dump(int fd, const std::vector<std::u16string>& args)
91 {
92     return 0;
93 }
94 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)95 void SecurityCollectorManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
96 {
97 }
98 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)99 void SecurityCollectorManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
100 {
101     LOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
102 }
103 
Subscribe(const SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)104 int32_t SecurityCollectorManagerService::Subscribe(const SecurityCollectorSubscribeInfo &subscribeInfo,
105     const sptr<IRemoteObject> &callback)
106 {
107     Event event = subscribeInfo.GetEvent();
108     LOGI("in subscribe, subscribinfo: duration:%{public}" PRId64 ", isNotify:%{public}d, eventid:%{public}" PRId64 ","
109         "version:%{public}s, extra:%{public}s", subscribeInfo.GetDuration(), (int)subscribeInfo.IsNotify(),
110         event.eventId, event.version.c_str(), event.extra.c_str());
111     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
112     if (ret != SUCCESS) {
113         LOGE("caller no permission");
114         return ret;
115     }
116     if (!SetDeathRecipient(callback)) {
117         return NULL_OBJECT;
118     }
119     auto eventHandler = [this] (const std::string &appName, const sptr<IRemoteObject> &remote, const Event &event) {
120         ExecuteOnNotifyByTask(remote, event);
121     };
122     auto subscriber = std::make_shared<SecurityCollectorSubscriber>(NOTIFY_APP_NAME,
123         subscribeInfo, callback, eventHandler);
124     ScSubscribeEvent subEvent;
125     subEvent.pid = IPCSkeleton::GetCallingPid();
126     subEvent.version = event.version;
127     subEvent.eventId = event.eventId;
128 
129     if (!SecurityCollectorSubscriberManager::GetInstance().SubscribeCollector(subscriber)) {
130         UnsetDeathRecipient(callback);
131         subEvent.ret = BAD_PARAM;
132         ReportScSubscribeEvent(subEvent);
133         return BAD_PARAM;
134     }
135     subEvent.ret = SUCCESS;
136     ReportScSubscribeEvent(subEvent);
137     LOGI("Out subscribe");
138     g_refCount.fetch_add(1);
139     return SUCCESS;
140 }
141 
Unsubscribe(const sptr<IRemoteObject> & callback)142 int32_t SecurityCollectorManagerService::Unsubscribe(const sptr<IRemoteObject> &callback)
143 {
144     LOGI("In unsubscribe");
145     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
146     if (ret != SUCCESS) {
147         LOGE("caller no permission");
148         return ret;
149     }
150     if (g_refCount.load() == 0) {
151         LOGE("Unsubscriber event failed, subscriber count is 0");
152         return FAILED;
153     }
154     CleanSubscriber(callback);
155 
156     ScUnsubscribeEvent subEvent;
157     subEvent.pid = IPCSkeleton::GetCallingPid();
158     subEvent.ret = SUCCESS;
159     LOGI("SecurityCollectorManagerService, CleanSubscriber");
160     ReportScUnsubscribeEvent(subEvent);
161 
162     LOGI("Out unsubscribe");
163     g_refCount.fetch_sub(1);
164     return SUCCESS;
165 }
166 
CollectorStart(const SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)167 int32_t SecurityCollectorManagerService::CollectorStart(const SecurityCollectorSubscribeInfo &subscribeInfo,
168     const sptr<IRemoteObject> &callback)
169 {
170     Event event = subscribeInfo.GetEvent();
171     int32_t ret = HasPermission(COLLECT_EVENT_PERMISSION);
172     if (ret != SUCCESS) {
173         LOGE("caller no permission");
174         return ret;
175     }
176     int32_t collectorType = COLLECTOR_NOT_CAN_START;
177     if (DataCollection::GetInstance().GetCollectorType(event.eventId, collectorType) != SUCCESS) {
178         LOGE("get collector type error event id: %{public}" PRId64, event.eventId);
179         return BAD_PARAM;
180     }
181 
182     if (collectorType != COLLECTOR_CAN_START) {
183         LOGE("collector type not support be start, event id: %{public}" PRId64, event.eventId);
184         return BAD_PARAM;
185     }
186     std::string appName = GetAppName();
187     LOGI("in subscribe, appname:%{public}s", appName.c_str());
188     if (appName.empty()) {
189         return BAD_PARAM;
190     }
191     auto eventHandler = [this] (const std::string &appName, const sptr<IRemoteObject> &remote, const Event &event) {
192         LOGD("eventid:%{public}" PRId64 " callback default", event.eventId);
193         auto reportEvent = [event] () {
194             auto info = std::make_shared<SecurityGuard::EventInfo>(event.eventId, event.version, event.content);
195             SecurityGuard::NativeDataCollectKit::ReportSecurityInfo(info);
196         };
197         reportEvent();
198         return;
199     };
200     auto subscriber = std::make_shared<SecurityCollectorSubscriber>(appName, subscribeInfo, nullptr, eventHandler);
201     ScSubscribeEvent subEvent;
202     subEvent.pid = IPCSkeleton::GetCallingPid();
203     subEvent.version = event.version;
204     subEvent.eventId = event.eventId;
205 
206     if (!SecurityCollectorRunManager::GetInstance().StartCollector(subscriber)) {
207         subEvent.ret = BAD_PARAM;
208         ReportScSubscribeEvent(subEvent);
209         return BAD_PARAM;
210     }
211     subEvent.ret = SUCCESS;
212     ReportScSubscribeEvent(subEvent);
213     LOGI("Out CollectorStart");
214     g_refCount.fetch_add(1);
215     return SUCCESS;
216 }
217 
CollectorStop(const SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)218 int32_t SecurityCollectorManagerService::CollectorStop(const SecurityCollectorSubscribeInfo &subscribeInfo,
219     const sptr<IRemoteObject> &callback)
220 {
221     Event event = subscribeInfo.GetEvent();
222     int32_t ret = HasPermission(COLLECT_EVENT_PERMISSION);
223     if (g_refCount.load() == 0) {
224         LOGE("Collector stop failed, subscriber count is 0");
225         return FAILED;
226     }
227     if (ret != SUCCESS) {
228         LOGE("caller no permission");
229         return ret;
230     }
231     std::string appName = GetAppName();
232     LOGI("in CollectorStop, appname:%{public}s", appName.c_str());
233     if (appName.empty()) {
234         return BAD_PARAM;
235     }
236     auto eventHandler = [this] (const std::string &appName, const sptr<IRemoteObject> &remote, const Event &event) {
237         return;
238     };
239     auto subscriber = std::make_shared<SecurityCollectorSubscriber>(appName, subscribeInfo, nullptr, eventHandler);
240     ScSubscribeEvent subEvent;
241     subEvent.pid = IPCSkeleton::GetCallingPid();
242     subEvent.version = event.version;
243     subEvent.eventId = event.eventId;
244 
245     if (!SecurityCollectorRunManager::GetInstance().StopCollector(subscriber)) {
246         subEvent.ret = BAD_PARAM;
247         ReportScSubscribeEvent(subEvent);
248         return BAD_PARAM;
249     }
250     subEvent.ret = SUCCESS;
251     ReportScSubscribeEvent(subEvent);
252     LOGI("Out CollectorStop");
253     g_refCount.fetch_sub(1);
254     return SUCCESS;
255 }
256 
CleanSubscriber(const sptr<IRemoteObject> & remote)257 void SecurityCollectorManagerService::CleanSubscriber(const sptr<IRemoteObject> &remote)
258 {
259     LOGI("Clean Subscribe ");
260     UnsetDeathRecipient(remote);
261     SecurityCollectorSubscriberManager::GetInstance().UnsubscribeCollector(remote);
262     SecurityCollectorSubscriberManager::GetInstance().RemoveAllFilter();
263 }
264 
265 // LCOV_EXCL_START
SetDeathRecipient(const sptr<IRemoteObject> & remote)266 bool SecurityCollectorManagerService::SetDeathRecipient(const sptr<IRemoteObject> &remote)
267 {
268     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
269     if (deathRecipient_ == nullptr) {
270         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
271         if (deathRecipient_ == nullptr) {
272             LOGE("no memory");
273             return false;
274         }
275     }
276     remote->AddDeathRecipient(deathRecipient_);
277     return true;
278 }
279 
UnsetDeathRecipient(const sptr<IRemoteObject> & remote)280 void SecurityCollectorManagerService::UnsetDeathRecipient(const sptr<IRemoteObject> &remote)
281 {
282     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
283     if (deathRecipient_ != nullptr) {
284         remote->RemoveDeathRecipient(deathRecipient_);
285     }
286 }
287 
OnRemoteDied(const wptr<IRemoteObject> & remote)288 void SecurityCollectorManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
289 {
290     g_refCount.fetch_sub(1);
291     LOGD("SecurityCollectorManagerService In");
292     if (remote == nullptr) {
293         LOGE("remote object is nullptr");
294         return;
295     }
296     sptr<IRemoteObject> object = remote.promote();
297     if (object == nullptr) {
298         LOGE("object is nullptr");
299         return;
300     }
301     sptr<SecurityCollectorManagerService> service = service_.promote();
302     if (service == nullptr) {
303         LOGE("service is nullptr");
304         return;
305     }
306     service->CleanSubscriber(object);
307     LOGD("SecurityCollectorManagerService out");
308 }
309 // LCOV_EXCL_STOP
310 
ReportScSubscribeEvent(const ScSubscribeEvent & event)311 void SecurityCollectorManagerService::ReportScSubscribeEvent(const ScSubscribeEvent &event)
312 {
313     HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::SECURITY_GUARD, "SC_EVENT_SUBSCRIBE",
314         OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, CALLER_PID, event.pid,
315         EVENT_VERSION, event.version, SC_EVENT_ID, event.eventId, SUB_RET, event.ret);
316 }
317 
ReportScUnsubscribeEvent(const ScUnsubscribeEvent & event)318 void SecurityCollectorManagerService::ReportScUnsubscribeEvent(const ScUnsubscribeEvent &event)
319 {
320     HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::SECURITY_GUARD, "SC_EVENT_UNSUBSCRIBE",
321         OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, CALLER_PID, event.pid, UNSUB_RET, event.ret);
322 }
323 
ExecuteOnNotifyByTask(const sptr<IRemoteObject> & remote,const Event & event)324 void SecurityCollectorManagerService::ExecuteOnNotifyByTask(const sptr<IRemoteObject> &remote, const Event &event)
325 {
326     auto proxy = iface_cast<SecurityCollectorManagerCallbackProxy>(remote);
327     if (proxy != nullptr) {
328         LOGD("report to proxy");
329         auto task = [proxy, event] () {
330             proxy->OnNotify(event);
331         };
332         if (event.eventId == SecurityCollector::FILE_EVENTID ||
333             event.eventId == SecurityCollector::PROCESS_EVENTID ||
334             event.eventId == SecurityCollector::NETWORK_EVENTID) {
335             ffrt::submit(task, {}, {}, ffrt::task_attr().qos(ffrt::qos_background));
336         } else {
337             ffrt::submit(task);
338         }
339     } else {
340         LOGE("report proxy is null");
341     }
342 }
343 
QuerySecurityEvent(const std::vector<SecurityEventRuler> rulers,std::vector<SecurityEvent> & events)344 int32_t SecurityCollectorManagerService::QuerySecurityEvent(const std::vector<SecurityEventRuler> rulers,
345     std::vector<SecurityEvent> &events)
346 {
347     g_refCount.fetch_add(1);
348     LOGI("begin QuerySecurityEvent");
349     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
350     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, QUERY_EVENT_PERMISSION);
351     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
352         LOGE("caller no permission");
353         g_refCount.fetch_sub(1);
354         return NO_PERMISSION;
355     }
356 
357     if (DataCollection::GetInstance().QuerySecurityEvent(rulers, events) != SUCCESS) {
358         LOGI("QuerySecurityEvent error");
359         g_refCount.fetch_sub(1);
360         return READ_ERR;
361     }
362     g_refCount.fetch_sub(1);
363     return SUCCESS;
364 }
365 
GetAppName()366 std::string SecurityCollectorManagerService::GetAppName()
367 {
368     AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
369     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(tokenId);
370     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
371         AccessToken::HapTokenInfo hapTokenInfo;
372         int ret = AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo);
373         if (ret != 0) {
374             LOGE("failed to get hap token info, result = %{public}d", ret);
375             return "";
376         }
377         return hapTokenInfo.bundleName;
378     } else if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
379         AccessToken::NativeTokenInfo nativeTokenInfo;
380         int ret = AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
381         if (ret != 0) {
382             LOGE("failed to get native token info, result = %{public}d", ret);
383             return "";
384         }
385         return nativeTokenInfo.processName;
386     }
387     LOGE("failed to get app name");
388     return "";
389 }
390 
HasPermission(const std::string & permission)391 int32_t SecurityCollectorManagerService::HasPermission(const std::string &permission)
392 {
393     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
394     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permission);
395     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
396         return NO_PERMISSION;
397     }
398 
399     return SUCCESS;
400 }
401 
AddFilter(const SecurityCollectorEventFilter & subscribeMute)402 int32_t SecurityCollectorManagerService::AddFilter(const SecurityCollectorEventFilter &subscribeMute)
403 {
404     LOGI("In SecurityCollectorManagerService AddFilter");
405     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
406     if (ret != SUCCESS) {
407         LOGE("caller no permission");
408         return ret;
409     }
410     ret = SecurityCollectorSubscriberManager::GetInstance().AddFilter(subscribeMute.GetMuteFilter());
411     if (ret != SUCCESS) {
412         LOGE("fail to set mute");
413     }
414     return ret;
415 }
416 
RemoveFilter(const SecurityCollectorEventFilter & subscribeMute)417 int32_t SecurityCollectorManagerService::RemoveFilter(const SecurityCollectorEventFilter &subscribeMute)
418 {
419     LOGI("In SecurityCollectorManagerService RemoveFilter");
420     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
421     if (ret != SUCCESS) {
422         LOGE("caller no permission");
423         return ret;
424     }
425     ret = SecurityCollectorSubscriberManager::GetInstance().RemoveFilter(subscribeMute.GetMuteFilter());
426     if (ret != SUCCESS) {
427         LOGE("fail to set unmute");
428     }
429     return ret;
430 }
431 }