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