• 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 
OnStart()57 void SecurityCollectorManagerService::OnStart()
58 {
59     LOGI("%{public}s", __func__);
60     auto handler = [this] (const sptr<IRemoteObject> &remote) { CleanSubscriber(remote); };
61     SecurityCollectorSubscriberManager::GetInstance().SetUnsubscribeHandler(handler);
62     auto task = []() {
63         while (true) {
64             std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_INTERVAL));
65             if (g_refCount.load() != 0) {
66                 continue;
67             }
68             LOGI("Unload security collector manager SA begin.");
69             auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
70             if (registry == nullptr) {
71                 LOGE("GetSystemAbilityManager error.");
72                 break;
73             }
74             registry->UnloadSystemAbility(SECURITY_COLLECTOR_MANAGER_SA_ID);
75             LOGI("Unload security collector manager SA end.");
76             break;
77         }
78     };
79     ffrt::submit(task);
80     if (!Publish(this)) {
81         LOGE("Publish error");
82     }
83 }
84 
OnStop()85 void SecurityCollectorManagerService::OnStop()
86 {
87     DataCollection::GetInstance().CloseLib();
88 }
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 
257 
CleanSubscriber(const sptr<IRemoteObject> & remote)258 void SecurityCollectorManagerService::CleanSubscriber(const sptr<IRemoteObject> &remote)
259 {
260     LOGI("Clean Subscribe ");
261     UnsetDeathRecipient(remote);
262     SecurityCollectorSubscriberManager::GetInstance().UnsubscribeCollector(remote);
263 }
264 
SetDeathRecipient(const sptr<IRemoteObject> & remote)265 bool SecurityCollectorManagerService::SetDeathRecipient(const sptr<IRemoteObject> &remote)
266 {
267     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
268     if (deathRecipient_ == nullptr) {
269         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
270         if (deathRecipient_ == nullptr) {
271             LOGE("no memory");
272             return false;
273         }
274     }
275     remote->AddDeathRecipient(deathRecipient_);
276     return true;
277 }
278 
UnsetDeathRecipient(const sptr<IRemoteObject> & remote)279 void SecurityCollectorManagerService::UnsetDeathRecipient(const sptr<IRemoteObject> &remote)
280 {
281     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
282     if (deathRecipient_ != nullptr) {
283         remote->RemoveDeathRecipient(deathRecipient_);
284     }
285 }
286 
OnRemoteDied(const wptr<IRemoteObject> & remote)287 void SecurityCollectorManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
288 {
289     g_refCount.fetch_sub(1);
290     LOGD("SecurityCollectorManagerService In");
291     if (remote == nullptr) {
292         LOGE("remote object is nullptr");
293         return;
294     }
295     sptr<IRemoteObject> object = remote.promote();
296     if (object == nullptr) {
297         LOGE("object is nullptr");
298         return;
299     }
300     sptr<SecurityCollectorManagerService> service = service_.promote();
301     if (service == nullptr) {
302         LOGE("service is nullptr");
303         return;
304     }
305     service->CleanSubscriber(object);
306     LOGD("SecurityCollectorManagerService out");
307 }
308 
ReportScSubscribeEvent(const ScSubscribeEvent & event)309 void SecurityCollectorManagerService::ReportScSubscribeEvent(const ScSubscribeEvent &event)
310 {
311     HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::SECURITY_GUARD, "SC_EVENT_SUBSCRIBE",
312         OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, CALLER_PID, event.pid,
313         EVENT_VERSION, event.version, SC_EVENT_ID, event.eventId, SUB_RET, event.ret);
314 }
315 
ReportScUnsubscribeEvent(const ScUnsubscribeEvent & event)316 void SecurityCollectorManagerService::ReportScUnsubscribeEvent(const ScUnsubscribeEvent &event)
317 {
318     HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::SECURITY_GUARD, "SC_EVENT_UNSUBSCRIBE",
319         OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, CALLER_PID, event.pid, UNSUB_RET, event.ret);
320 }
321 
ExecuteOnNotifyByTask(const sptr<IRemoteObject> & remote,const Event & event)322 void SecurityCollectorManagerService::ExecuteOnNotifyByTask(const sptr<IRemoteObject> &remote, const Event &event)
323 {
324     auto proxy = iface_cast<SecurityCollectorManagerCallbackProxy>(remote);
325     if (proxy != nullptr) {
326         LOGD("report to proxy");
327         auto task = [proxy, event] () {
328             proxy->OnNotify(event);
329         };
330         if (event.eventId == SecurityCollector::FILE_EVENTID ||
331             event.eventId == SecurityCollector::PROCESS_EVENTID ||
332             event.eventId == SecurityCollector::NETWORK_EVENTID) {
333             ffrt::submit(task, {}, {}, ffrt::task_attr().qos(ffrt::qos_background));
334         } else {
335             ffrt::submit(task);
336         }
337     } else {
338         LOGE("report proxy is null");
339     }
340 }
341 
QuerySecurityEvent(const std::vector<SecurityEventRuler> rulers,std::vector<SecurityEvent> & events)342 int32_t SecurityCollectorManagerService::QuerySecurityEvent(const std::vector<SecurityEventRuler> rulers,
343     std::vector<SecurityEvent> &events)
344 {
345     g_refCount.fetch_add(1);
346     LOGI("begin QuerySecurityEvent");
347     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
348     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, QUERY_EVENT_PERMISSION);
349     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
350         LOGE("caller no permission");
351         g_refCount.fetch_sub(1);
352         return NO_PERMISSION;
353     }
354     bool isSuccess = DataCollection::GetInstance().QuerySecurityEvent(rulers, events);
355     if (!isSuccess) {
356         LOGI("QuerySecurityEvent error");
357         g_refCount.fetch_sub(1);
358         return READ_ERR;
359     }
360     g_refCount.fetch_sub(1);
361     return SUCCESS;
362 }
363 
GetAppName()364 std::string SecurityCollectorManagerService::GetAppName()
365 {
366     AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
367     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(tokenId);
368     if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
369         AccessToken::HapTokenInfo hapTokenInfo;
370         int ret = AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo);
371         if (ret != 0) {
372             LOGE("failed to get hap token info, result = %{public}d", ret);
373             return "";
374         }
375         return hapTokenInfo.bundleName;
376     } else if (tokenType == AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
377         AccessToken::NativeTokenInfo nativeTokenInfo;
378         int ret = AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
379         if (ret != 0) {
380             LOGE("failed to get native token info, result = %{public}d", ret);
381             return "";
382         }
383         return nativeTokenInfo.processName;
384     }
385     LOGE("failed to get app name");
386     return "";
387 }
388 
HasPermission(const std::string & permission)389 int32_t SecurityCollectorManagerService::HasPermission(const std::string &permission)
390 {
391     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
392     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permission);
393     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
394         return NO_PERMISSION;
395     }
396 
397     return SUCCESS;
398 }
399 
Mute(const SecurityCollectorEventFilter & subscribeMute,const std::string & callbackFlag)400 int32_t SecurityCollectorManagerService::Mute(const SecurityCollectorEventFilter &subscribeMute,
401     const std::string &callbackFlag)
402 {
403     LOGI("In SecurityCollectorManagerService Mute");
404     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
405     if (ret != SUCCESS) {
406         LOGE("caller no permission");
407         return ret;
408     }
409     if (!DataCollection::GetInstance().Mute(subscribeMute.GetMuteFilter(), callbackFlag)) {
410         LOGE("fail to set mute");
411         return FAILED;
412     }
413     return SUCCESS;
414 }
415 
Unmute(const SecurityCollectorEventFilter & subscribeMute,const std::string & callbackFlag)416 int32_t SecurityCollectorManagerService::Unmute(const SecurityCollectorEventFilter &subscribeMute,
417     const std::string &callbackFlag)
418 {
419     LOGI("In SecurityCollectorManagerService Unmute");
420     int32_t ret = HasPermission(QUERY_EVENT_PERMISSION);
421     if (ret != SUCCESS) {
422         LOGE("caller no permission");
423         return ret;
424     }
425     if (!DataCollection::GetInstance().Unmute(subscribeMute.GetMuteFilter(), callbackFlag)) {
426         LOGE("fail to set unmute");
427         return FAILED;
428     }
429     return SUCCESS;
430 }
431 }