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 "acquire_data_subscribe_manager.h"
32 #include "bigdata.h"
33 #include "collector_manager.h"
34 #include "config_data_manager.h"
35 #include "data_collect_manager_callback_proxy.h"
36 #include "data_collect_manager.h"
37 #include "data_format.h"
38 #include "database_manager.h"
39 #include "data_collection.h"
40 #include "model_cfg_marshalling.h"
41 #include "security_guard_define.h"
42 #include "security_guard_log.h"
43 #include "security_guard_utils.h"
44 #include "system_ability_definition.h"
45 #include "ffrt.h"
46 #include "config_manager.h"
47 #include "risk_event_rdb_helper.h"
48 #include "config_subscriber.h"
49 #include "model_manager.h"
50 namespace OHOS::Security::SecurityGuard {
51 namespace {
52     constexpr int32_t TWO_ARGS = 2;
53     constexpr int32_t TIMEOUT_REPLY = 10000;
54     const std::string REPORT_PERMISSION = "ohos.permission.securityguard.REPORT_SECURITY_INFO";
55     const std::string REPORT_PERMISSION_NEW = "ohos.permission.REPORT_SECURITY_EVENT";
56     const std::string REQUEST_PERMISSION = "ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO";
57     const std::string MANAGE_CONFIG_PERMISSION = "ohos.permission.MANAGE_SECURITY_GUARD_CONFIG";
58     const std::string QUERY_SECURITY_EVENT_PERMISSION = "ohos.permission.QUERY_SECURITY_EVENT";
59     constexpr int32_t CFG_FILE_MAX_SIZE = 1 * 1024 * 1024;
60     constexpr int32_t CFG_FILE_BUFF_SIZE = 1 * 1024 * 1024 + 1;
61     const std::unordered_map<std::string, std::vector<std::string>> g_apiPermissionsMap {
62         {"RequestDataSubmit", {REPORT_PERMISSION, REPORT_PERMISSION_NEW}},
63         {"QuerySecurityEvent", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
64         {"CollectorStart", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
65         {"CollectorStop", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
66         {"Subscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
67         {"UnSubscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
68         {"ConfigUpdate", {MANAGE_CONFIG_PERMISSION}},
69         {"QuerySecurityEventConfig", {MANAGE_CONFIG_PERMISSION}},
70     };
71 
72     const std::string TRUST_LIST_FILE_PATH = "/system/etc/config_update_trust_list.json";
73     std::unordered_set<std::string> g_configCacheFilesSet;
74     constexpr uint32_t FINISH = 0;
75     constexpr uint32_t CONTINUE = 1;
76     constexpr size_t MAX_DISTRIBUTE_LENS = 100;
77 }
78 
79 REGISTER_SYSTEM_ABILITY_BY_ID(DataCollectManagerService, DATA_COLLECT_MANAGER_SA_ID, true);
80 
DataCollectManagerService(int32_t saId, bool runOnCreate)81 DataCollectManagerService::DataCollectManagerService(int32_t saId, bool runOnCreate)
82     : SystemAbility(saId, runOnCreate)
83 {
84     SGLOGW("%{public}s", __func__);
85 }
86 
OnStart()87 void DataCollectManagerService::OnStart()
88 {
89     SGLOGI("%{public}s", __func__);
90     DatabaseManager::GetInstance().Init(); // Make sure the database is ready
91 
92     AddSystemAbilityListener(RISK_ANALYSIS_MANAGER_SA_ID);
93     AddSystemAbilityListener(DFX_SYS_HIVIEW_ABILITY_ID);
94     bool success = ConfigManager::InitConfig<EventConfig>();
95         if (!success) {
96         SGLOGE("init event config error");
97     }
98     std::vector<int64_t> eventIds = ConfigDataManager::GetInstance().GetAllEventIds();
99     std::vector<int64_t> onStartEventList;
100     for (int64_t eventId : eventIds) {
101         EventCfg eventCfg;
102         bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(eventId, eventCfg);
103         if (!isSuccess) {
104             SGLOGI("GetEventConfig error");
105         } else if (eventCfg.collectOnStart == 1) {
106             onStartEventList.push_back(eventId);
107         }
108     }
109     SecurityCollector::DataCollection::GetInstance().SecurityGuardSubscribeCollector(onStartEventList);
110     if (!Publish(this)) {
111         SGLOGE("Publish error");
112         return;
113     }
114 }
115 
OnStop()116 void DataCollectManagerService::OnStop()
117 {
118     SecurityCollector::DataCollection::GetInstance().CloseLib();
119 }
120 
121 
Dump(int fd, const std::vector<std::u16string>& args)122 int DataCollectManagerService::Dump(int fd, const std::vector<std::u16string>& args)
123 {
124     SGLOGI("DataCollectManagerService Dump");
125     if (fd < 0) {
126         return BAD_PARAM;
127     }
128 
129     std::string arg0 = ((args.size() == 0) ? "" : Str16ToStr8(args.at(0)));
130     if (arg0.compare("-h") == 0) {
131         dprintf(fd, "Usage:\n");
132         dprintf(fd, "       -h: command help\n");
133         dprintf(fd, "       -i <EVENT_ID>: dump special eventId\n");
134     } else if (arg0.compare("-i") == 0) {
135         if (args.size() < TWO_ARGS) {
136             return BAD_PARAM;
137         }
138 
139         int64_t eventId;
140         bool isSuccess = SecurityGuardUtils::StrToI64(Str16ToStr8(args.at(1)), eventId);
141         if (!isSuccess) {
142             return BAD_PARAM;
143         }
144 
145         DumpEventInfo(fd, eventId);
146     }
147     return ERR_OK;
148 }
149 
DumpEventInfo(int fd, int64_t eventId)150 void DataCollectManagerService::DumpEventInfo(int fd, int64_t eventId)
151 {
152     SecEvent secEvent;
153     int code = DatabaseManager::GetInstance().QueryRecentEventByEventId(eventId, secEvent);
154     if (code != SUCCESS) {
155         SGLOGE("query event error, code=%{public}d", code);
156         return;
157     }
158     dprintf(fd, "eventId : %ld\n", secEvent.eventId);
159     dprintf(fd, "report time : %s\n", secEvent.date.c_str());
160     dprintf(fd, "report version : %s\n", secEvent.version.c_str());
161 }
162 
RequestDataSubmit(int64_t eventId, std::string &version, std::string &time, std::string &content)163 int32_t DataCollectManagerService::RequestDataSubmit(int64_t eventId, std::string &version, std::string &time,
164     std::string &content)
165 {
166     SGLOGD("enter DataCollectManagerService RequestDataSubmit");
167     int32_t ret = IsApiHasPermission("RequestDataSubmit");
168     if (ret != SUCCESS) {
169         return ret;
170     }
171     if (!DataFormat::CheckRiskContent(content)) {
172         SGLOGE("CheckRiskContent error");
173         return BAD_PARAM;
174     }
175     SGLOGD("eventId=%{public}" PRId64 ", version=%{public}s, date=%{public}s", eventId, version.c_str(), time.c_str());
176     SecEvent event {
177         .eventId = eventId,
178         .version = version,
179         .date = time,
180         .content = content
181     };
182     auto task = [event] () mutable {
183         int code = DatabaseManager::GetInstance().InsertEvent(USER_SOURCE, event);
184         if (code != SUCCESS) {
185             SGLOGE("insert event error, %{public}d", code);
186         }
187     };
188     ffrt::submit(task);
189     return SUCCESS;
190 }
191 
RequestRiskData(std::string &devId, std::string &eventList, const sptr<IRemoteObject> &callback)192 int32_t DataCollectManagerService::RequestRiskData(std::string &devId, std::string &eventList,
193     const sptr<IRemoteObject> &callback)
194 {
195     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
196     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, REQUEST_PERMISSION);
197     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
198         SGLOGE("caller no permission");
199         return NO_PERMISSION;
200     }
201     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
202     if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
203         uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
204         if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
205             SGLOGE("not system app no permission");
206             return NO_SYSTEMCALL;
207         }
208     }
209     ObatinDataEvent event;
210     auto pid = IPCSkeleton::GetCallingPid();
211     event.pid = pid;
212     event.time = SecurityGuardUtils::GetDate();
213     SGLOGI("eventList=%{public}s", eventList.c_str());
214     auto promise = std::make_shared<std::promise<int32_t>>();
215     auto future = promise->get_future();
216     PushDataCollectTask(callback, eventList, devId, promise);
217     std::chrono::milliseconds span(TIMEOUT_REPLY);
218     if (future.wait_for(span) == std::future_status::timeout) {
219         SGLOGE("wait for result timeout");
220         event.size = 0;
221     } else {
222         event.size = future.get();
223     }
224     SGLOGI("ReportObatinDataEvent");
225     BigData::ReportObatinDataEvent(event);
226     return SUCCESS;
227 }
228 
GetSecEventsFromConditions(RequestCondition &condition)229 std::vector<SecEvent> DataCollectManagerService::GetSecEventsFromConditions(RequestCondition &condition)
230 {
231     std::vector<SecEvent> events {};
232     if (condition.beginTime.empty() && condition.endTime.empty()) {
233         (void) DatabaseManager::GetInstance().QueryEventByEventId(RISK_TABLE, condition.riskEvent, events);
234     } else {
235         (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, condition.riskEvent, events,
236             condition.beginTime, condition.endTime);
237     }
238     return events;
239 }
240 
PushDataCollectTask(const sptr<IRemoteObject> &object, std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)241 void DataCollectManagerService::PushDataCollectTask(const sptr<IRemoteObject> &object,
242     std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)
243 {
244     auto task = [object, conditions, devId, promise] () mutable {
245         auto proxy = iface_cast<DataCollectManagerCallbackProxy>(object);
246         if (proxy == nullptr) {
247             promise->set_value(0);
248             return;
249         }
250         RequestCondition reqCondition {};
251         DataFormat::ParseConditions(conditions, reqCondition);
252         if (reqCondition.riskEvent.empty() && reqCondition.auditEvent.empty()) {
253             SGLOGE("reqCondition no permission");
254             std::string empty;
255             proxy->ResponseRiskData(devId, empty, FINISH);
256             promise->set_value(0);
257             return;
258         }
259 
260         std::vector<SecEvent> events = GetSecEventsFromConditions(reqCondition);
261         size_t curIndex = 0;
262         size_t lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
263         size_t maxIndex = events.size();
264         promise->set_value(maxIndex);
265         SGLOGI("events size=%{public}zu", maxIndex);
266         std::vector<SecEvent> dispatchVec;
267         while (lastIndex < maxIndex) {
268             dispatchVec.assign(events.begin() + curIndex, events.begin() + lastIndex);
269             std::string dispatch = nlohmann::json(dispatchVec).dump();
270             SGLOGD("dispatch size=%{public}zu", dispatch.size());
271             (void) proxy->ResponseRiskData(devId, dispatch, CONTINUE);
272             curIndex = lastIndex;
273             lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
274         }
275 
276         // last dispatch
277         dispatchVec.assign(events.begin() + curIndex, events.end());
278         std::string dispatch = nlohmann::json(dispatchVec).dump();
279         (void) proxy->ResponseRiskData(devId, dispatch, FINISH);
280         SGLOGI("ResponseRiskData FINISH");
281     };
282     ffrt::submit(task);
283 }
284 
GetSecurityEventConfig(std::vector<int64_t>& eventIdList)285 bool DataCollectManagerService::GetSecurityEventConfig(std::vector<int64_t>& eventIdList)
286 {
287     std::string result;
288     if (DataCollectManager::GetInstance().QuerySecurityEventConfig(result) != SUCCESS) {
289         return false;
290     }
291     nlohmann::json jsonObj = nlohmann::json::parse(result, nullptr, false);
292     if (jsonObj.is_discarded() || !jsonObj.is_array()) {
293         SGLOGE("json is discarded or not array");
294         return false;
295     }
296     for (const auto& item : jsonObj) {
297         if (!item.contains("eventId") || !item["eventId"].is_number()) {
298             SGLOGE("json item no eventId");
299             return false;
300         }
301         int64_t eventId = item["eventId"].get<int64_t>();
302         eventIdList.emplace_back(eventId);
303     }
304     return true;
305 }
306 
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)307 void DataCollectManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
308 {
309     SGLOGI("OnAddSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
310 }
311 
OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)312 void DataCollectManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
313 {
314     SGLOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
315 }
316 
Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)317 int32_t DataCollectManagerService::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
318     const sptr<IRemoteObject> &callback)
319 {
320     SGLOGD("DataCollectManagerService, start subscribe");
321     int32_t ret = IsApiHasPermission("Subscribe");
322     if (ret != SUCCESS) {
323         return ret;
324     }
325     std::lock_guard<std::mutex> lock(mutex_);
326     if (deathRecipient_ == nullptr) {
327         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
328         if (deathRecipient_ == nullptr) {
329             SGLOGE("no memory");
330             return NULL_OBJECT;
331         }
332     }
333     callback->AddDeathRecipient(deathRecipient_);
334     ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(subscribeInfo, callback);
335     SgSubscribeEvent event;
336     event.pid = IPCSkeleton::GetCallingPid();
337     event.time = SecurityGuardUtils::GetDate();
338     event.eventId = subscribeInfo.GetEvent().eventId;
339     event.ret = ret;
340     SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64, event.eventId);
341     BigData::ReportSgSubscribeEvent(event);
342     return ret;
343 }
344 
Unsubscribe(const sptr<IRemoteObject> &callback)345 int32_t DataCollectManagerService::Unsubscribe(const sptr<IRemoteObject> &callback)
346 {
347     int32_t ret = IsApiHasPermission("UnSubscribe");
348     if (ret != SUCCESS) {
349         return ret;
350     }
351     std::lock_guard<std::mutex> lock(mutex_);
352     if (deathRecipient_ != nullptr) {
353         callback->RemoveDeathRecipient(deathRecipient_);
354     }
355 
356     ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(callback);
357     SgUnsubscribeEvent event;
358     event.pid = IPCSkeleton::GetCallingPid();
359     event.time = SecurityGuardUtils::GetDate();
360     event.ret = ret;
361     SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
362     BigData::ReportSgUnsubscribeEvent(event);
363     return ret;
364 }
365 
QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy, SecurityCollector::SecurityEventRuler ruler)366 bool DataCollectManagerService::QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,
367     SecurityCollector::SecurityEventRuler ruler)
368 {
369     EventCfg config;
370     bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(ruler.GetEventId(), config);
371     if (!isSuccess) {
372         SGLOGE("GetEventConfig error, eventId is 0x%{public}" PRIx64, ruler.GetEventId());
373         return true;
374     }
375     std::vector<SecurityCollector::SecurityEvent> replyEvents;
376     std::vector<int64_t> eventIds{ruler.GetEventId()};
377     SGLOGD("eventType is %{public}u", config.eventType);
378     if (config.eventType == 1) { // query in collector
379         int32_t code = SecurityCollector::CollectorManager::GetInstance().QuerySecurityEvent(
380             {ruler}, replyEvents);
381         if (code != SUCCESS) {
382             return false;
383         }
384         proxy->OnQuery(replyEvents);
385     } else {
386         std::vector<SecEvent> events;
387         if (ruler.GetBeginTime().empty() && ruler.GetEndTime().empty()) {
388             (void) DatabaseManager::GetInstance().QueryEventByEventId(ruler.GetEventId(), events);
389         } else {
390             (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, eventIds, events,
391                 ruler.GetBeginTime(), ruler.GetEndTime());
392         }
393         std::transform(events.begin(), events.end(),
394             std::back_inserter(replyEvents), [] (SecEvent event) {
395             return SecurityCollector::SecurityEvent(event.eventId, event.version, event.content, event.date);
396         });
397         proxy->OnQuery(replyEvents);
398     }
399     return true;
400 }
401 
QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers, const sptr<IRemoteObject> &callback)402 int32_t DataCollectManagerService::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
403     const sptr<IRemoteObject> &callback)
404 {
405     SGLOGI("enter DataCollectManagerService QuerySecurityEvent");
406     int32_t ret = IsApiHasPermission("QuerySecurityEvent");
407     if (ret != SUCCESS) {
408         return ret;
409     }
410     auto proxy = iface_cast<ISecurityEventQueryCallback>(callback);
411     if (proxy == nullptr) {
412         SGLOGI("proxy is null");
413         return NULL_OBJECT;
414     }
415 
416     auto task = [proxy, rulers] {
417         std::string errEventIds;
418         for (auto &ruler : rulers) {
419             if (!QueryEventByRuler(proxy, ruler)) {
420                 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
421             }
422         }
423         if (!errEventIds.empty()) {
424             std::string message = "QuerySecurityEvent " + errEventIds + "failed";
425             SGLOGE("QuerySecurityEvent failed");
426             proxy->OnError(message);
427             return;
428         }
429         proxy->OnComplete();
430     };
431 
432     ffrt::submit(task);
433     return SUCCESS;
434 }
435 
OnRemoteDied(const wptr<IRemoteObject> &remote)436 void DataCollectManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
437 {
438     SGLOGI("enter OnRemoteDied");
439     if (remote == nullptr) {
440         SGLOGE("remote object is nullptr");
441         return;
442     }
443 
444     sptr<IRemoteObject> object = remote.promote();
445     if (object == nullptr) {
446         SGLOGE("object is nullptr");
447         return;
448     }
449     sptr<DataCollectManagerService> service = service_.promote();
450     if (service == nullptr) {
451         SGLOGE("service is nullptr");
452         return;
453     }
454     AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(object);
455     if (object->IsProxyObject() && service->deathRecipient_ != nullptr) {
456         object->RemoveDeathRecipient(service->deathRecipient_);
457     }
458     SGLOGI("end OnRemoteDied");
459 }
460 
CollectorStart( const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)461 int32_t DataCollectManagerService::CollectorStart(
462     const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)
463 {
464     SGLOGI("enter DataCollectManagerService CollectorStart.");
465     int32_t code = IsApiHasPermission("CollectorStart");
466     if (code != SUCCESS) {
467         return code;
468     }
469     code = SecurityCollector::CollectorManager::GetInstance().CollectorStart(subscribeInfo);
470     if (code != SUCCESS) {
471         SGLOGI("CollectorStart failed, code=%{public}d", code);
472         return code;
473     }
474     return SUCCESS;
475 }
476 
CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)477 int32_t DataCollectManagerService::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
478     const sptr<IRemoteObject> &callback)
479 {
480     SGLOGI("enter DataCollectManagerService CollectorStop.");
481     int32_t code = IsApiHasPermission("CollectorStop");
482     if (code != SUCCESS) {
483         return code;
484     }
485     code = SecurityCollector::CollectorManager::GetInstance().CollectorStop(subscribeInfo);
486     if (code != SUCCESS) {
487         SGLOGI("CollectorStop failed, code=%{public}d", code);
488         return code;
489     }
490     return SUCCESS;
491 }
492 
IsApiHasPermission(const std::string &api)493 int32_t DataCollectManagerService::IsApiHasPermission(const std::string &api)
494 {
495     if (g_apiPermissionsMap.count(api) == 0) {
496         SGLOGE("api not in map");
497         return FAILED;
498     }
499     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
500     if (std::any_of(g_apiPermissionsMap.at(api).cbegin(), g_apiPermissionsMap.at(api).cend(),
501         [callerToken](const std::string &per) {
502         int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
503         return code == AccessToken::PermissionState::PERMISSION_GRANTED;
504     })) {
505         AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
506         if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
507             uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
508             if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
509                 SGLOGE("not system app no permission");
510                 return NO_SYSTEMCALL;
511             }
512         }
513         return SUCCESS;
514     }
515     SGLOGE("caller no permission");
516     return NO_PERMISSION;
517 }
518 
WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo &info, const std::string &realPath)519 bool DataCollectManagerService::WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo &info,
520     const std::string &realPath)
521 {
522     int32_t fd = info.GetFd();
523     int32_t outputFd = dup(fd);
524     close(fd);
525     if (outputFd == -1) {
526         SGLOGE("dup fd fail reason %{public}s", strerror(errno));
527         return FAILED;
528     }
529     int32_t inputFd = open(realPath.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
530     if (inputFd < 0) {
531         close(outputFd);
532         SGLOGE("open file fail reason %{public}s", strerror(errno));
533         return FAILED;
534     }
535     auto buffer = std::make_unique<char[]> (CFG_FILE_BUFF_SIZE);
536     int offset = -1;
537     while ((offset = read(outputFd, buffer.get(), CFG_FILE_BUFF_SIZE)) > 0) {
538         if (offset > CFG_FILE_MAX_SIZE) {
539             close(outputFd);
540             close(inputFd);
541             SGLOGE("file is empty or too large, len = %{public}d", offset);
542             return BAD_PARAM;
543         }
544         if (write(inputFd, buffer.get(), offset) < 0) {
545             close(inputFd);
546             close(outputFd);
547             SGLOGE("write file to the tmp dir failed");
548             return FAILED;
549         }
550     }
551     close(inputFd);
552     fsync(outputFd);
553     close(outputFd);
554     return SUCCESS;
555 }
556 
ParseTrustListFile(const std::string &trustListFile)557 bool DataCollectManagerService::ParseTrustListFile(const std::string &trustListFile)
558 {
559     if (trustListFile.empty()) {
560         SGLOGE("path is empty");
561         return false;
562     }
563     std::ifstream stream(trustListFile, std::ios::in);
564     if (!stream.is_open()) {
565         SGLOGE("stream error");
566         return false;
567     }
568     stream.seekg(0, std::ios::end);
569     std::ios::pos_type cfgFileMaxSize = 1 * 1024 * 1024;
570     std::ios::pos_type len = stream.tellg();
571     if (len == 0 || len > cfgFileMaxSize) {
572         SGLOGE("stream is empty or too large");
573         stream.close();
574         return false;
575     }
576     stream.seekg(0, std::ios_base::beg);
577     nlohmann::json jsonObj = nlohmann::json::parse(stream, nullptr, false);
578     stream.close();
579     if (jsonObj.is_discarded()) {
580         SGLOGE("json is discarded");
581         return false;
582     }
583 
584     if (!jsonObj.contains("trust_list_config") || !jsonObj["trust_list_config"].is_array()) {
585         return false;
586     }
587 
588     for (const auto &ele : jsonObj["trust_list_config"]) {
589         if (!ele.contains("name")) {
590             return false;
591         }
592         g_configCacheFilesSet.emplace(ele["name"]);
593     }
594 
595     return true;
596 }
597 
ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &info)598 int32_t DataCollectManagerService::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &info)
599 {
600     SGLOGI("enter DataCollectManagerService ConfigUpdate.");
601     int32_t code = IsApiHasPermission("ConfigUpdate");
602     if (code != SUCCESS) {
603         return code;
604     }
605     if (!ParseTrustListFile(TRUST_LIST_FILE_PATH)) {
606         return BAD_PARAM;
607     }
608     if (g_configCacheFilesSet.empty() || !g_configCacheFilesSet.count(info.GetFileName())) {
609         return BAD_PARAM;
610     }
611     const uint32_t modelId = 3001000008;
612     if (info.GetFileName() == "related_event_analysis.json") {
613         ModelManager::GetInstance().InitModel(modelId);
614     }
615     const std::string &realPath = CONFIG_ROOT_PATH + "tmp/" + info.GetFileName();
616     SGLOGI("config file is %{public}s, fd is %{public}d", realPath.c_str(), info.GetFd());
617     std::string tmpPath = realPath + ".t";
618     int32_t ret = WriteRemoteFileToLocal(info, tmpPath);
619     if (ret != SUCCESS) {
620         SGLOGE("write remote file to local fail");
621         return ret;
622     }
623     if (rename(tmpPath.c_str(), realPath.c_str()) != 0) {
624         SGLOGE("remote file rename fail");
625         (void)unlink(tmpPath.c_str());
626         return FAILED;
627     }
628     (void)unlink(tmpPath.c_str());
629 
630     if (!ConfigSubscriber::UpdateConfig(realPath)) {
631         SGLOGE("update config fail");
632         return FAILED;
633     }
634     return SUCCESS;
635 }
636 
QueryEventConfig(std::string &result)637 int32_t DataCollectManagerService::QueryEventConfig(std::string &result)
638 {
639     SGLOGI("Start DataCollectManagerService::QueryEventConfig");
640     std::vector<EventCfg> eventConfigs = ConfigDataManager::GetInstance().GetAllEventConfigs();
641     nlohmann::json resultObj = nlohmann::json::array();
642     for (const auto& event : eventConfigs) {
643         nlohmann::json jObject;
644         jObject["eventId"] = event.eventId;
645         jObject["eventName"] = event.eventName;
646         jObject["version"] = event.version;
647         jObject["eventType"] = event.eventType;
648         jObject["collectOnStart"] = event.collectOnStart;
649         jObject["dataSensitivityLevel"] = event.dataSensitivityLevel;
650         jObject["storageRamNums"] = event.storageRamNums;
651         jObject["storageRomNums"] = event.storageRomNums;
652         jObject["storageTime"] = event.storageTime;
653         jObject["owner"] = event.owner;
654         jObject["source"] = event.source;
655         jObject["dbTable"] = event.dbTable;
656         jObject["prog"] = event.prog;
657         resultObj.push_back(jObject);
658     }
659     result = resultObj.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
660     return SUCCESS;
661 }
662 
QuerySecurityEventConfig(std::string &result)663 int32_t DataCollectManagerService::QuerySecurityEventConfig(std::string &result)
664 {
665     SGLOGI("enter QuerySecurityEventConfig");
666     int32_t ret = IsApiHasPermission("QuerySecurityEventConfig");
667     if (ret != SUCCESS) {
668         return ret;
669     }
670     return QueryEventConfig(result);
671 }
672 
673 }