• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 "data_collect_manager_service.h"
17 #include <cstdio>
18 #include <thread>
19 #include <vector>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <cinttypes>
24 #include <unistd.h>
25 #include <unordered_set>
26 #include "accesstoken_kit.h"
27 #include "tokenid_kit.h"
28 #include "ipc_skeleton.h"
29 #include "string_ex.h"
30 #include "directory_ex.h"
31 #include "file_ex.h"
32 #include "acquire_data_subscribe_manager.h"
33 #include "bigdata.h"
34 #include "collector_manager.h"
35 #include "config_data_manager.h"
36 #include "data_collect_manager_callback_proxy.h"
37 #include "data_collect_manager.h"
38 #include "data_format.h"
39 #include "database_manager.h"
40 #include "data_collection.h"
41 #include "model_cfg_marshalling.h"
42 #include "security_guard_define.h"
43 #include "security_guard_log.h"
44 #include "security_guard_utils.h"
45 #include "system_ability_definition.h"
46 #include "ffrt.h"
47 #include "config_manager.h"
48 #include "risk_event_rdb_helper.h"
49 #include "file_system_store_helper.h"
50 #include "config_subscriber.h"
51 #include "model_manager.h"
52 #include "config_define.h"
53 #ifdef SECURITY_GUARD_TRIM_MODEL_ANALYSIS
54 #include "event_group_config.h"
55 #endif
56 
57 namespace OHOS::Security::SecurityGuard {
58 namespace {
59     constexpr int32_t TWO_ARGS = 2;
60     constexpr int32_t TIMEOUT_REPLY = 10000;
61     const std::string REPORT_PERMISSION = "ohos.permission.securityguard.REPORT_SECURITY_INFO";
62     const std::string REPORT_PERMISSION_NEW = "ohos.permission.REPORT_SECURITY_EVENT";
63     const std::string REQUEST_PERMISSION = "ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO";
64     const std::string MANAGE_CONFIG_PERMISSION = "ohos.permission.MANAGE_SECURITY_GUARD_CONFIG";
65     const std::string QUERY_SECURITY_EVENT_PERMISSION = "ohos.permission.QUERY_SECURITY_EVENT";
66     constexpr int32_t CFG_FILE_MAX_SIZE = 1 * 1024 * 1024;
67     constexpr int32_t CFG_FILE_BUFF_SIZE = 1 * 1024 * 1024 + 1;
68     const std::unordered_map<std::string, std::vector<std::string>> g_apiPermissionsMap {
69         {"RequestDataSubmit", {REPORT_PERMISSION, REPORT_PERMISSION_NEW}},
70         {"QuerySecurityEvent", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
71         {"CollectorStart", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
72         {"CollectorStop", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
73         {"Subscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
74         {"UnSubscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
75         {"ConfigUpdate", {MANAGE_CONFIG_PERMISSION}},
76         {"QuerySecurityEventConfig", {MANAGE_CONFIG_PERMISSION}},
77         {"Mute", {QUERY_SECURITY_EVENT_PERMISSION}},
78         {"Unmute", {QUERY_SECURITY_EVENT_PERMISSION}},
79     };
80     std::unordered_set<std::string> g_configCacheFilesSet;
81     constexpr uint32_t FINISH = 0;
82     constexpr uint32_t CONTINUE = 1;
83     constexpr size_t MAX_DISTRIBUTE_LENS = 100;
84     constexpr uint64_t CLEAR_TIME = 3600000000;
85     constexpr uint32_t FFRT_MAX_NUM = 256;
86     std::string TRUST_LIST_FILE_PATH_PRE = "/system/etc/";
87     const std::string TRUST_LIST_FILE_PATH = TRUST_LIST_FILE_PATH_PRE + SECURITY_GUARD_CONFIG_UPDATE_TRUST_LIST_SOURCE;
88 }
89 
90 REGISTER_SYSTEM_ABILITY_BY_ID(DataCollectManagerService, DATA_COLLECT_MANAGER_SA_ID, true);
91 
DataCollectManagerService(int32_t saId,bool runOnCreate)92 DataCollectManagerService::DataCollectManagerService(int32_t saId, bool runOnCreate)
93     : SystemAbility(saId, runOnCreate)
94 {
95     SGLOGW("%{public}s", __func__);
96 }
97 
OnStart()98 void DataCollectManagerService::OnStart()
99 {
100     SGLOGI("%{public}s", __func__);
101     DatabaseManager::GetInstance().Init(); // Make sure the database is ready
102 
103     AddSystemAbilityListener(RISK_ANALYSIS_MANAGER_SA_ID);
104     AddSystemAbilityListener(DFX_SYS_HIVIEW_ABILITY_ID);
105     bool success = ConfigManager::InitConfig<EventConfig>();
106     if (!success) {
107         SGLOGE("init event config error");
108     }
109 #ifdef SECURITY_GUARD_TRIM_MODEL_ANALYSIS
110     success = ConfigManager::InitConfig<EventGroupConfig>();
111     if (!success) {
112         SGLOGE("init event group config error");
113     }
114 #endif
115     std::vector<int64_t> eventIds = ConfigDataManager::GetInstance().GetAllEventIds();
116     std::vector<int64_t> onStartEventList;
117     for (int64_t eventId : eventIds) {
118         EventCfg eventCfg;
119         bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(eventId, eventCfg);
120         if (!isSuccess) {
121             SGLOGI("GetEventConfig error");
122         } else if (eventCfg.collectOnStart == 1) {
123             onStartEventList.push_back(eventId);
124         }
125     }
126     SecurityCollector::DataCollection::GetInstance().SecurityGuardSubscribeCollector(onStartEventList);
127     if (!Publish(this)) {
128         SGLOGE("Publish error");
129         return;
130     }
131 }
132 
OnStop()133 void DataCollectManagerService::OnStop()
134 {
135     SecurityCollector::DataCollection::GetInstance().CloseLib();
136 }
137 
138 
Dump(int fd,const std::vector<std::u16string> & args)139 int DataCollectManagerService::Dump(int fd, const std::vector<std::u16string>& args)
140 {
141     SGLOGI("DataCollectManagerService Dump");
142     if (fd < 0) {
143         return BAD_PARAM;
144     }
145 
146     std::string arg0 = ((args.size() == 0) ? "" : Str16ToStr8(args.at(0)));
147     if (arg0.compare("-h") == 0) {
148         dprintf(fd, "Usage:\n");
149         dprintf(fd, "       -h: command help\n");
150         dprintf(fd, "       -i <EVENT_ID>: dump special eventId\n");
151     } else if (arg0.compare("-i") == 0) {
152         if (args.size() < TWO_ARGS) {
153             return BAD_PARAM;
154         }
155 
156         int64_t eventId;
157         bool isSuccess = SecurityGuardUtils::StrToI64(Str16ToStr8(args.at(1)), eventId);
158         if (!isSuccess) {
159             return BAD_PARAM;
160         }
161 
162         DumpEventInfo(fd, eventId);
163     }
164     return ERR_OK;
165 }
166 
DumpEventInfo(int fd,int64_t eventId)167 void DataCollectManagerService::DumpEventInfo(int fd, int64_t eventId)
168 {
169     SecEvent secEvent;
170     int code = DatabaseManager::GetInstance().QueryRecentEventByEventId(eventId, secEvent);
171     if (code != SUCCESS) {
172         SGLOGE("query event error, code=%{public}d", code);
173         return;
174     }
175     dprintf(fd, "eventId : %ld\n", secEvent.eventId);
176     dprintf(fd, "report time : %s\n", secEvent.date.c_str());
177     dprintf(fd, "report version : %s\n", secEvent.version.c_str());
178 }
179 
IsDiscardEventInThisHour(int64_t eventId)180 bool DataCollectManagerService::IsDiscardEventInThisHour(int64_t eventId)
181 {
182     std::lock_guard<std::mutex> lock(eventsMutex_);
183     {
184         if (reportedEventsMap_.size() == 0) {
185             auto clearTask = [&] () mutable {
186                 std::lock_guard<std::mutex> lock(eventsMutex_);
187                 reportedEventsMap_.clear();
188                 SGLOGI("clear reportedEventsMap_");
189             };
190             ffrt::submit(clearTask, {}, {}, ffrt::task_attr().delay(CLEAR_TIME));
191         }
192         if (reportedEventsMap_.count(eventId) != 0) {
193             EventCfg config;
194             bool success = ConfigDataManager::GetInstance().GetEventConfig(eventId, config);
195             if (!success) {
196                 SGLOGE("not found event, id=%{public}" PRId64, eventId);
197                 return true;
198             }
199             if (reportedEventsMap_[eventId].load() >= config.storageRomNums) {
200                 SGLOGD("event is reported too much in this hour, eventid is %{public}" PRId64, eventId);
201                 return true;
202             }
203             reportedEventsMap_[eventId]++;
204         } else {
205             reportedEventsMap_[eventId] = 1;
206         }
207     }
208     return false;
209 }
210 
RequestDataSubmit(int64_t eventId,std::string & version,std::string & time,std::string & content,bool isSync)211 int32_t DataCollectManagerService::RequestDataSubmit(int64_t eventId, std::string &version, std::string &time,
212     std::string &content, bool isSync)
213 {
214     SGLOGD("enter DataCollectManagerService RequestDataSubmit");
215     SGLOGD("isSync: %{public}s", isSync ? "true" : "false");
216     int32_t ret = IsApiHasPermission("RequestDataSubmit");
217     if (ret != SUCCESS) {
218         return ret;
219     }
220     if (!DataFormat::CheckRiskContent(content)) {
221         SGLOGE("CheckRiskContent error");
222         return BAD_PARAM;
223     }
224     SGLOGD("eventId=%{public}" PRId64 ", version=%{public}s, date=%{public}s", eventId, version.c_str(), time.c_str());
225     SecEvent event {
226         .eventId = eventId,
227         .version = version,
228         .date = time,
229         .content = content
230     };
231     auto task = [&, event] () mutable {
232         taskCount_++;
233         int code = DatabaseManager::GetInstance().InsertEvent(USER_SOURCE, event, {});
234         if (code != SUCCESS) {
235             SGLOGE("insert event error, %{public}d", code);
236         }
237         SGLOGD("ffrt task num is %{public}u", taskCount_.load());
238         taskCount_--;
239     };
240     if (taskCount_.load() > FFRT_MAX_NUM) {
241         discardedCount_++;
242         SGLOGD("too much event reported, ffrt task num is %{public}u, eventid is %{public}" PRId64,
243             discardedCount_.load(), eventId);
244         return SUCCESS;
245     }
246     if (IsDiscardEventInThisHour(eventId)) {
247         return SUCCESS;
248     }
249     ffrt::submit(task);
250     return SUCCESS;
251 }
252 
RequestRiskData(std::string & devId,std::string & eventList,const sptr<IRemoteObject> & callback)253 int32_t DataCollectManagerService::RequestRiskData(std::string &devId, std::string &eventList,
254     const sptr<IRemoteObject> &callback)
255 {
256     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
257     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, REQUEST_PERMISSION);
258     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
259         SGLOGE("caller no permission");
260         return NO_PERMISSION;
261     }
262     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
263     if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
264         uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
265         if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
266             SGLOGE("not system app no permission");
267             return NO_SYSTEMCALL;
268         }
269     }
270     ObtainDataEvent event;
271     auto pid = IPCSkeleton::GetCallingPid();
272     event.pid = pid;
273     event.time = SecurityGuardUtils::GetDate();
274     SGLOGI("eventList=%{public}s", eventList.c_str());
275     auto promise = std::make_shared<std::promise<int32_t>>();
276     auto future = promise->get_future();
277     PushDataCollectTask(callback, eventList, devId, promise);
278     std::chrono::milliseconds span(TIMEOUT_REPLY);
279     if (future.wait_for(span) == std::future_status::timeout) {
280         SGLOGE("wait for result timeout");
281         event.size = 0;
282     } else {
283         event.size = future.get();
284     }
285     SGLOGI("ReportObtainDataEvent");
286     BigData::ReportObtainDataEvent(event);
287     return SUCCESS;
288 }
289 
GetSecEventsFromConditions(RequestCondition & condition)290 std::vector<SecEvent> DataCollectManagerService::GetSecEventsFromConditions(RequestCondition &condition)
291 {
292     std::vector<SecEvent> events {};
293     if (condition.beginTime.empty() && condition.endTime.empty()) {
294         (void) DatabaseManager::GetInstance().QueryEventByEventId(RISK_TABLE, condition.riskEvent, events);
295     } else {
296         (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, condition.riskEvent, events,
297             condition.beginTime, condition.endTime);
298     }
299     return events;
300 }
301 
PushDataCollectTask(const sptr<IRemoteObject> & object,std::string conditions,std::string devId,std::shared_ptr<std::promise<int32_t>> promise)302 void DataCollectManagerService::PushDataCollectTask(const sptr<IRemoteObject> &object,
303     std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)
304 {
305     auto task = [object, conditions, devId, promise] () mutable {
306         auto proxy = iface_cast<DataCollectManagerCallbackProxy>(object);
307         if (proxy == nullptr) {
308             promise->set_value(0);
309             return;
310         }
311         RequestCondition reqCondition {};
312         DataFormat::ParseConditions(conditions, reqCondition);
313         if (reqCondition.riskEvent.empty() && reqCondition.auditEvent.empty()) {
314             SGLOGE("reqCondition no permission");
315             std::string empty;
316             proxy->ResponseRiskData(devId, empty, FINISH);
317             promise->set_value(0);
318             return;
319         }
320 
321         std::vector<SecEvent> events = GetSecEventsFromConditions(reqCondition);
322         size_t curIndex = 0;
323         size_t lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
324         size_t maxIndex = events.size();
325         promise->set_value(maxIndex);
326         SGLOGI("events size=%{public}zu", maxIndex);
327         std::vector<SecEvent> dispatchVec;
328         while (lastIndex < maxIndex) {
329             dispatchVec.assign(events.begin() + curIndex, events.begin() + lastIndex);
330             std::string dispatch = nlohmann::json(dispatchVec).dump();
331             SGLOGD("dispatch size=%{public}zu", dispatch.size());
332             (void) proxy->ResponseRiskData(devId, dispatch, CONTINUE);
333             curIndex = lastIndex;
334             lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
335         }
336 
337         // last dispatch
338         dispatchVec.assign(events.begin() + curIndex, events.end());
339         std::string dispatch = nlohmann::json(dispatchVec).dump();
340         (void) proxy->ResponseRiskData(devId, dispatch, FINISH);
341         SGLOGI("ResponseRiskData FINISH");
342     };
343     ffrt::submit(task);
344 }
345 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)346 void DataCollectManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
347 {
348     SGLOGI("OnAddSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
349 }
350 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)351 void DataCollectManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
352 {
353     SGLOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
354 }
355 
Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)356 int32_t DataCollectManagerService::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
357     const sptr<IRemoteObject> &callback)
358 {
359     SGLOGD("DataCollectManagerService, start subscribe");
360     int32_t ret = FAILED;
361     SgSubscribeEvent event;
362     event.pid = IPCSkeleton::GetCallingPid();
363     event.time = SecurityGuardUtils::GetDate();
364     event.eventId = subscribeInfo.GetEvent().eventId;
365     if (subscribeInfo.GetEventGroup() == "") {
366         ret = IsApiHasPermission("Subscribe");
367     } else {
368         ret = IsEventGroupHasPermission(subscribeInfo.GetEventGroup(),
369             std::vector<int64_t>{subscribeInfo.GetEvent().eventId});
370     }
371     if (ret != SUCCESS) {
372         event.ret = ret;
373         BigData::ReportSgSubscribeEvent(event);
374         return ret;
375     }
376     ret = SetDeathCallBack(event, callback);
377     if (ret != SUCCESS) {
378         return ret;
379     }
380     ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(subscribeInfo, callback);
381     event.ret = ret;
382     SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64, event.eventId);
383     BigData::ReportSgSubscribeEvent(event);
384     return ret;
385 }
386 
Unsubscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)387 int32_t DataCollectManagerService::Unsubscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
388     const sptr<IRemoteObject> &callback)
389 {
390     int32_t ret = FAILED;
391     SgUnsubscribeEvent event;
392     event.pid = IPCSkeleton::GetCallingPid();
393     event.time = SecurityGuardUtils::GetDate();
394     if (subscribeInfo.GetEventGroup() == "") {
395         ret = IsApiHasPermission("Subscribe");
396     } else {
397         ret = IsEventGroupHasPermission(subscribeInfo.GetEventGroup(),
398             std::vector<int64_t>{subscribeInfo.GetEvent().eventId});
399     }
400     if (ret != SUCCESS) {
401         event.ret = ret;
402         BigData::ReportSgUnsubscribeEvent(event);
403         return ret;
404     }
405     std::lock_guard<std::mutex> lock(mutex_);
406     if (deathRecipient_ != nullptr) {
407         callback->RemoveDeathRecipient(deathRecipient_);
408     }
409 
410     ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(subscribeInfo.GetEvent().eventId, callback);
411     event.ret = ret;
412     SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
413     BigData::ReportSgUnsubscribeEvent(event);
414     return ret;
415 }
416 
QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,SecurityCollector::SecurityEventRuler ruler)417 bool DataCollectManagerService::QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,
418     SecurityCollector::SecurityEventRuler ruler)
419 {
420     EventCfg config;
421     bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(ruler.GetEventId(), config);
422     if (!isSuccess) {
423         SGLOGE("GetEventConfig error, eventId is 0x%{public}" PRIx64, ruler.GetEventId());
424         return false;
425     }
426     std::vector<SecurityCollector::SecurityEvent> replyEvents;
427     std::vector<int64_t> eventIds{ruler.GetEventId()};
428     SGLOGD("eventType is %{public}u", config.eventType);
429     if (config.eventType == 1) { // query in collector
430         int32_t code = SecurityCollector::CollectorManager::GetInstance().QuerySecurityEvent(
431             {ruler}, replyEvents);
432         if (code != SUCCESS) {
433             return false;
434         }
435         proxy->OnQuery(replyEvents);
436     } else if (config.dbTable == FILE_SYSTEM) {
437         (void) FileSystemStoreHelper::GetInstance().QuerySecurityEvent(ruler, proxy);
438     } else {
439         std::vector<SecEvent> events;
440         if (ruler.GetBeginTime().empty() && ruler.GetEndTime().empty()) {
441             (void) DatabaseManager::GetInstance().QueryEventByEventId(ruler.GetEventId(), events);
442         } else {
443             (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, eventIds, events,
444                 ruler.GetBeginTime(), ruler.GetEndTime());
445         }
446         std::transform(events.begin(), events.end(),
447             std::back_inserter(replyEvents), [] (SecEvent event) {
448             return SecurityCollector::SecurityEvent(event.eventId, event.version, event.content, event.date);
449         });
450         proxy->OnQuery(replyEvents);
451     }
452     return true;
453 }
454 
QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,const sptr<IRemoteObject> & callback,const std::string & eventGroup)455 int32_t DataCollectManagerService::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
456     const sptr<IRemoteObject> &callback, const std::string &eventGroup)
457 {
458     SGLOGI("enter DataCollectManagerService QuerySecurityEvent");
459     int32_t ret = 0;
460     if (eventGroup == "") {
461         ret = IsApiHasPermission("QuerySecurityEvent");
462     } else {
463         ret = IsEventGroupHasPermission(eventGroup, std::vector<int64_t>{});
464     }
465     if (ret != SUCCESS) {
466         return ret;
467     }
468     auto proxy = iface_cast<ISecurityEventQueryCallback>(callback);
469     if (proxy == nullptr) {
470         SGLOGI("proxy is null");
471         return NULL_OBJECT;
472     }
473     auto task = [proxy, rulers, eventGroup] {
474         std::string errEventIds;
475         EventGroupCfg config {};
476         if (!ConfigDataManager::GetInstance().GetEventGroupConfig(eventGroup, config)) {
477             SGLOGE("get event group config fail group = %{public}s", eventGroup.c_str());
478             return;
479         }
480         for (auto &ruler : rulers) {
481             if (config.eventList.count(ruler.GetEventId()) == 0) {
482                 SGLOGE("eventid not in eventid list");
483                 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
484                 continue;
485             }
486             if (!QueryEventByRuler(proxy, ruler)) {
487                 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
488             }
489         }
490         if (!errEventIds.empty()) {
491             std::string message = "QuerySecurityEvent " + errEventIds + "failed";
492             SGLOGE("QuerySecurityEvent failed");
493             proxy->OnError(message);
494             return;
495         }
496         proxy->OnComplete();
497     };
498     ffrt::submit(task);
499     return SUCCESS;
500 }
501 
OnRemoteDied(const wptr<IRemoteObject> & remote)502 void DataCollectManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
503 {
504     SGLOGI("enter OnRemoteDied");
505     if (remote == nullptr) {
506         SGLOGE("remote object is nullptr");
507         return;
508     }
509 
510     sptr<IRemoteObject> object = remote.promote();
511     if (object == nullptr) {
512         SGLOGE("object is nullptr");
513         return;
514     }
515     sptr<DataCollectManagerService> service = service_.promote();
516     if (service == nullptr) {
517         SGLOGE("service is nullptr");
518         return;
519     }
520     AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecordOnRemoteDied(object);
521     if (object->IsProxyObject() && service->deathRecipient_ != nullptr) {
522         object->RemoveDeathRecipient(service->deathRecipient_);
523     }
524     SGLOGI("end OnRemoteDied");
525 }
526 
CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)527 int32_t DataCollectManagerService::CollectorStart(
528     const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)
529 {
530     SGLOGI("enter DataCollectManagerService CollectorStart.");
531     int32_t code = IsApiHasPermission("CollectorStart");
532     if (code != SUCCESS) {
533         return code;
534     }
535     code = SecurityCollector::CollectorManager::GetInstance().CollectorStart(subscribeInfo);
536     if (code != SUCCESS) {
537         SGLOGI("CollectorStart failed, code=%{public}d", code);
538         return code;
539     }
540     return SUCCESS;
541 }
542 
CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)543 int32_t DataCollectManagerService::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
544     const sptr<IRemoteObject> &callback)
545 {
546     SGLOGI("enter DataCollectManagerService CollectorStop.");
547     int32_t code = IsApiHasPermission("CollectorStop");
548     if (code != SUCCESS) {
549         return code;
550     }
551     code = SecurityCollector::CollectorManager::GetInstance().CollectorStop(subscribeInfo);
552     if (code != SUCCESS) {
553         SGLOGI("CollectorStop failed, code=%{public}d", code);
554         return code;
555     }
556     return SUCCESS;
557 }
558 
IsApiHasPermission(const std::string & api)559 int32_t DataCollectManagerService::IsApiHasPermission(const std::string &api)
560 {
561     if (g_apiPermissionsMap.count(api) == 0) {
562         SGLOGE("api not in map");
563         return FAILED;
564     }
565     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
566     if (std::any_of(g_apiPermissionsMap.at(api).cbegin(), g_apiPermissionsMap.at(api).cend(),
567         [callerToken](const std::string &per) {
568         int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
569         return code == AccessToken::PermissionState::PERMISSION_GRANTED;
570     })) {
571         AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
572         if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
573             uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
574             if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
575                 SGLOGE("not system app no permission");
576                 return NO_SYSTEMCALL;
577             }
578         }
579         return SUCCESS;
580     }
581     SGLOGE("caller no permission");
582     return NO_PERMISSION;
583 }
584 
IsEventGroupHasPermission(const std::string & eventGroup,std::vector<int64_t> eventIds)585 int32_t DataCollectManagerService::IsEventGroupHasPermission(const std::string &eventGroup,
586     std::vector<int64_t> eventIds)
587 {
588     EventGroupCfg config {};
589     if (!ConfigDataManager::GetInstance().GetEventGroupConfig(eventGroup, config)) {
590         SGLOGE("get event group config fail group = %{public}s", eventGroup.c_str());
591         return BAD_PARAM;
592     }
593     for (int64_t eventId : eventIds) {
594         if (config.eventList.count(eventId) == 0) {
595             SGLOGE("eventid not in eventid list");
596             return BAD_PARAM;
597         }
598     }
599     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
600     if (std::any_of(config.permissionList.cbegin(), config.permissionList.cend(),
601         [callerToken](const std::string &per) {
602         int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
603         return code == AccessToken::PermissionState::PERMISSION_GRANTED;
604     })) {
605         AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
606         if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
607             uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
608             if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
609                 SGLOGE("not system app no permission");
610                 return NO_SYSTEMCALL;
611             }
612         }
613         return SUCCESS;
614     }
615     SGLOGE("caller no permission");
616     return NO_PERMISSION;
617 }
618 
WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo & info,const std::string & realPath)619 bool DataCollectManagerService::WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo &info,
620     const std::string &realPath)
621 {
622     int32_t fd = info.GetFd();
623     int32_t outputFd = dup(fd);
624     close(fd);
625     if (outputFd == -1) {
626         SGLOGE("dup fd fail reason %{public}s", strerror(errno));
627         return FAILED;
628     }
629     int32_t inputFd = open(realPath.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
630     if (inputFd < 0) {
631         close(outputFd);
632         SGLOGE("open file fail reason %{public}s", strerror(errno));
633         return FAILED;
634     }
635     auto buffer = std::make_unique<char[]> (CFG_FILE_BUFF_SIZE);
636     int offset = -1;
637     while ((offset = read(outputFd, buffer.get(), CFG_FILE_BUFF_SIZE)) > 0) {
638         if (offset > CFG_FILE_MAX_SIZE) {
639             close(outputFd);
640             close(inputFd);
641             SGLOGE("file is empty or too large, len = %{public}d", offset);
642             return BAD_PARAM;
643         }
644         if (write(inputFd, buffer.get(), offset) < 0) {
645             close(inputFd);
646             close(outputFd);
647             SGLOGE("write file to the tmp dir failed");
648             return FAILED;
649         }
650     }
651     close(inputFd);
652     fsync(outputFd);
653     close(outputFd);
654     return SUCCESS;
655 }
656 
ParseTrustListFile(const std::string & trustListFile)657 bool DataCollectManagerService::ParseTrustListFile(const std::string &trustListFile)
658 {
659     if (trustListFile.empty()) {
660         SGLOGE("path is empty");
661         return false;
662     }
663     std::ifstream stream(trustListFile, std::ios::in);
664     if (!stream.is_open()) {
665         SGLOGE("stream error");
666         return false;
667     }
668     stream.seekg(0, std::ios::end);
669     std::ios::pos_type cfgFileMaxSize = 1 * 1024 * 1024;
670     std::ios::pos_type len = stream.tellg();
671     if (len == 0 || len > cfgFileMaxSize) {
672         SGLOGE("stream is empty or too large");
673         stream.close();
674         return false;
675     }
676     stream.seekg(0, std::ios_base::beg);
677     nlohmann::json jsonObj = nlohmann::json::parse(stream, nullptr, false);
678     stream.close();
679     if (jsonObj.is_discarded()) {
680         SGLOGE("json is discarded");
681         return false;
682     }
683 
684     if (!jsonObj.contains("trust_list_config") || !jsonObj["trust_list_config"].is_array()) {
685         return false;
686     }
687 
688     for (const auto &ele : jsonObj["trust_list_config"]) {
689         if (!ele.contains("name")) {
690             return false;
691         }
692         g_configCacheFilesSet.emplace(ele["name"]);
693     }
694 
695     return true;
696 }
697 
ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo & info)698 int32_t DataCollectManagerService::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &info)
699 {
700     SGLOGI("enter DataCollectManagerService ConfigUpdate.");
701     int32_t code = IsApiHasPermission("ConfigUpdate");
702     if (code != SUCCESS) {
703         return code;
704     }
705     if (!ParseTrustListFile(TRUST_LIST_FILE_PATH)) {
706         return BAD_PARAM;
707     }
708     if (g_configCacheFilesSet.empty() || !g_configCacheFilesSet.count(info.GetFileName())) {
709         return BAD_PARAM;
710     }
711     const std::string &realPath = CONFIG_ROOT_PATH + "tmp/" + info.GetFileName();
712     SGLOGI("config file is %{public}s, fd is %{public}d", realPath.c_str(), info.GetFd());
713     std::string tmpPath = realPath + ".t";
714     int32_t ret = WriteRemoteFileToLocal(info, tmpPath);
715     if (ret != SUCCESS) {
716         SGLOGE("write remote file to local fail");
717         return ret;
718     }
719     if (rename(tmpPath.c_str(), realPath.c_str()) != 0) {
720         SGLOGE("remote file rename fail");
721         (void)unlink(tmpPath.c_str());
722         return FAILED;
723     }
724     (void)unlink(tmpPath.c_str());
725 
726     if (!ConfigSubscriber::UpdateConfig(realPath)) {
727         SGLOGE("update config fail");
728         return FAILED;
729     }
730     return SUCCESS;
731 }
732 
QueryEventConfig(std::string & result)733 int32_t DataCollectManagerService::QueryEventConfig(std::string &result)
734 {
735     SGLOGI("Start DataCollectManagerService::QueryEventConfig");
736     std::vector<EventCfg> eventConfigs = ConfigDataManager::GetInstance().GetAllEventConfigs();
737     nlohmann::json resultObj = nlohmann::json::array();
738     for (const auto& event : eventConfigs) {
739         nlohmann::json jObject;
740         jObject["eventId"] = event.eventId;
741         jObject["eventName"] = event.eventName;
742         jObject["version"] = event.version;
743         jObject["eventType"] = event.eventType;
744         jObject["collectOnStart"] = event.collectOnStart;
745         jObject["dataSensitivityLevel"] = event.dataSensitivityLevel;
746         jObject["storageRamNums"] = event.storageRamNums;
747         jObject["storageRomNums"] = event.storageRomNums;
748         jObject["storageTime"] = event.storageTime;
749         jObject["owner"] = event.owner;
750         jObject["source"] = event.source;
751         jObject["dbTable"] = event.dbTable;
752         jObject["prog"] = event.prog;
753         resultObj.push_back(jObject);
754     }
755     result = resultObj.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
756     return SUCCESS;
757 }
758 
QuerySecurityEventConfig(std::string & result)759 int32_t DataCollectManagerService::QuerySecurityEventConfig(std::string &result)
760 {
761     SGLOGI("enter QuerySecurityEventConfig");
762     int32_t ret = IsApiHasPermission("QuerySecurityEventConfig");
763     if (ret != SUCCESS) {
764         return ret;
765     }
766     return QueryEventConfig(result);
767 }
768 
Mute(const SecurityEventFilter & subscribeMute,const sptr<IRemoteObject> & callback,const std::string & sdkFlag)769 int32_t DataCollectManagerService::Mute(const SecurityEventFilter &subscribeMute,
770     const sptr<IRemoteObject> &callback, const std::string &sdkFlag)
771 {
772     SGLOGI("enter DataCollectManagerService Mute.");
773     SgSubscribeEvent event;
774     event.pid = IPCSkeleton::GetCallingPid();
775     event.time = SecurityGuardUtils::GetDate();
776     event.eventId = subscribeMute.GetMuteFilter().eventId;
777     if (subscribeMute.GetMuteFilter().eventGroup == "") {
778         SGLOGE("event group empty");
779         event.ret = BAD_PARAM;
780         BigData::ReportSetMuteEvent(event);
781         return BAD_PARAM;
782     }
783     int32_t ret = IsEventGroupHasPermission(subscribeMute.GetMuteFilter().eventGroup,
784         std::vector<int64_t>{subscribeMute.GetMuteFilter().eventId});
785     if (ret != SUCCESS) {
786         event.ret = ret;
787         BigData::ReportSetMuteEvent(event);
788         return ret;
789     }
790     ret = SetDeathCallBack(event, callback);
791     if (ret != SUCCESS) {
792         return ret;
793     }
794     ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeMute(subscribeMute, callback, sdkFlag);
795     event.ret = ret;
796     BigData::ReportSetMuteEvent(event);
797     return ret;
798 }
799 
Unmute(const SecurityEventFilter & subscribeMute,const sptr<IRemoteObject> & callback,const std::string & sdkFlag)800 int32_t DataCollectManagerService::Unmute(const SecurityEventFilter &subscribeMute,
801     const sptr<IRemoteObject> &callback, const std::string &sdkFlag)
802 {
803     SGLOGI("enter DataCollectManagerService Unmute.");
804     SgSubscribeEvent event;
805     event.pid = IPCSkeleton::GetCallingPid();
806     event.time = SecurityGuardUtils::GetDate();
807     event.eventId = subscribeMute.GetMuteFilter().eventId;
808     if (subscribeMute.GetMuteFilter().eventGroup == "") {
809         SGLOGE("event group empty");
810         event.ret = BAD_PARAM;
811         BigData::ReportSetUnMuteEvent(event);
812         return BAD_PARAM;
813     }
814     int32_t ret = IsEventGroupHasPermission(subscribeMute.GetMuteFilter().eventGroup,
815         std::vector<int64_t>{subscribeMute.GetMuteFilter().eventId});
816     if (ret != SUCCESS) {
817         event.ret = ret;
818         BigData::ReportSetUnMuteEvent(event);
819         return ret;
820     }
821     ret = SetDeathCallBack(event, callback);
822     if (ret != SUCCESS) {
823         return ret;
824     }
825     ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeMute(subscribeMute, callback, sdkFlag);
826     event.ret = ret;
827     BigData::ReportSetUnMuteEvent(event);
828     return ret;
829 }
830 
SetDeathCallBack(SgSubscribeEvent event,const sptr<IRemoteObject> & callback)831 int32_t DataCollectManagerService::SetDeathCallBack(SgSubscribeEvent event, const sptr<IRemoteObject> &callback)
832 {
833     if (deathRecipient_ == nullptr) {
834         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
835         if (deathRecipient_ == nullptr) {
836             SGLOGE("no memory");
837             event.ret = NULL_OBJECT;
838             BigData::ReportSgSubscribeEvent(event);
839             return NULL_OBJECT;
840         }
841     }
842     callback->AddDeathRecipient(deathRecipient_);
843     return SUCCESS;
844 }
845 }