1 /*
2 * Copyright (c) 2025 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 "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 "file_system_store_helper.h"
49 #include "config_subscriber.h"
50 #include "model_manager.h"
51 #include "config_define.h"
52 #ifdef SECURITY_GUARD_TRIM_MODEL_ANALYSIS
53 #include "event_group_config.h"
54 #endif
55
56 namespace OHOS::Security::SecurityGuard {
57 namespace {
58 constexpr int32_t TWO_ARGS = 2;
59 constexpr int32_t TIMEOUT_REPLY = 10000;
60 const std::string REPORT_PERMISSION = "ohos.permission.securityguard.REPORT_SECURITY_INFO";
61 const std::string REPORT_PERMISSION_NEW = "ohos.permission.REPORT_SECURITY_EVENT";
62 const std::string REQUEST_PERMISSION = "ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO";
63 const std::string MANAGE_CONFIG_PERMISSION = "ohos.permission.MANAGE_SECURITY_GUARD_CONFIG";
64 const std::string QUERY_SECURITY_EVENT_PERMISSION = "ohos.permission.QUERY_SECURITY_EVENT";
65 const std::string QUERY_AUDIT_EVENT_PERMISSION = "ohos.permission.QUERY_AUDIT_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 {"AddFilter", {QUERY_SECURITY_EVENT_PERMISSION}},
78 {"RemoveFilter", {QUERY_SECURITY_EVENT_PERMISSION}},
79 {"QuerySecurityEventById", {QUERY_AUDIT_EVENT_PERMISSION}}
80 };
81 std::unordered_set<std::string> g_configCacheFilesSet;
82 constexpr uint32_t FINISH = 0;
83 constexpr uint32_t CONTINUE = 1;
84 constexpr size_t MAX_DISTRIBUTE_LENS = 100;
85 std::string TRUST_LIST_FILE_PATH_PRE = "/system/etc/";
86 const std::string TRUST_LIST_FILE_PATH = TRUST_LIST_FILE_PATH_PRE + SECURITY_GUARD_CONFIG_UPDATE_TRUST_LIST_SOURCE;
87 }
88
89 REGISTER_SYSTEM_ABILITY_BY_ID(DataCollectManagerService, DATA_COLLECT_MANAGER_SA_ID, true);
90
DataCollectManagerService(int32_t saId,bool runOnCreate)91 DataCollectManagerService::DataCollectManagerService(int32_t saId, bool runOnCreate)
92 : SystemAbility(saId, runOnCreate)
93 {
94 SGLOGW("%{public}s", __func__);
95 }
96
97 typedef void (*InitAllConfigFunc)();
98 typedef bool (*UpdateConfigFunc)(const std::string &);
99 // LCOV_EXCL_START
OnStart()100 void DataCollectManagerService::OnStart()
101 {
102 SGLOGI("%{public}s", __func__);
103 DatabaseManager::GetInstance().Init(); // Make sure the database is ready
104
105 void *handle = dlopen("libsg_config_manager.z.so", RTLD_LAZY);
106 if (handle == nullptr) {
107 SGLOGE("dlopen error: %{public}s", dlerror());
108 } else {
109 auto func = (InitAllConfigFunc)dlsym(handle, "InitAllConfig");
110 if (func != nullptr) {
111 SGLOGI("begin init all config");
112 func();
113 } else {
114 SGLOGE("dlsym error: %{public}s", dlerror());
115 }
116 dlclose(handle);
117 }
118 AcquireDataSubscribeManager::GetInstance().InitEventQueue();
119 AcquireDataSubscribeManager::GetInstance().SubscriberEventOnSgStart();
120 if (!Publish(this)) {
121 SGLOGE("Publish error");
122 return;
123 }
124 AcquireDataSubscribeManager::GetInstance().StartClearEventCache();
125 }
126
OnStop()127 void DataCollectManagerService::OnStop()
128 {
129 SecurityCollector::DataCollection::GetInstance().CloseLib();
130 AcquireDataSubscribeManager::GetInstance().StopClearEventCache();
131 AcquireDataSubscribeManager::GetInstance().DeInitDeviceId();
132 }
133
Dump(int fd,const std::vector<std::u16string> & args)134 int DataCollectManagerService::Dump(int fd, const std::vector<std::u16string>& args)
135 {
136 SGLOGI("DataCollectManagerService Dump");
137 if (fd < 0) {
138 return BAD_PARAM;
139 }
140
141 std::string arg0 = ((args.size() == 0) ? "" : Str16ToStr8(args.at(0)));
142 if (arg0.compare("-h") == 0) {
143 dprintf(fd, "Usage:\n");
144 dprintf(fd, " -h: command help\n");
145 dprintf(fd, " -i <EVENT_ID>: dump special eventId\n");
146 } else if (arg0.compare("-i") == 0) {
147 if (args.size() < TWO_ARGS) {
148 return BAD_PARAM;
149 }
150
151 int64_t eventId;
152 bool isSuccess = SecurityGuardUtils::StrToI64(Str16ToStr8(args.at(1)), eventId);
153 if (!isSuccess) {
154 return BAD_PARAM;
155 }
156
157 DumpEventInfo(fd, eventId);
158 }
159 return ERR_OK;
160 }
161
DumpEventInfo(int fd,int64_t eventId)162 void DataCollectManagerService::DumpEventInfo(int fd, int64_t eventId)
163 {
164 SecEvent secEvent;
165 int code = DatabaseManager::GetInstance().QueryRecentEventByEventId(eventId, secEvent);
166 if (code != SUCCESS) {
167 SGLOGE("query event error, code=%{public}d", code);
168 return;
169 }
170 dprintf(fd, "eventId : %ld\n", secEvent.eventId);
171 dprintf(fd, "report time : %s\n", secEvent.date.c_str());
172 dprintf(fd, "report version : %s\n", secEvent.version.c_str());
173 }
174
175 // LCOV_EXCL_STOP
176
RequestDataSubmit(int64_t eventId,const std::string & version,const std::string & time,const std::string & content)177 ErrCode DataCollectManagerService::RequestDataSubmit(int64_t eventId, const std::string &version,
178 const std::string &time, const std::string &content)
179 {
180 SGLOGD("enter DataCollectManagerService RequestDataSubmit");
181 int32_t ret = IsApiHasPermission("RequestDataSubmit");
182 if (ret != SUCCESS) {
183 return ret;
184 }
185 // LCOV_EXCL_START
186 SecurityCollector::Event event {};
187 event.eventId = eventId;
188 event.version = version;
189 event.timestamp = time;
190 event.content = content;
191 AcquireDataSubscribeManager::GetInstance().UploadEvent(event);
192 return SUCCESS;
193 // LCOV_EXCL_STOP
194 }
195
RequestDataSubmitAsync(int64_t eventId,const std::string & version,const std::string & time,const std::string & content)196 ErrCode DataCollectManagerService::RequestDataSubmitAsync(int64_t eventId, const std::string &version,
197 const std::string &time, const std::string &content)
198 {
199 SGLOGD("enter DataCollectManagerService RequestDataSubmitAsync");
200 return RequestDataSubmit(eventId, version, time, content);
201 }
202
RequestRiskData(const std::string & devId,const std::string & eventList,const sptr<IRemoteObject> & cb)203 ErrCode DataCollectManagerService::RequestRiskData(const std::string &devId, const std::string &eventList,
204 const sptr<IRemoteObject> &cb)
205 {
206 AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
207 int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, REQUEST_PERMISSION);
208 if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
209 SGLOGE("caller no permission");
210 return NO_PERMISSION;
211 }
212 AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
213 if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
214 uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
215 if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
216 SGLOGE("not system app no permission");
217 return NO_SYSTEMCALL;
218 }
219 }
220 ObtainDataEvent event;
221 auto pid = IPCSkeleton::GetCallingPid();
222 event.pid = pid;
223 event.time = SecurityGuardUtils::GetDate();
224 SGLOGI("eventList=%{public}s", eventList.c_str());
225 auto promise = std::make_shared<std::promise<int32_t>>();
226 auto future = promise->get_future();
227 PushDataCollectTask(cb, eventList, devId, promise);
228 std::chrono::milliseconds span(TIMEOUT_REPLY);
229 if (future.wait_for(span) == std::future_status::timeout) {
230 SGLOGE("wait for result timeout");
231 event.size = 0;
232 } else {
233 event.size = future.get();
234 }
235 SGLOGI("ReportObtainDataEvent");
236 BigData::ReportObtainDataEvent(event);
237 return SUCCESS;
238 }
239
GetSecEventsFromConditions(RequestCondition & condition)240 std::vector<SecEvent> DataCollectManagerService::GetSecEventsFromConditions(RequestCondition &condition)
241 {
242 std::vector<SecEvent> events {};
243 if (condition.beginTime.empty() && condition.endTime.empty()) {
244 (void) DatabaseManager::GetInstance().QueryEventByEventId(RISK_TABLE, condition.riskEvent, events);
245 } else {
246 (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, condition.riskEvent, events,
247 condition.beginTime, condition.endTime);
248 }
249 return events;
250 }
251
to_json(nlohmann::json & jsonObj,const SecEvent & eventDataSt)252 void to_json(nlohmann::json &jsonObj, const SecEvent &eventDataSt)
253 {
254 jsonObj = nlohmann::json {
255 { "eventId", eventDataSt.eventId },
256 { "version", eventDataSt.version },
257 { "date", eventDataSt.date },
258 { "content", eventDataSt.content },
259 { "userId", eventDataSt.userId },
260 { "deviceId", eventDataSt.deviceId },
261 };
262 }
263
PushDataCollectTask(const sptr<IRemoteObject> & object,std::string conditions,std::string devId,std::shared_ptr<std::promise<int32_t>> promise)264 void DataCollectManagerService::PushDataCollectTask(const sptr<IRemoteObject> &object,
265 std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)
266 {
267 auto task = [object, conditions, devId, promise] () mutable {
268 auto proxy = iface_cast<DataCollectManagerCallbackProxy>(object);
269 if (proxy == nullptr) {
270 promise->set_value(0);
271 return;
272 }
273 RequestCondition reqCondition {};
274 DataFormat::ParseConditions(conditions, reqCondition);
275 if (reqCondition.riskEvent.empty() && reqCondition.auditEvent.empty()) {
276 SGLOGE("reqCondition no permission");
277 std::string empty;
278 proxy->ResponseRiskData(devId, empty, FINISH);
279 promise->set_value(0);
280 return;
281 }
282
283 std::vector<SecEvent> events = GetSecEventsFromConditions(reqCondition);
284 size_t curIndex = 0;
285 size_t lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
286 size_t maxIndex = events.size();
287 promise->set_value(maxIndex);
288 SGLOGI("events size=%{public}zu", maxIndex);
289 std::vector<SecEvent> dispatchVec;
290 while (lastIndex < maxIndex) {
291 dispatchVec.assign(events.begin() + curIndex, events.begin() + lastIndex);
292 std::string dispatch = nlohmann::json(dispatchVec).dump();
293 SGLOGD("dispatch size=%{public}zu", dispatch.size());
294 (void) proxy->ResponseRiskData(devId, dispatch, CONTINUE);
295 curIndex = lastIndex;
296 lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
297 }
298
299 // last dispatch
300 dispatchVec.assign(events.begin() + curIndex, events.end());
301 std::string dispatch = nlohmann::json(dispatchVec).dump();
302 (void) proxy->ResponseRiskData(devId, dispatch, FINISH);
303 SGLOGI("ResponseRiskData FINISH");
304 };
305 ffrt::submit(task);
306 }
307
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)308 void DataCollectManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
309 {
310 SGLOGI("OnAddSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
311 }
312
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)313 void DataCollectManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
314 {
315 SGLOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
316 }
317
Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & cb,const std::string & clientId)318 ErrCode DataCollectManagerService::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
319 const sptr<IRemoteObject> &cb, const std::string &clientId)
320 {
321 SGLOGD("DataCollectManagerService, start subscribe");
322 int32_t ret = FAILED;
323 SgSubscribeEvent event;
324 event.pid = IPCSkeleton::GetCallingPid();
325 event.time = SecurityGuardUtils::GetDate();
326 event.eventId = subscribeInfo.GetEvent().eventId;
327 if (subscribeInfo.GetEventGroup() == "") {
328 ret = IsApiHasPermission("Subscribe");
329 } else if (subscribeInfo.GetEventGroup() == "auditGroup") {
330 ret = IsEventGroupHasPublicPermission(subscribeInfo.GetEventGroup(), {});
331 } else {
332 ret = IsEventGroupHasPermission(subscribeInfo.GetEventGroup(),
333 std::vector<int64_t>{subscribeInfo.GetEvent().eventId});
334 }
335 if (ret != SUCCESS) {
336 event.ret = ret;
337 BigData::ReportSgSubscribeEvent(event);
338 return ret;
339 }
340 ret = SetDeathCallBack(event, cb);
341 if (ret != SUCCESS) {
342 return ret;
343 }
344 ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(subscribeInfo, cb, clientId);
345 event.ret = ret;
346 SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64, event.eventId);
347 BigData::ReportSgSubscribeEvent(event);
348 return ret;
349 }
350
Unsubscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & cb,const std::string & clientId)351 ErrCode DataCollectManagerService::Unsubscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
352 const sptr<IRemoteObject> &cb, const std::string &clientId)
353 {
354 int32_t ret = FAILED;
355 SgUnsubscribeEvent event;
356 event.pid = IPCSkeleton::GetCallingPid();
357 event.time = SecurityGuardUtils::GetDate();
358 if (subscribeInfo.GetEventGroup() == "") {
359 ret = IsApiHasPermission("UnSubscribe");
360 } else if (subscribeInfo.GetEventGroup() == "auditGroup") {
361 ret = IsEventGroupHasPublicPermission(subscribeInfo.GetEventGroup(), {});
362 } else {
363 ret = IsEventGroupHasPermission(subscribeInfo.GetEventGroup(),
364 std::vector<int64_t>{subscribeInfo.GetEvent().eventId});
365 }
366 if (ret != SUCCESS) {
367 event.ret = ret;
368 BigData::ReportSgUnsubscribeEvent(event);
369 return ret;
370 }
371 {
372 std::lock_guard<std::mutex> lock(mutex_);
373 if (deathRecipient_ != nullptr) {
374 cb->RemoveDeathRecipient(deathRecipient_);
375 }
376 }
377 ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(subscribeInfo.GetEvent().eventId, cb,
378 clientId);
379 event.ret = ret;
380 SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
381 BigData::ReportSgUnsubscribeEvent(event);
382 return ret;
383 }
384
QuerySecurityEventCallBack(sptr<ISecurityEventQueryCallback> proxy,std::vector<SecurityCollector::SecurityEvent> events)385 void DataCollectManagerService::QuerySecurityEventCallBack(sptr<ISecurityEventQueryCallback> proxy,
386 std::vector<SecurityCollector::SecurityEvent> events)
387 {
388 int32_t step = MAX_ON_QUERY_SIZE;
389 if (events.size() > 0 && events.size() <= static_cast<size_t>(MAX_ON_QUERY_SIZE)) {
390 proxy->OnQuery(events);
391 } else if (events.size() > static_cast<size_t>(MAX_ON_QUERY_SIZE)) {
392 std::vector<SecurityCollector::SecurityEvent>::iterator curPtr = events.begin();
393 std::vector<SecurityCollector::SecurityEvent>::iterator endPtr = events.end();
394 std::vector<SecurityCollector::SecurityEvent>::iterator end;
395 while (curPtr < endPtr) {
396 end = endPtr - curPtr > step ? step + curPtr : endPtr;
397 step = endPtr - curPtr > step ? step : endPtr - curPtr;
398 proxy->OnQuery(std::vector<SecurityCollector::SecurityEvent>(curPtr, end));
399 curPtr += step;
400 }
401 }
402 }
403
QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,SecurityCollector::SecurityEventRuler ruler)404 bool DataCollectManagerService::QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,
405 SecurityCollector::SecurityEventRuler ruler)
406 {
407 EventCfg config;
408 bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(ruler.GetEventId(), config);
409 if (!isSuccess) {
410 SGLOGE("GetEventConfig error, eventId is 0x%{public}" PRIx64, ruler.GetEventId());
411 return false;
412 }
413 std::vector<SecurityCollector::SecurityEvent> replyEvents;
414 std::vector<int64_t> eventIds{ruler.GetEventId()};
415 SGLOGD("eventType is %{public}u", config.eventType);
416 if (config.eventType == 1) { // query in collector
417 int32_t code = FAILED;
418 if (config.prog == "security_guard") {
419 code = SecurityCollector::DataCollection::GetInstance().QuerySecurityEvent({ruler}, replyEvents);
420 } else {
421 code = SecurityCollector::CollectorManager::GetInstance().QuerySecurityEvent(
422 {ruler}, replyEvents);
423 }
424 if (code != SUCCESS) {
425 return false;
426 }
427 QuerySecurityEventCallBack(proxy, replyEvents);
428 } else { // query in db
429 if (config.dbTable == FILE_SYSTEM) {
430 (void) FileSystemStoreHelper::GetInstance().QuerySecurityEvent(ruler, proxy);
431 return true;
432 }
433 std::vector<SecEvent> events;
434 if (ruler.GetBeginTime().empty() && ruler.GetEndTime().empty()) {
435 (void) DatabaseManager::GetInstance().QueryEventByEventId(ruler.GetEventId(), events);
436 } else {
437 (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, eventIds, events,
438 ruler.GetBeginTime(), ruler.GetEndTime());
439 }
440 std::transform(events.begin(), events.end(),
441 std::back_inserter(replyEvents), [] (SecEvent event) {
442 return SecurityCollector::SecurityEvent(event.eventId, event.version, event.content, event.date);
443 });
444 QuerySecurityEventCallBack(proxy, replyEvents);
445 }
446 return true;
447 }
448
QuerySecurityEventById(const std::vector<SecurityCollector::SecurityEventRuler> & rulers,const sptr<IRemoteObject> & cb,const std::string & eventGroup)449 ErrCode DataCollectManagerService::QuerySecurityEventById(const std::vector<SecurityCollector::SecurityEventRuler>
450 &rulers, const sptr<IRemoteObject> &cb, const std::string &eventGroup)
451 {
452 SGLOGI("enter DataCollectManagerService QuerySecurityEventById");
453 int32_t ret = IsEventGroupHasPublicPermission(eventGroup, std::vector<int64_t>{});
454 if (ret != SUCCESS) {
455 return ret;
456 }
457 auto proxy = iface_cast<ISecurityEventQueryCallback>(cb);
458 if (proxy == nullptr) {
459 SGLOGI("proxy is null");
460 return NULL_OBJECT;
461 }
462 const int64_t queryPorcInfoEventId = 1011015023;
463 std::unordered_set<int64_t> eventIds = {queryPorcInfoEventId};
464 auto task = [proxy, rulers, eventIds] {
465 std::string errEventIds;
466 for (auto &ruler : rulers) {
467 if (eventIds.count(ruler.GetEventId()) == 0) {
468 SGLOGE("eventid not in eventid list eventId=%{public}" PRId64, ruler.GetEventId());
469 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
470 continue;
471 }
472 if (!QueryEventByRuler(proxy, ruler)) {
473 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
474 }
475 }
476 if (!errEventIds.empty()) {
477 std::string message = "QuerySecurityEvent " + errEventIds + "failed";
478 SGLOGE("QuerySecurityEvent failed");
479 proxy->OnError(message);
480 return;
481 }
482 proxy->OnComplete();
483 };
484 ffrt::submit(task);
485 return SUCCESS;
486 }
487
QuerySecurityEvent(const std::vector<SecurityCollector::SecurityEventRuler> & rulers,const sptr<IRemoteObject> & cb,const std::string & eventGroup)488 ErrCode DataCollectManagerService::QuerySecurityEvent(const std::vector<SecurityCollector::SecurityEventRuler> &rulers,
489 const sptr<IRemoteObject> &cb, const std::string &eventGroup)
490 {
491 SGLOGI("enter DataCollectManagerService QuerySecurityEvent");
492 int32_t ret = 0;
493 if (eventGroup == "") {
494 ret = IsApiHasPermission("QuerySecurityEvent");
495 } else {
496 ret = IsEventGroupHasPermission(eventGroup, std::vector<int64_t>{});
497 }
498 if (ret != SUCCESS) {
499 return ret;
500 }
501 auto proxy = iface_cast<ISecurityEventQueryCallback>(cb);
502 if (proxy == nullptr) {
503 SGLOGI("proxy is null");
504 return NULL_OBJECT;
505 }
506 auto task = [proxy, rulers, eventGroup] {
507 std::string errEventIds;
508 EventGroupCfg config {};
509 if (!ConfigDataManager::GetInstance().GetEventGroupConfig(eventGroup, config)) {
510 SGLOGE("get event group config fail group = %{public}s", eventGroup.c_str());
511 return;
512 }
513 for (auto &ruler : rulers) {
514 if (config.eventList.count(ruler.GetEventId()) == 0) {
515 SGLOGE("eventid not in eventid list");
516 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
517 continue;
518 }
519 if (!QueryEventByRuler(proxy, ruler)) {
520 errEventIds.append(std::to_string(ruler.GetEventId()) + " ");
521 }
522 }
523 if (!errEventIds.empty()) {
524 std::string message = "QuerySecurityEvent " + errEventIds + "failed";
525 SGLOGE("QuerySecurityEvent failed");
526 proxy->OnError(message);
527 return;
528 }
529 proxy->OnComplete();
530 };
531 ffrt::submit(task);
532 return SUCCESS;
533 }
534
535 // LCOV_EXCL_START
OnRemoteDied(const wptr<IRemoteObject> & remote)536 void DataCollectManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
537 {
538 SGLOGI("enter OnRemoteDied");
539 if (remote == nullptr) {
540 SGLOGE("remote object is nullptr");
541 return;
542 }
543
544 sptr<IRemoteObject> object = remote.promote();
545 if (object == nullptr) {
546 SGLOGE("object is nullptr");
547 return;
548 }
549 sptr<DataCollectManagerService> service = service_.promote();
550 if (service == nullptr) {
551 SGLOGE("service is nullptr");
552 return;
553 }
554 AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecordOnRemoteDied(object);
555 if (object->IsProxyObject() && service->deathRecipient_ != nullptr) {
556 object->RemoveDeathRecipient(service->deathRecipient_);
557 }
558 SGLOGI("end OnRemoteDied");
559 }
560
CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & cb)561 ErrCode DataCollectManagerService::CollectorStart(
562 const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &cb)
563 {
564 SGLOGI("enter DataCollectManagerService CollectorStart.");
565 int32_t code = IsApiHasPermission("CollectorStart");
566 if (code != SUCCESS) {
567 return code;
568 }
569 code = SecurityCollector::CollectorManager::GetInstance().CollectorStart(subscribeInfo);
570 if (code != SUCCESS) {
571 SGLOGI("CollectorStart failed, code=%{public}d", code);
572 return code;
573 }
574 return SUCCESS;
575 }
576
CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & cb)577 ErrCode DataCollectManagerService::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
578 const sptr<IRemoteObject> &cb)
579 {
580 SGLOGI("enter DataCollectManagerService CollectorStop.");
581 int32_t code = IsApiHasPermission("CollectorStop");
582 if (code != SUCCESS) {
583 return code;
584 }
585 code = SecurityCollector::CollectorManager::GetInstance().CollectorStop(subscribeInfo);
586 if (code != SUCCESS) {
587 SGLOGI("CollectorStop failed, code=%{public}d", code);
588 return code;
589 }
590 return SUCCESS;
591 }
592
IsApiHasPermission(const std::string & api)593 int32_t DataCollectManagerService::IsApiHasPermission(const std::string &api)
594 {
595 if (g_apiPermissionsMap.count(api) == 0) {
596 SGLOGE("api not in map");
597 return FAILED;
598 }
599 AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
600 if (std::any_of(g_apiPermissionsMap.at(api).cbegin(), g_apiPermissionsMap.at(api).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
IsEventGroupHasPublicPermission(const std::string & eventGroup,std::vector<int64_t> eventIds)619 int32_t DataCollectManagerService::IsEventGroupHasPublicPermission(const std::string &eventGroup,
620 std::vector<int64_t> eventIds)
621 {
622 EventGroupCfg config {};
623 if (!ConfigDataManager::GetInstance().GetEventGroupConfig(eventGroup, config)) {
624 SGLOGE("get event group config fail group = %{public}s", eventGroup.c_str());
625 return BAD_PARAM;
626 }
627 for (int64_t eventId : eventIds) {
628 if (config.eventList.count(eventId) == 0) {
629 SGLOGE("eventid not in eventid list");
630 return BAD_PARAM;
631 }
632 }
633 AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
634 if (std::any_of(config.permissionList.cbegin(), config.permissionList.cend(),
635 [callerToken](const std::string &per) {
636 int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
637 return code == AccessToken::PermissionState::PERMISSION_GRANTED;
638 })) {
639 return SUCCESS;
640 }
641 SGLOGE("caller no permission");
642 return NO_PERMISSION;
643 }
644
IsEventGroupHasPermission(const std::string & eventGroup,std::vector<int64_t> eventIds)645 int32_t DataCollectManagerService::IsEventGroupHasPermission(const std::string &eventGroup,
646 std::vector<int64_t> eventIds)
647 {
648 EventGroupCfg config {};
649 if (!ConfigDataManager::GetInstance().GetEventGroupConfig(eventGroup, config)) {
650 SGLOGE("get event group config fail group = %{public}s", eventGroup.c_str());
651 return BAD_PARAM;
652 }
653 for (int64_t eventId : eventIds) {
654 if (config.eventList.count(eventId) == 0) {
655 SGLOGE("eventid not in eventid list");
656 return BAD_PARAM;
657 }
658 }
659 AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
660 if (std::any_of(config.permissionList.cbegin(), config.permissionList.cend(),
661 [callerToken](const std::string &per) {
662 int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
663 return code == AccessToken::PermissionState::PERMISSION_GRANTED;
664 })) {
665 AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
666 if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
667 uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
668 if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
669 SGLOGE("not system app no permission");
670 return NO_SYSTEMCALL;
671 }
672 }
673 return SUCCESS;
674 }
675 SGLOGE("caller no permission");
676 return NO_PERMISSION;
677 }
678
WriteRemoteFileToLocal(int fd,const std::string & realPath)679 int32_t DataCollectManagerService::WriteRemoteFileToLocal(int fd, const std::string &realPath)
680 {
681 int32_t outputFd = dup(fd);
682 close(fd);
683 if (outputFd == -1) {
684 SGLOGE("dup fd fail reason %{public}s", strerror(errno));
685 return FAILED;
686 }
687 int32_t inputFd = open(realPath.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
688 if (inputFd < 0) {
689 close(outputFd);
690 SGLOGE("open file fail reason %{public}s", strerror(errno));
691 return FAILED;
692 }
693 auto buffer = std::make_unique<char[]> (CFG_FILE_BUFF_SIZE);
694 int offset = -1;
695 while ((offset = read(outputFd, buffer.get(), CFG_FILE_BUFF_SIZE)) > 0) {
696 if (offset > CFG_FILE_MAX_SIZE) {
697 close(outputFd);
698 close(inputFd);
699 SGLOGE("file is empty or too large, len = %{public}d", offset);
700 return BAD_PARAM;
701 }
702 if (write(inputFd, buffer.get(), offset) < 0) {
703 close(inputFd);
704 close(outputFd);
705 SGLOGE("write file to the tmp dir failed");
706 return FAILED;
707 }
708 }
709 close(inputFd);
710 fsync(outputFd);
711 close(outputFd);
712 return SUCCESS;
713 }
714
ParseTrustListFile(const std::string & trustListFile)715 bool DataCollectManagerService::ParseTrustListFile(const std::string &trustListFile)
716 {
717 if (trustListFile.empty()) {
718 SGLOGE("path is empty");
719 return false;
720 }
721 std::ifstream stream(trustListFile, std::ios::in);
722 if (!stream.is_open()) {
723 SGLOGE("stream error");
724 return false;
725 }
726 stream.seekg(0, std::ios::end);
727 std::ios::pos_type cfgFileMaxSize = 1 * 1024 * 1024;
728 std::ios::pos_type len = stream.tellg();
729 if (len == 0 || len > cfgFileMaxSize) {
730 SGLOGE("stream is empty or too large");
731 stream.close();
732 return false;
733 }
734 stream.seekg(0, std::ios_base::beg);
735 nlohmann::json jsonObj = nlohmann::json::parse(stream, nullptr, false);
736 stream.close();
737 if (jsonObj.is_discarded()) {
738 SGLOGE("json is discarded");
739 return false;
740 }
741
742 if (!jsonObj.contains("trust_list_config") || !jsonObj["trust_list_config"].is_array()) {
743 return false;
744 }
745
746 for (const auto &ele : jsonObj["trust_list_config"]) {
747 if (!ele.contains("name")) {
748 return false;
749 }
750 g_configCacheFilesSet.emplace(ele["name"]);
751 }
752
753 return true;
754 }
755
ConfigUpdate(int fd,const std::string & name)756 ErrCode DataCollectManagerService::ConfigUpdate(int fd, const std::string& name)
757 {
758 SGLOGI("enter DataCollectManagerService ConfigUpdate.");
759 int32_t code = IsApiHasPermission("ConfigUpdate");
760 if (code != SUCCESS) {
761 return code;
762 }
763 if (!ParseTrustListFile(TRUST_LIST_FILE_PATH)) {
764 return BAD_PARAM;
765 }
766 if (g_configCacheFilesSet.empty() || !g_configCacheFilesSet.count(name)) {
767 return BAD_PARAM;
768 }
769 const std::string &realPath = CONFIG_ROOT_PATH + "tmp/" + name;
770 SGLOGI("config file is %{public}s, fd is %{public}d", realPath.c_str(), fd);
771 std::string tmpPath = realPath + ".t";
772 int32_t ret = WriteRemoteFileToLocal(fd, tmpPath);
773 if (ret != SUCCESS) {
774 SGLOGE("write remote file to local fail");
775 return ret;
776 }
777 if (rename(tmpPath.c_str(), realPath.c_str()) != 0) {
778 SGLOGE("remote file rename fail");
779 (void)unlink(tmpPath.c_str());
780 return FAILED;
781 }
782 (void)unlink(tmpPath.c_str());
783 void *handle = dlopen("libsg_config_manager.z.so", RTLD_LAZY);
784 if (handle == nullptr) {
785 SGLOGE("dlopen error: %{public}s", dlerror());
786 return FAILED;
787 }
788 auto func = (UpdateConfigFunc)dlsym(handle, "UpdateConfig");
789 if (func == nullptr) {
790 SGLOGE("dlsym error: %{public}s", dlerror());
791 dlclose(handle);
792 return FAILED;
793 }
794 if (!func(realPath)) {
795 SGLOGE("update config fail");
796 dlclose(handle);
797 return FAILED;
798 }
799 dlclose(handle);
800 return SUCCESS;
801 }
802
QueryEventConfig(std::string & result)803 int32_t DataCollectManagerService::QueryEventConfig(std::string &result)
804 {
805 SGLOGI("Start DataCollectManagerService::QueryEventConfig");
806 std::vector<EventCfg> eventConfigs = ConfigDataManager::GetInstance().GetAllEventConfigs();
807 nlohmann::json resultObj = nlohmann::json::array();
808 for (const auto& event : eventConfigs) {
809 nlohmann::json jObject;
810 jObject["eventId"] = event.eventId;
811 jObject["eventName"] = event.eventName;
812 jObject["version"] = event.version;
813 jObject["eventType"] = event.eventType;
814 jObject["collectOnStart"] = event.collectOnStart;
815 jObject["dataSensitivityLevel"] = event.dataSensitivityLevel;
816 jObject["discardEventWhiteList"] = event.discardEventWhiteList;
817 jObject["storageRamNums"] = event.storageRamNums;
818 jObject["storageRomNums"] = event.storageRomNums;
819 jObject["storageTime"] = event.storageTime;
820 jObject["owner"] = event.owner;
821 jObject["source"] = event.source;
822 jObject["dbTable"] = event.dbTable;
823 jObject["prog"] = event.prog;
824 jObject["isBatchUpload"] = event.isBatchUpload;
825 resultObj.push_back(jObject);
826 }
827 result = resultObj.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
828 return SUCCESS;
829 }
830
QuerySecurityEventConfig(std::string & result)831 ErrCode DataCollectManagerService::QuerySecurityEventConfig(std::string &result)
832 {
833 SGLOGI("enter QuerySecurityEventConfig");
834 int32_t ret = IsApiHasPermission("QuerySecurityEventConfig");
835 if (ret != SUCCESS) {
836 return ret;
837 }
838 return QueryEventConfig(result);
839 }
840
AddFilter(const SecurityEventFilter & subscribeMute,const std::string & clientId)841 ErrCode DataCollectManagerService::AddFilter(const SecurityEventFilter &subscribeMute, const std::string &clientId)
842 {
843 SGLOGI("enter DataCollectManagerService AddFilter.");
844 int32_t ret = FAILED;
845 SgSubscribeEvent event;
846 EventMuteFilter filter = subscribeMute.GetMuteFilter();
847 event.pid = IPCSkeleton::GetCallingPid();
848 event.time = SecurityGuardUtils::GetDate();
849 event.eventId = filter.eventId;
850 std::string eventGroup = AcquireDataSubscribeManager::GetInstance().GetCurrentClientGroup(clientId);
851 if (eventGroup == "securityGroup") {
852 ret = IsEventGroupHasPermission(eventGroup, std::vector<int64_t>{filter.eventId});
853 } else {
854 ret = IsEventGroupHasPublicPermission(eventGroup, std::vector<int64_t>{filter.eventId});
855 }
856 if (ret != SUCCESS) {
857 event.ret = ret;
858 BigData::ReportSetMuteEvent(event);
859 return ret;
860 }
861 ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeMute(filter, clientId);
862 if (ret != SUCCESS) {
863 SGLOGE("InsertSubscribeMute fail");
864 event.ret = ret;
865 BigData::ReportSetMuteEvent(event);
866 return ret;
867 }
868 event.ret = ret;
869 BigData::ReportSetMuteEvent(event);
870 return ret;
871 }
872
RemoveFilter(const SecurityEventFilter & subscribeMute,const std::string & clientId)873 ErrCode DataCollectManagerService::RemoveFilter(const SecurityEventFilter &subscribeMute, const std::string &clientId)
874 {
875 SGLOGI("enter DataCollectManagerService RemoveFilter.");
876 SgSubscribeEvent event;
877 EventMuteFilter filter = subscribeMute.GetMuteFilter();
878 event.pid = IPCSkeleton::GetCallingPid();
879 event.time = SecurityGuardUtils::GetDate();
880 event.eventId = filter.eventId;
881 std::string eventGroup = AcquireDataSubscribeManager::GetInstance().GetCurrentClientGroup(clientId);
882 int32_t ret = 0;
883 if (eventGroup == "securityGroup") {
884 ret = IsEventGroupHasPermission(eventGroup, std::vector<int64_t>{filter.eventId});
885 } else {
886 ret = IsEventGroupHasPublicPermission(eventGroup, std::vector<int64_t>{filter.eventId});
887 }
888 if (ret != SUCCESS) {
889 event.ret = ret;
890 BigData::ReportSetUnMuteEvent(event);
891 return ret;
892 }
893 ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeMute(filter, clientId);
894 if (ret != SUCCESS) {
895 SGLOGE("fail to RemoveSubscribeMute");
896 event.ret = ret;
897 BigData::ReportSetUnMuteEvent(event);
898 return ret;
899 }
900 event.ret = ret;
901 BigData::ReportSetUnMuteEvent(event);
902 return ret;
903 }
904
SetDeathCallBack(SgSubscribeEvent event,const sptr<IRemoteObject> & callback)905 int32_t DataCollectManagerService::SetDeathCallBack(SgSubscribeEvent event, const sptr<IRemoteObject> &callback)
906 {
907 std::lock_guard<std::mutex> lock(mutex_);
908 if (deathRecipient_ == nullptr) {
909 deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
910 if (deathRecipient_ == nullptr) {
911 SGLOGE("no memory");
912 event.ret = NULL_OBJECT;
913 BigData::ReportSgSubscribeEvent(event);
914 return NULL_OBJECT;
915 }
916 }
917 callback->AddDeathRecipient(deathRecipient_);
918 return SUCCESS;
919 }
920 // LCOV_EXCL_STOP
Subscribe(int64_t eventId,const std::string & clientId)921 ErrCode DataCollectManagerService::Subscribe(int64_t eventId, const std::string &clientId)
922 {
923 SGLOGI("DataCollectManagerService, start new subscribe");
924 int32_t ret = FAILED;
925 SgSubscribeEvent event;
926 event.pid = IPCSkeleton::GetCallingPid();
927 event.time = SecurityGuardUtils::GetDate();
928 event.eventId = eventId;
929 std::string eventGroup = AcquireDataSubscribeManager::GetInstance().GetCurrentClientGroup(clientId);
930 if (eventGroup == "securityGroup") {
931 ret = IsEventGroupHasPermission(eventGroup, {});
932 } else {
933 ret = IsEventGroupHasPublicPermission(eventGroup, {});
934 }
935 if (ret != SUCCESS) {
936 event.ret = ret;
937 BigData::ReportSgSubscribeEvent(event);
938 return ret;
939 }
940 ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(eventId, clientId);
941 if (ret != SUCCESS) {
942 SGLOGE("InsertSubscribeRecord fail");
943 event.ret = ret;
944 BigData::ReportSgSubscribeEvent(event);
945 return ret;
946 }
947 event.ret = ret;
948 SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64, event.eventId);
949 BigData::ReportSgSubscribeEvent(event);
950 return SUCCESS;
951 }
952
Unsubscribe(int64_t eventId,const std::string & clientId)953 ErrCode DataCollectManagerService::Unsubscribe(int64_t eventId, const std::string &clientId)
954 {
955 SGLOGI("DataCollectManagerService, start new Unsubscribe");
956 int32_t ret = FAILED;
957 SgUnsubscribeEvent event;
958 event.pid = IPCSkeleton::GetCallingPid();
959 event.time = SecurityGuardUtils::GetDate();
960 std::string eventGroup = AcquireDataSubscribeManager::GetInstance().GetCurrentClientGroup(clientId);
961 if (eventGroup == "securityGroup") {
962 ret = IsEventGroupHasPermission(eventGroup, {});
963 } else {
964 ret = IsEventGroupHasPublicPermission(eventGroup, {});
965 }
966 if (ret != SUCCESS) {
967 event.ret = ret;
968 BigData::ReportSgUnsubscribeEvent(event);
969 return ret;
970 }
971 ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(eventId, clientId);
972 if (ret != SUCCESS) {
973 SGLOGE("RemoveSubscribeRecord fail");
974 event.ret = ret;
975 BigData::ReportSgUnsubscribeEvent(event);
976 return ret;
977 }
978 event.ret = ret;
979 SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
980 BigData::ReportSgUnsubscribeEvent(event);
981 return ret;
982 }
983
DestoryClient(const std::string & eventGroup,const std::string & clientId)984 ErrCode DataCollectManagerService::DestoryClient(const std::string &eventGroup, const std::string &clientId)
985 {
986 SGLOGI("DataCollectManagerService, DestoryClient");
987 if (eventGroup == "") {
988 SGLOGE("event group empty");
989 return BAD_PARAM;
990 }
991 int32_t ret = 0;
992 if (eventGroup == "securityGroup") {
993 ret = IsEventGroupHasPermission(eventGroup, {});
994 } else {
995 ret = IsEventGroupHasPublicPermission(eventGroup, {});
996 }
997 if (ret != SUCCESS) {
998 SGLOGE("check permission fail");
999 return ret;
1000 }
1001 {
1002 std::lock_guard<std::mutex> lock(mutex_);
1003 auto iter = clientCallBacks_.find(clientId);
1004 if (iter == clientCallBacks_.end()) {
1005 SGLOGE("clientId not exist");
1006 return BAD_PARAM;
1007 }
1008 }
1009 ret = AcquireDataSubscribeManager::GetInstance().DestoryClient(eventGroup, clientId);
1010 if (ret != SUCCESS) {
1011 SGLOGI("AcquireDataSubscribeManager, DestoryClient ret=%{public}d", ret);
1012 return ret;
1013 }
1014 {
1015 std::lock_guard<std::mutex> lock(mutex_);
1016 if (deathRecipient_ != nullptr) {
1017 clientCallBacks_.at(clientId)->RemoveDeathRecipient(deathRecipient_);
1018 }
1019 clientCallBacks_.erase(clientId);
1020 }
1021 return SUCCESS;
1022 }
1023
CreatClient(const std::string & eventGroup,const std::string & clientId,const sptr<IRemoteObject> & cb)1024 ErrCode DataCollectManagerService::CreatClient(const std::string &eventGroup, const std::string &clientId,
1025 const sptr<IRemoteObject> &cb)
1026 {
1027 SGLOGI("DataCollectManagerService, CreatClient");
1028 if (eventGroup == "") {
1029 SGLOGE("event group empty");
1030 return BAD_PARAM;
1031 }
1032 int32_t ret = 0;
1033 if (eventGroup == "securityGroup") {
1034 ret = IsEventGroupHasPermission(eventGroup, {});
1035 } else {
1036 ret = IsEventGroupHasPublicPermission(eventGroup, {});
1037 }
1038 if (ret != SUCCESS) {
1039 SGLOGE("check permission fail");
1040 return ret;
1041 }
1042 if (cb == nullptr) {
1043 SGLOGE("cb is null");
1044 return NULL_OBJECT;
1045 }
1046 {
1047 std::lock_guard<std::mutex> lock(mutex_);
1048 if (clientCallBacks_.find(clientId) != clientCallBacks_.end()) {
1049 SGLOGE("clientId exist");
1050 return BAD_PARAM;
1051 }
1052 }
1053 SgSubscribeEvent event {};
1054 ret = AcquireDataSubscribeManager::GetInstance().CreatClient(eventGroup, clientId, cb);
1055 if (ret != SUCCESS) {
1056 SGLOGI("AcquireDataSubscribeManager, CreatClient ret=%{public}d", ret);
1057 return ret;
1058 }
1059 ret = SetDeathCallBack(event, cb);
1060 if (ret != SUCCESS) {
1061 return ret;
1062 }
1063 {
1064 std::lock_guard<std::mutex> lock(mutex_);
1065 clientCallBacks_[clientId] = cb;
1066 }
1067 return SUCCESS;
1068 }
1069 }