Merge pull request !62 from 王毅/master
This commit is contained in:
openharmony_ci 2024-10-08 09:29:28 +00:00 committed by Gitee
commit f5f00e8f4b
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
354 changed files with 9096 additions and 6463 deletions

View File

@ -28,6 +28,7 @@ group("sg_collect_service_build_module") {
if (is_standard_system) {
deps = [
"${sg_root_dir}/interfaces/inner_api/collect:libsg_collect_sdk",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager:libsg_data_collect_manager_sdk",
"${sg_root_dir}/interfaces/inner_api/obtaindata:libsg_obtaindata_sdk",
"${sg_root_dir}/services/data_collect:sg_collect_service",
"${sg_root_dir}/services/data_collect:sg_collect_service_database",
@ -35,6 +36,23 @@ group("sg_collect_service_build_module") {
}
}
group("security_guard_fuzz_test") {
testonly = true
deps = []
if (is_standard_system) {
deps += [
"${sg_root_dir}/test/fuzztest/classify:fuzztest",
"${sg_root_dir}/test/fuzztest/collect:fuzztest",
"${sg_root_dir}/test/fuzztest/config_manager:fuzztest",
"${sg_root_dir}/test/fuzztest/data_collect:fuzztest",
"${sg_root_dir}/test/fuzztest/inner_sdk:fuzztest",
"${sg_root_dir}/test/fuzztest/ipc:fuzztest",
"${sg_root_dir}/test/fuzztest/obtaindata:fuzztest",
"${sg_root_dir}/test/fuzztest/security_collector:fuzztest",
]
}
}
group("security_guard_napi") {
if (os_level == "standard") {
if (support_jsapi) {
@ -50,3 +68,31 @@ group("security_collector_service_build_module") {
]
}
}
group("security_guard_unit_test") {
testonly = true
if (is_standard_system) {
deps = [
"${sg_root_dir}/test/unittest/config_manager:unittest",
"${sg_root_dir}/test/unittest/data_collect:data_collect_test",
"${sg_root_dir}/test/unittest/data_collect:unittest",
"${sg_root_dir}/test/unittest/inner_api:unittest",
"${sg_root_dir}/test/unittest/model_manager:unittest",
"${sg_root_dir}/test/unittest/risk_classify:unittest",
"${sg_root_dir}/test/unittest/security_collector:security_collector_test",
"${sg_root_dir}/test/unittest/security_collector:unittest",
]
}
}
group("security_guard_build_module_test") {
testonly = true
deps = []
if (is_standard_system) {
deps += [
"${sg_root_dir}/interfaces/inner_api/classify/test:unittest",
"${sg_root_dir}/interfaces/inner_api/collect/test:unittest",
"${sg_root_dir}/interfaces/inner_api/obtaindata/test:unittest",
]
}
}

View File

@ -1,2 +1,2 @@
# security_guard
# SGout

View File

@ -1,86 +0,0 @@
# 设备风险管理平台
- 简介
- 目录
- 编译构建
- 说明
## 简介
设备风险管理平台SecurityGuard简称SG向应用提供风险分析能力包括root检测设备完整性检测物理真机检测等功能。
SG模块可以分为如下三大部分
- SG 接口层提供SG API供应用调用。
- SG 基础服务层实现SG数据管理、模型管理、配置管理、采集器管理等功能。
- SG 安全模型:
1越狱检测模型检测系统是否处于越狱的状态比如通过分析系统调用表、内核代码段是否会破坏来判断是越狱状态
2设备完整性检测模型检测设备是否处于完整的未被修改的状态比如通过分析boot状态是否有异常、设备是否被解锁来判断设备完整性状态
3物理机检测模型检测当前设备是物理机或模拟器
SG部件的主要结构如下图所示
![SG部件架架构图](figures/ohos_security_guard_architecture.png)
## 目录
```
├── build # 编译配置文件
├── frameworks # 框架代码, 作为基础功能目录, 被interfaces和services使用
├── interfaces # 接口API代码
│ ├── inner_api # inner api接口
│ └── kits # 对外api接口
├── services # 服务框架代码
│ ├── config_manager # SG 配置管理代码
│ ├── data_collect # SG 数据管理代码
│ ├── risk_classify # SG 模型管理代码
│ └── security_collector # SG 采集器管理代码
└── test # 测试代码存放目录
```
## 编译构建
以rk3568为例编译命令如下
```
./build.sh --product-name rk3568 --build-target security_guard --ccache
```
## 说明
### 接口说明
[接口文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-securityGuard.md)
### 事件ID编码规则
使用事件ID编码的方式对数据做分类编码原则如下
- 按照OH系统、厂商系统基于OH定制的系统两个维度定义编码
- OH系统的编码随社区独立演进代码合入社区时重新分配编码
- 厂商系统的编码有厂商自定义演进,不与社区编码重叠
事件ID编码分为三部分组成每部分采用三位16进制表示**子系统编码 + 部件编码 + 事件编码**
- 区分OH系统与厂商系统的子系统、部件、事件编码范围
OH系统使用 0x800 0xFFF
厂商系统使用: 0x000 0x7FF
- 新增编码从小到大自然增长;
事件ID示例
```
OH系统以82c800801编码为例
82c OH a子系统 800OH b部件、 801OH c事件
厂商系统以1002003编码为例
1 :厂商 x子系统 002 :厂商 y部件、 003 :厂商 z事件
```
### 模型编码规则:
使用易于开发者使用的字符串标识模型,提供两种分类:
1、Vender厂商预置的由OpenHarmory定义由厂商做差异化的能力
2、EDR类App下发模型由App做自定义模型的标识
## 相关仓
**安全子系统**
[security\_security\_guard](https://gitee.com/openharmony/security_security_guard)

View File

@ -1,5 +1,5 @@
{
"name": "@ohos/security_guard",
"name": "@openharmony/security_guard",
"description": "security_guard",
"version": "3.1.0",
"license": "Apache License 2.0",
@ -18,6 +18,7 @@
"hisysevent_config": [
"//base/security/security_guard/hisysevent.yaml"
],
"features": ["security_guard_enable"],
"adapted_system_type": [
"standard"
],
@ -37,8 +38,10 @@
"hilog",
"init",
"ipc",
"json",
"napi",
"netmanager_base",
"openssl",
"os_account",
"preferences",
"relational_store",
@ -46,12 +49,10 @@
"samgr",
"time_service",
"appverify",
"json",
"googletest",
"ffrt",
"bundle_framework"
],
"third_party": [
"openssl"
]
},
"build": {
@ -60,6 +61,9 @@
"//base/security/security_guard/sa_profile:security_guard.init",
"//base/security/security_guard/oem_property:security_audit_cfg",
"//base/security/security_guard/oem_property:security_guard_cfg",
"//base/security/security_guard/oem_property:real_time_upload_event_cfg",
"//base/security/security_guard/oem_property:config_update_trust_list_cfg",
"//base/security/security_guard/oem_property:config_update_trust_list_cfg",
"//base/security/security_guard/oem_property:security_guard_model_cfg",
"//base/security/security_guard/oem_property:security_guard_event_cfg",
"//base/security/security_guard:sg_classify_service_build_module",
@ -74,7 +78,8 @@
"name": "//base/security/security_guard/interfaces/inner_api/classify:libsg_classify_sdk",
"header": {
"header_files": [
"sg_classify_client.h"
"sg_classify_client.h",
"i_model.h"
],
"header_base": "//base/security/security_guard/interfaces/inner_api/classify/include"
}
@ -111,12 +116,21 @@
],
"header_base": "//base/security/security_guard/interfaces/inner_api/obtaindata/include"
}
},
{
"name": "//base/security/security_guard/interfaces/inner_api/data_collect_manager:libsg_data_collect_manager_sdk",
"header": {
"header_files": [
"data_collect_manager.h"
],
"header_base": "//base/security/security_guard/interfaces/inner_api/data_collect_manager/include"
}
}
],
"test": [
"//base/security/security_guard/test:security_guard_build_module_test",
"//base/security/security_guard/test:security_guard_fuzz_test",
"//base/security/security_guard/test:security_guard_unit_test"
"//base/security/security_guard:security_guard_build_module_test",
"//base/security/security_guard:security_guard_fuzz_test",
"//base/security/security_guard:security_guard_unit_test"
]
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

View File

@ -29,6 +29,7 @@ enum class DataCollectManagerInterfaceCode {
CMD_SECURITY_COLLECTOR_START = 6,
CMD_SECURITY_COLLECTOR_STOP = 7,
CMD_SECURITY_CONFIG_UPDATE = 8,
CMD_SECURITY_EVENT_CONFIG_QUERY = 9,
};
enum class DataCollectManagerCallbackInterfaceCode {

View File

@ -25,7 +25,7 @@
#include "security_event_ruler.h"
#include "security_event.h"
#include "security_config_update_info.h"
#include "security_event_config.h"
namespace OHOS::Security::SecurityGuard {
constexpr int32_t DATA_COLLECT_MANAGER_SA_ID = 3524;
@ -42,6 +42,7 @@ public:
CMD_SECURITY_COLLECTOR_START = static_cast<uint32_t>(InterfaceCode::CMD_SECURITY_COLLECTOR_START),
CMD_SECURITY_COLLECTOR_STOP = static_cast<uint32_t>(InterfaceCode::CMD_SECURITY_COLLECTOR_STOP),
CMD_SECURITY_CONFIG_UPDATE = static_cast<uint32_t>(InterfaceCode::CMD_SECURITY_CONFIG_UPDATE),
CMD_SECURITY_EVENT_CONFIG_QUERY = static_cast<uint32_t>(InterfaceCode::CMD_SECURITY_EVENT_CONFIG_QUERY),
};
virtual int32_t RequestDataSubmit(int64_t eventId, std::string &version, std::string &time,
@ -58,6 +59,7 @@ public:
virtual int32_t CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback) = 0;
virtual int32_t ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &updateInfo) = 0;
virtual int32_t QuerySecurityEventConfig(std::string &result) = 0;
};
class IDataCollectManagerCallback : public IRemoteBroker {

View File

@ -21,7 +21,6 @@
#define LOG_DOMAIN 0xD002F07
#include "hilog/log.h"
#include <cinttypes>
namespace OHOS::Security::SecurityCollector {

View File

@ -21,7 +21,7 @@
#define LOG_DOMAIN 0xD002F07
#include "hilog/log.h"
#include <cinttypes>
namespace OHOS::Security::SecurityGuard {
constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
LOG_CORE,

View File

@ -1,44 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/security/security_guard/security_guard.gni")
import("//build/ohos.gni")
ohos_source_set("sg_task_stamp") {
subsystem_name = "security"
part_name = "security_guard"
include_dirs = [
"${sg_root_dir}/frameworks/common/task_handler/include",
"${sg_root_dir}/frameworks/common/log/include",
]
sources =
[ "${sg_root_dir}/frameworks/common/task_handler/src/task_handler.cpp" ]
sanitize = {
integer_overflow = true
ubsan = true
boundary_sanitize = true
cfi = true
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"init:libbegetutil",
]
}

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "task_handler.h"
#include "security_guard_log.h"
namespace OHOS::Security::SecurityGuard {
namespace {
const int THREAD_NUMS = 5;
const int MAX_TASK_NUMS = 1000;
const int MINORS_THREAD_NUMS = 1;
const int MINORS_MAX_TASK_NUMS = 500;
}
TaskHandler::TaskHandler()
{
SGLOGE("TaskHandler is called .");
pool_.Start(THREAD_NUMS);
pool_.SetMaxTaskNum(MAX_TASK_NUMS);
minorsPool_.Start(MINORS_THREAD_NUMS);
minorsPool_.SetMaxTaskNum(MINORS_MAX_TASK_NUMS);
SGLOGE("TaskHandler end");
}
TaskHandler::~TaskHandler()
{
pool_.Stop();
minorsPool_.Stop();
}
void TaskHandler::AddTask(Task &task)
{
pool_.AddTask(task);
}
void TaskHandler::AddMinorsTask(Task &task)
{
minorsPool_.AddTask(task);
}
}

View File

@ -67,10 +67,12 @@ bool SecurityGuardUtils::StrToLL(const std::string &str, long long &value, int32
if ((errno == ERANGE && (value == LLONG_MAX || value == LLONG_MIN)) || (errno != 0 && value == 0)) {
SGLOGE("strtoll converse error,str=%{public}s", str.c_str());
return false;
} else if (end == add) {
}
if (end == add) {
SGLOGE("strtoll no digit find");
return false;
} else if (end[0] != '\0') {
}
if (end[0] != '\0') {
SGLOGE("strtoll no all digit");
return false;
}
@ -87,10 +89,12 @@ bool SecurityGuardUtils::StrToULL(const std::string &str, unsigned long long &va
if ((errno == ERANGE && value == ULLONG_MAX) || (errno != 0 && value == 0)) {
SGLOGE("strtoull converse error,str=%{public}s", str.c_str());
return false;
} else if (end == add) {
}
if (end == add) {
SGLOGE("strtoull no digit find");
return false;
} else if (end[0] != '\0') {
}
if (end[0] != '\0') {
SGLOGE("strtoull no all digit");
return false;
}
@ -114,9 +118,8 @@ std::string SecurityGuardUtils::GetDate()
bool SecurityGuardUtils::CopyFile(const std::string &srcPath, const std::string &dstPath)
{
std::ifstream src(srcPath, std::ios::binary);
if (!src.is_open() || !src) {
if (!src.is_open()) {
SGLOGE("copy file stream error");
src.close();
return false;
}
if (src.seekg(0, std::ios_base::end).tellg() > FILE_MAX_SIZE) {
@ -126,10 +129,9 @@ bool SecurityGuardUtils::CopyFile(const std::string &srcPath, const std::string
}
src.seekg(0, std::ios::beg);
std::ofstream dst(dstPath, std::ios::binary);
if (!dst.is_open() || !dst) {
if (!dst.is_open()) {
SGLOGE("copy file stream error");
src.close();
dst.close();
return false;
}

View File

@ -62,7 +62,7 @@ ohos_shared_library("securityguard_napi") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
deps = [ "${sg_root_dir}/interfaces/inner_api/collector:libsg_collector_sdk" ]

View File

@ -27,10 +27,12 @@ NapiSecurityEventQuerier::NapiSecurityEventQuerier(QuerySecurityEventContext *co
NapiSecurityEventQuerier::~NapiSecurityEventQuerier()
{
if (callbackContext_->threadId == getproctid()) {
napi_delete_reference(callbackContext_->env, callbackContext_->ref);
if (callbackContext_ != nullptr) {
if (callbackContext_->threadId == getproctid()) {
napi_delete_reference(callbackContext_->env, callbackContext_->ref);
}
delete callbackContext_;
}
delete callbackContext_;
};
napi_value NapiSecurityEventQuerier::NapiGetNamedProperty(const napi_env env, const napi_value &object,
@ -59,7 +61,7 @@ napi_value NapiSecurityEventQuerier::NapiCreateInt64(const napi_env env, int64_t
{
napi_value result = nullptr;
napi_status status = napi_create_int64(env, value, &result);
SGLOGI("create napi value of int64 type, value is %{public}" PRId64 ".", value);
SGLOGI("create napi value of int64 type, value is %{public}" PRId64, value);
if (status != napi_ok || result == nullptr) {
SGLOGE("failed to create napi value of int64 type.");
}
@ -92,7 +94,11 @@ void NapiSecurityEventQuerier::RunCallback(QuerySecurityEventContext *context, C
return;
}
QuerySecurityEventContext *tmpContext = new QuerySecurityEventContext(context);
QuerySecurityEventContext *tmpContext = new (std::nothrow) QuerySecurityEventContext(context);
if (tmpContext == nullptr) {
SGLOGE("tmpContext new failed, no memory left.");
return;
}
tmpContext->callback = callback;
tmpContext->release = release;
uv_work_t* work = new (std::nothrow) uv_work_t();
@ -102,10 +108,7 @@ void NapiSecurityEventQuerier::RunCallback(QuerySecurityEventContext *context, C
return;
}
work->data = reinterpret_cast<void *>(tmpContext);
uv_queue_work_with_qos(
loop,
work,
OnExecute,
uv_queue_work_with_qos(loop, work, OnExecute,
[] (uv_work_t *work, int status) {
SGLOGD("Begin uv work.");
if (work == nullptr || work->data == nullptr) {
@ -160,9 +163,11 @@ void NapiSecurityEventQuerier::OnQuery(const std::vector<SecurityCollector::Secu
napi_value eventId = NapiCreateInt64(env, napiEvents[i].GetEventId());
napi_value version = NapiCreateString(env, napiEvents[i].GetVersion().c_str());
napi_value content = NapiCreateString(env, napiEvents[i].GetContent().c_str());
napi_value timestamp = NapiCreateString(env, napiEvents[i].GetTimestamp().c_str());
napi_set_named_property(env, item, "eventId", eventId);
napi_set_named_property(env, item, "version", version);
napi_set_named_property(env, item, "content", content);
napi_set_named_property(env, item, "timestamp", timestamp);
status = napi_set_element(env, eventJsArray, i, item);
if (status != napi_ok) {
SGLOGE("napi_set_element failed, %{public}d", status);

View File

@ -54,7 +54,8 @@ constexpr int TIME_MAX_LEN = 15;
using NAPI_QUERIER_PAIR = std::pair<pid_t, std::shared_ptr<NapiSecurityEventQuerier>>;
static std::unordered_map<napi_ref, NAPI_QUERIER_PAIR> queriers;
static std::mutex g_mutex;
static std::mutex g_subscribeMutex;
static std::mutex g_queryMutex;
std::map<napi_env, std::vector<SubscribeCBInfo *>> g_subscribers;
static const std::unordered_map<int32_t, std::pair<int32_t, std::string>> g_errorStringMap = {
@ -109,7 +110,7 @@ static napi_value NapiCreateInt64(const napi_env env, int64_t value)
{
napi_value result = nullptr;
napi_status status = napi_create_int64(env, value, &result);
SGLOGI("create napi value of int64 type, value is %{public}" PRId64 ".", value);
SGLOGI("create napi value of int64 type, value is %{public}" PRId64, value);
if (status != napi_ok || result == nullptr) {
SGLOGE("failed to create napi value of int64 type.");
}
@ -189,6 +190,7 @@ static napi_value ParseInt64(napi_env env, napi_value object, const std::string
NAPI_CALL(env, napi_get_named_property(env, object, key.c_str(), &result));
if (result == nullptr) {
SGLOGE("get %{public}s failed", key.c_str());
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "get key failed."));
return nullptr;
}
@ -196,6 +198,7 @@ static napi_value ParseInt64(napi_env env, napi_value object, const std::string
NAPI_CALL(env, napi_typeof(env, result, &type));
if (type != napi_number) {
SGLOGE("type of param %{public}s is not number", key.c_str());
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "type of param is not number."));
return nullptr;
}
@ -216,6 +219,7 @@ static napi_value ParseInt32(napi_env env, napi_value object, const std::string
NAPI_CALL(env, napi_get_named_property(env, object, key.c_str(), &result));
if (result == nullptr) {
SGLOGE("get %{public}s failed", key.c_str());
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "get key failed."));
return nullptr;
}
@ -223,6 +227,7 @@ static napi_value ParseInt32(napi_env env, napi_value object, const std::string
NAPI_CALL(env, napi_typeof(env, result, &type));
if (type != napi_number) {
SGLOGE("type of param %{public}s is not number", key.c_str());
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "type of param is not number."));
return nullptr;
}
@ -376,7 +381,8 @@ static void RequestSecurityModelResultExecute(napi_env env, void *data)
promise->set_value(model);
return SUCCESS;
};
context->ret = SecurityGuardSdkAdaptor::RequestSecurityModelResult(context->deviceId, context->modelId, "", func);
context->ret =
SecurityGuardSdkAdaptor::RequestSecurityModelResult(context->deviceId, context->modelId, context->param, func);
if (context->ret != SUCCESS) {
SGLOGE("RequestSecurityModelResultSync error, ret=%{public}d", context->ret);
return;
@ -393,6 +399,9 @@ static void RequestSecurityModelResultExecute(napi_env env, void *data)
static napi_value GenerateSecurityModelResult(napi_env env, RequestSecurityModelResultContext *context)
{
napi_value ret = NapiCreateObject(env);
if (ret == nullptr) {
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "napi create object error ."));
}
napi_value deviceId = NapiCreateString(env, context->result.devId.c_str());
napi_value modelId = NapiCreateUint32(env, context->result.modelId);
napi_value result = NapiCreateString(env, context->result.result.c_str());
@ -441,7 +450,7 @@ static void RequestSecurityModelResultComplete(napi_env env, napi_status status,
delete context;
}
static napi_value ParseModelId(napi_env env, std::string modelNameStr, uint32_t &modelId)
static napi_value ParseModelId(napi_env env, const std::string &modelNameStr, uint32_t &modelId)
{
if (modelNameStr == "SecurityGuard_JailbreakCheck") {
modelId = ModelIdType::ROOT_SCAN_MODEL_ID;
@ -449,6 +458,8 @@ static napi_value ParseModelId(napi_env env, std::string modelNameStr, uint32_t
modelId = ModelIdType::DEVICE_COMPLETENESS_MODEL_ID;
} else if (modelNameStr == "SecurityGuard_SimulatorCheck") {
modelId = ModelIdType::PHYSICAL_MACHINE_DETECTION_MODEL_ID;
} else if (modelNameStr == "SecurityGuard_RiskFactorCheck") {
modelId = ModelIdType::SECURITY_RISK_FACTOR_MODEL_ID;
} else {
napi_throw(env, GenerateBusinessError(env, BAD_PARAM,
"Parameter error, please make sure using the correct model name"));
@ -528,6 +539,7 @@ static napi_value NapiGetModelResult(napi_env env, napi_callback_info info)
return nullptr;
}
context->modelId = modelId;
context->param = modelRule.param;
napi_value promise = nullptr;
NAPI_CALL(env, napi_create_promise(env, &context->deferred, &promise));
napi_value resourceName = NapiCreateString(env, "NapiGetModelResult");
@ -542,9 +554,10 @@ static napi_value ParsePolicyFileInfo(napi_env env, napi_value object, NapiSecur
napi_valuetype type = napi_undefined;
NAPI_CALL(env, napi_typeof(env, object, &type));
if (type != napi_object) {
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "type of param eventInfo is not object"));
GenerateBusinessError(env, BAD_PARAM, "type of param eventInfo is not object");
return nullptr;
}
if (ParseInt32(env, object, "fd", context->fd) == nullptr) {
return nullptr;
}
@ -567,7 +580,7 @@ static void UpdatePolicyExecute(napi_env env, void *data)
context->ret = SecurityGuardSdkAdaptor::ConfigUpdate(policyInfo);
if (context->ret != SUCCESS) {
SGLOGE("update policy file error, code=%{public}d", context->ret);
return;
return ;
}
}
@ -590,13 +603,12 @@ static void UpdatePolicyComplete(napi_env env, napi_status status, void *data)
static napi_value NapiUpdatePolicyFile(napi_env env, napi_callback_info info)
{
SGLOGD("in NapiUpdatePolicyFile");
size_t argc = NAPI_UPDATE_POLICY_FILE_ARGS_CNT;
napi_value argv[NAPI_UPDATE_POLICY_FILE_ARGS_CNT] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
if (argc != NAPI_UPDATE_POLICY_FILE_ARGS_CNT) {
SGLOGE("update policy file count is not expected");
std::string msg = "update policy file count is not expected";
SGLOGE("update policy file arg count is not expected");
std::string msg = "update policy arguments count is not expected";
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, msg));
return nullptr;
}
@ -606,12 +618,12 @@ static napi_value NapiUpdatePolicyFile(napi_env env, napi_callback_info info)
napi_throw(env, GenerateBusinessError(env, NULL_OBJECT, "context new failed, no memory left."));
return nullptr;
}
napi_value ret = ParsePolicyFileInfo(env, argv[0], context);
if (ret == nullptr) {
SGLOGE("policy file parse error");
delete context;
napi_throw(env, GenerateBusinessError(env, BAD_PARAM));
return nullptr;
}
napi_value promise = nullptr;
@ -620,6 +632,7 @@ static napi_value NapiUpdatePolicyFile(napi_env env, napi_callback_info info)
NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, UpdatePolicyExecute,
UpdatePolicyComplete, static_cast<void *>(context), &context->asyncWork));
NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork));
return promise;
}
@ -647,7 +660,7 @@ static bool ParseEventForNotifyCollector(napi_env env, napi_value object,
static napi_value NapiStartSecurityEventCollector(napi_env env, napi_callback_info info)
{
SGLOGD("===========================in NapiStartSecurityEventCollector");
SGLOGD("in NapiStartSecurityEventCollector");
size_t argc = NAPI_START_COLLECTOR_ARGS_CNT;
napi_value argv[NAPI_START_COLLECTOR_ARGS_CNT] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
@ -693,7 +706,7 @@ static napi_value NapiStartSecurityEventCollector(napi_env env, napi_callback_in
static napi_value NapiStopSecurityEventCollector(napi_env env, napi_callback_info info)
{
SGLOGD("===========================in NapiStopSecurityEventCollector");
SGLOGD("in NapiStopSecurityEventCollector");
size_t argc = NAPI_STOP_COLLECTOR_ARGS_CNT;
napi_value argv[NAPI_STOP_COLLECTOR_ARGS_CNT] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
@ -857,11 +870,10 @@ static napi_value NapiQuerySecurityEvent(napi_env env, napi_callback_info info)
}
size_t index = 0;
std::vector<SecurityEventRuler> rules;
if (auto ret = ParseSecurityEventRulers(env, argv[index], rules); ret != SUCCESS) {
if (auto ret = ParseSecurityEventRulers(env, argv[index++], rules); ret != SUCCESS) {
SGLOGE("failed to parse query rules, result code is %{public}d.", ret);
return nullptr;
}
index++;
if (IsValueTypeValid(env, argv[index], napi_valuetype::napi_null) ||
IsValueTypeValid(env, argv[index], napi_valuetype::napi_undefined)) {
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "Parameter error. The type of must querier be Querier."));
@ -880,7 +892,7 @@ static napi_value NapiQuerySecurityEvent(napi_env env, napi_callback_info info)
napi_get_reference_value(env, ref, &querier);
auto iter = CompareAndReturnCacheItem<NapiSecurityEventQuerier>(env, querier, queriers);
if (iter != queriers.end()) {
std::unique_lock<std::mutex> lock(g_mutex);
std::unique_lock<std::mutex> lock(g_queryMutex);
queriers.erase(iter->first);
NapiRequestDataManager::GetInstance().DelDataCallback(env);
}
@ -891,6 +903,7 @@ static napi_value NapiQuerySecurityEvent(napi_env env, napi_callback_info info)
SGLOGE("query error, code=%{public}d", code);
napi_throw(env, GenerateBusinessError(env, code));
}
std::unique_lock<std::mutex> lock(g_queryMutex);
queriers[context->ref] = std::make_pair(context->threadId, querier);
NapiRequestDataManager::GetInstance().AddDataCallback(env);
SGLOGI("NapiQuerySecurityEvent end.");
@ -922,6 +935,11 @@ static bool GetStringProperty(napi_env env, napi_value obj, std::string &propert
size_t propLen;
NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, obj, nullptr, 0, &propLen), false);
if (propLen > ALL_PROPERTY_MAX_LEN) {
SGLOGE("Parameter error. param is too long");
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "Parameter error. param is too long"));
return false;
}
property.reserve(propLen + 1);
property.resize(propLen);
NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, obj, property.data(), propLen + 1, &propLen), false);
@ -962,7 +980,7 @@ static bool ParseSubscribeForEventOccur(const napi_env &env, const std::string &
if (type != "securityEventOccur") {
std::string errMsg = "Parameter error. The param of type must be securityEventOccur.";
SGLOGE("Parameter error. The param of type must be securityEventOccur.");
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "Type ERROR!"));
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, errMsg));
return false;
}
SubscribeEventInfo eventInfo;
@ -1028,7 +1046,7 @@ static bool CompareOnAndOffRef(const napi_env env, napi_ref subscriberRef, napi_
static bool IsSubscribeInMap(napi_env env, SubscribeCBInfo *info)
{
std::lock_guard<std::mutex> lock(g_mutex);
std::lock_guard<std::mutex> lock(g_subscribeMutex);
auto subscribe = g_subscribers.find(env);
if (subscribe == g_subscribers.end()) {
return false;
@ -1101,9 +1119,12 @@ static bool ParseParaToUnsubscriber(const napi_env &env, napi_callback_info cbIn
static napi_value GenerateEvent(napi_env env, const NapiSecurityEvent &event)
{
napi_value ret = NapiCreateObject(env);
if (ret == nullptr) {
napi_throw(env, GenerateBusinessError(env, BAD_PARAM, "napi create object error ."));
}
napi_value eventId = NapiCreateInt64(env, event.eventId);
napi_value version = NapiCreateString(env, event.version.c_str());
napi_value content = NapiCreateString(env, event.content.c_str());
napi_value version = NapiCreateString(env, event.version);
napi_value content = NapiCreateString(env, event.content);
napi_set_named_property(env, ret, NAPI_EVENT_EVENT_ID_ATTR, eventId);
napi_set_named_property(env, ret, NAPI_EVENT_VERSION_ATTR, version);
@ -1111,6 +1132,101 @@ static napi_value GenerateEvent(napi_env env, const NapiSecurityEvent &event)
return ret;
}
static bool InitUvWorkCallbackEnv(CommonAsyncContext *data, napi_handle_scope *scope)
{
if (data == nullptr) {
SGLOGE("data is nullptr");
return false;
}
napi_open_handle_scope(data->env, scope);
if (scope == nullptr) {
SGLOGE("fail to open scope");
delete data;
data = nullptr;
return false;
}
return true;
}
static void UvQueueWorkOnSecEventsChanged(uv_work_t *work, int status)
{
SGLOGI("UvQueueWorkOnSecEventsChanged");
if (work == nullptr) {
SGLOGE("work is nullptr");
return;
}
napi_handle_scope scope = nullptr;
if (!InitUvWorkCallbackEnv(reinterpret_cast<CommonAsyncContext *>(work->data), &scope)) {
return;
}
std::unique_ptr<SubscriberOAWorker> subscriberOAWorkerData(reinterpret_cast<SubscriberOAWorker *>(work->data));
bool isFound = false;
{
std::lock_guard<std::mutex> lock(g_subscribeMutex);
SubscriberPtr *subscriber = subscriberOAWorkerData->subscriber;
for (auto subscriberInstance : g_subscribers) {
isFound = std::any_of(subscriberInstance.second.begin(), subscriberInstance.second.end(),
[subscriber](const SubscribeCBInfo *item) {
return item->subscriber.get() == subscriber;
});
if (isFound) {
SGLOGI("subscriber has been found.");
break;
}
}
}
if (isFound) {
napi_value result[ARGS_SIZE_ONE] = {nullptr};
result[PARAMZERO] = GenerateEvent(subscriberOAWorkerData->env, subscriberOAWorkerData->event);
napi_value undefined = nullptr;
napi_get_undefined(subscriberOAWorkerData->env, &undefined);
napi_value callback = nullptr;
napi_get_reference_value(subscriberOAWorkerData->env, subscriberOAWorkerData->ref, &callback);
napi_value resultOut = nullptr;
napi_status ok = napi_call_function(subscriberOAWorkerData->env, undefined, callback, ARGS_SIZE_ONE,
&result[0], &resultOut);
SGLOGI("isOk=%{public}d", ok);
}
napi_close_handle_scope(subscriberOAWorkerData->env, scope);
}
static int32_t OnNotifyEvent(const Event &event, napi_env env, napi_ref ref, SubscriberPtr *subscriber)
{
SGLOGI("OnNotify");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(env, &loop);
if (loop == nullptr) {
SGLOGE("loop instance is nullptr");
return -1;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
SGLOGE("insufficient memory for work!");
return -1;
}
SubscriberOAWorker *subscriberOAWorker = new (std::nothrow) SubscriberOAWorker();
if (subscriberOAWorker == nullptr) {
SGLOGE("insufficient memory for SubscriberAccountsWorker!");
delete work;
return -1;
}
subscriberOAWorker->event.eventId = event.eventId;
subscriberOAWorker->event.version = event.version;
subscriberOAWorker->event.content = event.content;
subscriberOAWorker->event.timestamp = event.timestamp;
subscriberOAWorker->env = env;
subscriberOAWorker->ref = ref;
subscriberOAWorker->subscriber = subscriber;
work->data = reinterpret_cast<void *>(subscriberOAWorker);
uv_queue_work_with_qos(loop, work, [](uv_work_t *work) {
SGLOGD("UvQueueWorkOnSecEventsChanged...");
}, UvQueueWorkOnSecEventsChanged, uv_qos_default);
return 0;
}
class SubscriberPtr : public ICollectorSubscriber {
public:
explicit SubscriberPtr(const Event &event) : ICollectorSubscriber(event) {};
@ -1118,102 +1234,13 @@ public:
int32_t OnNotify(const Event &event) override
{
SGLOGI("OnNotify");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(env_, &loop);
if (loop == nullptr) {
SGLOGE("loop instance is nullptr");
if (OnNotifyEvent(event, env_, ref_, this) != 0) {
return -1;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
SGLOGE("insufficient memory for work!");
return -1;
}
SubscriberOAWorker *subscriberOAWorker = new (std::nothrow) SubscriberOAWorker();
if (subscriberOAWorker == nullptr) {
SGLOGE("insufficient memory for SubscriberAccountsWorker!");
delete work;
return -1;
}
subscriberOAWorker->event.eventId = event.eventId;
subscriberOAWorker->event.version = event.version;
subscriberOAWorker->event.content = event.content;
subscriberOAWorker->event.timestamp = event.timestamp;
subscriberOAWorker->env = env_;
subscriberOAWorker->ref = ref_;
subscriberOAWorker->subscriber = this;
work->data = reinterpret_cast<void *>(subscriberOAWorker);
uv_queue_work_with_qos(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnAccountsChanged, uv_qos_default);
return 0;
};
static bool InitUvWorkCallbackEnv(uv_work_t *work, napi_handle_scope &scope)
{
if (work == nullptr) {
SGLOGE("work is nullptr");
return false;
}
if (work->data == nullptr) {
SGLOGE("data is nullptr");
return false;
}
CommonAsyncContext *data = reinterpret_cast<CommonAsyncContext *>(work->data);
napi_open_handle_scope(data->env, &scope);
if (scope == nullptr) {
SGLOGE("fail to open scope");
delete data;
work->data = nullptr;
return false;
}
return true;
}
static void UvQueueWorkOnAccountsChanged(uv_work_t *work, int status)
{
SGLOGI("UvQueueWorkOnAccountsChanged");
std::unique_ptr<uv_work_t> workPtr(work);
napi_handle_scope scope = nullptr;
if (!InitUvWorkCallbackEnv(work, scope)) {
return;
}
std::unique_ptr<SubscriberOAWorker> subscriberOAWorkerData(reinterpret_cast<SubscriberOAWorker *>(work->data));
bool isFound = false;
{
std::lock_guard<std::mutex> lock(g_mutex);
SubscriberPtr *subscriber = subscriberOAWorkerData->subscriber;
for (auto subscriberInstance : g_subscribers) {
isFound = std::any_of(subscriberInstance.second.begin(), subscriberInstance.second.end(),
[subscriber](const SubscribeCBInfo *item) {
return item->subscriber.get() == subscriber;
});
if (isFound) {
SGLOGI("subscriber has been found.");
break;
}
}
}
if (isFound) {
napi_value result[ARGS_SIZE_ONE] = {nullptr};
result[PARAMZERO] = GenerateEvent(subscriberOAWorkerData->env, subscriberOAWorkerData->event);
napi_value undefined = nullptr;
napi_get_undefined(subscriberOAWorkerData->env, &undefined);
napi_value callback = nullptr;
napi_get_reference_value(subscriberOAWorkerData->env, subscriberOAWorkerData->ref, &callback);
napi_value resultOut = nullptr;
napi_status ok = napi_call_function(subscriberOAWorkerData->env, undefined, callback, ARGS_SIZE_ONE,
&result[0], &resultOut);
SGLOGI("isOk=%{public}d", ok);
}
napi_close_handle_scope(subscriberOAWorkerData->env, scope);
}
void SetEnv(const napi_env &env) { env_ = env; }
void SetCallbackRef(const napi_ref &ref) { ref_ = ref; }
private:
napi_env env_ = nullptr;
napi_ref ref_ = nullptr;
@ -1246,7 +1273,7 @@ static napi_value Subscribe(napi_env env, napi_callback_info cbInfo)
napi_throw(env, GenerateBusinessError(env, errCode, "Subscribe failed!"));
return WrapVoidToJS(env);
} else {
std::lock_guard<std::mutex> lock(g_mutex);
std::lock_guard<std::mutex> lock(g_subscribeMutex);
g_subscribers[env].emplace_back(info);
}
return WrapVoidToJS(env);
@ -1254,7 +1281,7 @@ static napi_value Subscribe(napi_env env, napi_callback_info cbInfo)
static void UnsubscribeSync(napi_env env, UnsubscribeCBInfo *unsubscribeCBInfo)
{
std::lock_guard<std::mutex> lock(g_mutex);
std::lock_guard<std::mutex> lock(g_subscribeMutex);
auto subscribe = g_subscribers.find(env);
if (subscribe == g_subscribers.end()) {
return;

View File

@ -32,6 +32,7 @@ constexpr int DEVICE_ID_MAX_LEN = 64;
constexpr int FILE_NAME_MAX_LEN = 64;
constexpr int MODEL_NAME_MAX_LEN = 64;
constexpr int PARAM_MAX_LEN = 900;
constexpr int ALL_PROPERTY_MAX_LEN = 2048;
constexpr int NAPI_ON_RESULT_ARGS_CNT = 3;
constexpr char NAPI_ON_RESULT_ATTR[] = "onResult";
constexpr char NAPI_SECURITY_MODEL_RESULT_DEVICE_ID_ATTR[] = "deviceId";
@ -62,6 +63,7 @@ struct RequestSecurityModelResultContext {
napi_deferred deferred;
napi_async_work asyncWork;
std::string deviceId;
std::string param;
uint32_t modelId;
OHOS::Security::SecurityGuard::SecurityModel result;
int32_t ret;
@ -110,6 +112,7 @@ struct NapiSecurityPolicyFileInfo {
int32_t fd;
int32_t ret;
};
using CALLBACK_FUNC = std::function<void(const napi_env, const napi_ref, pid_t threadId,
const std::vector<OHOS::Security::SecurityCollector::SecurityEvent> &napiEvents)>;
using RELEASE_FUNC = std::function<void(pid_t threadId)>;
@ -140,6 +143,7 @@ enum ModelIdType : uint32_t {
DEVICE_COMPLETENESS_MODEL_ID = 3001000001,
PHYSICAL_MACHINE_DETECTION_MODEL_ID = 3001000002,
SECURITY_AUDIT_MODEL_ID = 3001000003,
SECURITY_RISK_FACTOR_MODEL_ID = 3001000009,
};
enum JsErrCode : int32_t {
@ -182,7 +186,7 @@ struct CommonAsyncContext {
struct SubscribeCBInfo : public CommonAsyncContext {
explicit SubscribeCBInfo(napi_env napiEnv,
std::thread::id thId) : CommonAsyncContext(napiEnv, thId) {};
OHOS::Security::SecurityCollector::Event events;
OHOS::Security::SecurityCollector::Event events {};
std::shared_ptr<SubscriberPtr> subscriber = nullptr;
};
@ -192,9 +196,8 @@ struct UnsubscribeCBInfo : public CommonAsyncContext {
std::vector<std::shared_ptr<SubscriberPtr>> subscribers;
};
struct SubscriberOAWorker : public CommonAsyncContext {
NapiSecurityEvent event;
NapiSecurityEvent event {};
napi_ref ref = nullptr;
SubscriberPtr *subscriber = nullptr;
};

View File

@ -15,7 +15,7 @@
#include <set>
#include "security_guard_sdk_adaptor.h"
#include <cinttypes>
#include "iservice_registry.h"
#include "data_collect_manager_callback_service.h"
@ -38,7 +38,7 @@ namespace {
const std::set<int64_t> GRANTED_EVENT{1037000001, 1064001001, 1064001002};
static std::mutex g_mutex;
}
sptr<IRemoteObject> SecurityGuardSdkAdaptor::object_ = nullptr;
sptr<IDataCollectManager> SecurityGuardSdkAdaptor::proxy_ = nullptr;
std::map<std::shared_ptr<SecurityCollector::ICollectorSubscriber>,
sptr<AcquireDataManagerCallbackService>> SecurityGuardSdkAdaptor::subscribers_ {};
std::mutex SecurityGuardSdkAdaptor::objMutex_;
@ -67,6 +67,7 @@ int32_t SecurityGuardSdkAdaptor::RequestSecurityEventInfo(std::string &devId, st
int32_t SecurityGuardSdkAdaptor::RequestSecurityModelResult(const std::string &devId, uint32_t modelId,
const std::string &param, ResultCallback callback)
{
SGLOGI("enter SecurityGuardSdkAdaptor RequestSecurityModelResult");
auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (registry == nullptr) {
SGLOGE("GetSystemAbilityManager error");
@ -92,6 +93,7 @@ int32_t SecurityGuardSdkAdaptor::RequestSecurityModelResult(const std::string &d
int32_t SecurityGuardSdkAdaptor::ReportSecurityInfo(const std::shared_ptr<EventInfo> &info)
{
SGLOGD("enter SecurityGuardSdkAdaptor ReportSecurityInfo");
if (info == nullptr) {
return BAD_PARAM;
}
@ -167,6 +169,7 @@ int32_t SecurityGuardSdkAdaptor::NotifyCollector(const SecurityCollector::Event
int32_t SecurityGuardSdkAdaptor::StartCollector(const SecurityCollector::Event &event,
int64_t duration)
{
SGLOGI("enter SecurityGuardSdkAdaptor StartCollector");
auto proxy = LoadDataCollectManageService();
if (proxy == nullptr) {
SGLOGE("proxy is null");
@ -188,7 +191,7 @@ int32_t SecurityGuardSdkAdaptor::StartCollector(const SecurityCollector::Event &
int32_t SecurityGuardSdkAdaptor::StopCollector(const SecurityCollector::Event &event)
{
SGLOGD("in SecurityGuardSdkAdaptor StopCollector ************");
SGLOGI("in SecurityGuardSdkAdaptor StopCollector");
auto proxy = LoadDataCollectManageService();
if (proxy == nullptr) {
SGLOGE("proxy is null");
@ -211,6 +214,7 @@ int32_t SecurityGuardSdkAdaptor::StopCollector(const SecurityCollector::Event &e
int32_t SecurityGuardSdkAdaptor::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
std::shared_ptr<SecurityEventQueryCallback> callback)
{
SGLOGI("enter SecurityGuardSdkAdaptor QuerySecurityEvent");
auto proxy = LoadDataCollectManageService();
if (proxy == nullptr) {
SGLOGE("proxy is null");
@ -233,6 +237,7 @@ int32_t SecurityGuardSdkAdaptor::QuerySecurityEvent(std::vector<SecurityCollecto
int32_t SecurityGuardSdkAdaptor::Subscribe(const std::shared_ptr<SecurityCollector::ICollectorSubscriber> &subscriber)
{
SGLOGI("enter SecurityGuardSdkAdaptor Subscribe");
if (subscriber == nullptr) {
SGLOGE("subscriber is nullptr");
return NULL_OBJECT;
@ -267,6 +272,7 @@ int32_t SecurityGuardSdkAdaptor::Subscribe(const std::shared_ptr<SecurityCollect
int32_t SecurityGuardSdkAdaptor::Unsubscribe(const std::shared_ptr<SecurityCollector::ICollectorSubscriber> &subscriber)
{
SGLOGI("enter SecurityGuardSdkAdaptor Unsubscribe");
if (subscriber == nullptr) {
SGLOGE("subscriber is nullptr");
return NULL_OBJECT;
@ -297,21 +303,23 @@ int32_t SecurityGuardSdkAdaptor::Unsubscribe(const std::shared_ptr<SecurityColle
sptr<IDataCollectManager> SecurityGuardSdkAdaptor::LoadDataCollectManageService()
{
std::lock_guard<std::mutex> lock(objMutex_);
if (object_ != nullptr) {
SGLOGI("object_ not null");
return iface_cast<IDataCollectManager>(object_);
if (proxy_ != nullptr) {
SGLOGI("proxy_ not null");
return proxy_;
}
auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (registry == nullptr) {
SGLOGE("GetSystemAbilityManager error");
return nullptr;
}
object_ = registry->GetSystemAbility(DATA_COLLECT_MANAGER_SA_ID);
return iface_cast<IDataCollectManager>(object_);
auto object = registry->GetSystemAbility(DATA_COLLECT_MANAGER_SA_ID);
proxy_ = iface_cast<IDataCollectManager>(object);
return proxy_;
}
int32_t SecurityGuardSdkAdaptor::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &updateInfo)
{
SGLOGI("enter SecurityGuardSdkAdaptor ConfigUpdate");
auto proxy = LoadDataCollectManageService();
if (proxy == nullptr) {
SGLOGE("proxy is null");

View File

@ -47,7 +47,7 @@ private:
static std::map<std::shared_ptr<SecurityCollector::ICollectorSubscriber>,
sptr<AcquireDataManagerCallbackService>> subscribers_;
static sptr<IDataCollectManager> LoadDataCollectManageService();
static sptr<IRemoteObject> object_;
static sptr<IDataCollectManager> proxy_;
static std::mutex objMutex_;
};
} // OHOS::Security::SecurityGuard

View File

@ -39,7 +39,7 @@ void AcquireDataManager::DeathRecipient::OnRemoteDied(const wptr<IRemoteObject>
void AcquireDataManager::HandleDecipient()
{
std::lock_guard<std::mutex> lock(mutex_);
callback_ = nullptr;
eventListeners_.clear();
}
int32_t AcquireDataManager::Subscribe(const std::shared_ptr<SecurityCollector::ICollectorSubscriber> &subscriber)
@ -49,6 +49,12 @@ int32_t AcquireDataManager::Subscribe(const std::shared_ptr<SecurityCollector::I
SGLOGE("subscriber is nullptr");
return NULL_OBJECT;
}
if (eventListeners_.find(subscriber) != eventListeners_.end()) {
SGLOGE("Already subscribed");
return BAD_PARAM;
}
auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (registry == nullptr) {
SGLOGE("GetSystemAbilityManager error");
@ -81,8 +87,10 @@ int32_t AcquireDataManager::Subscribe(const std::shared_ptr<SecurityCollector::I
}
int32_t ret = proxy->Subscribe(subscriber->GetSubscribeInfo(), callback);
if (ret == SUCCESS) {
eventListeners_[subscriber] = callback;
}
SGLOGI("Subscribe result, ret=%{public}d", ret);
callback_ = callback;
return ret;
}
@ -95,6 +103,11 @@ int32_t AcquireDataManager::Unsubscribe(const std::shared_ptr<SecurityCollector:
return NULL_OBJECT;
}
if (eventListeners_.find(subscriber) == eventListeners_.end()) {
SGLOGE("Not subscribed");
return BAD_PARAM;
}
auto object = registry->GetSystemAbility(DATA_COLLECT_MANAGER_SA_ID);
auto proxy = iface_cast<IDataCollectManager>(object);
if (proxy == nullptr) {
@ -102,9 +115,9 @@ int32_t AcquireDataManager::Unsubscribe(const std::shared_ptr<SecurityCollector:
return NULL_OBJECT;
}
int32_t ret = proxy->Unsubscribe(callback_);
int32_t ret = proxy->Unsubscribe(eventListeners_[subscriber]);
SGLOGI("Unsubscribe result, ret=%{public}d", ret);
callback_ = nullptr;
eventListeners_.erase(subscriber);
return ret;
}
}

View File

@ -14,7 +14,7 @@
*/
#include "acquire_data_manager_callback_service.h"
#include <cinttypes>
#include "security_guard_define.h"
#include "security_guard_log.h"
@ -22,7 +22,7 @@ namespace OHOS::Security::SecurityGuard {
int32_t AcquireDataManagerCallbackService::OnNotify(const SecurityCollector::Event &event)
{
SGLOGD("callback eventId=%{public}" PRId64 "", event.eventId);
SGLOGD("callback eventId=%{public}" PRId64, event.eventId);
if (subscriber_ != nullptr) {
subscriber_->OnNotify(event);
}

View File

@ -30,7 +30,7 @@ int32_t AcquireDataManagerCallbackStub::OnRemoteRequest(uint32_t code, MessagePa
if (code == AcquireDataManagerCallbackStub::CMD_DATA_SUBSCRIBE_CALLBACK) {
uint32_t expected = sizeof(uint32_t);
uint32_t actual = data.GetReadableBytes();
if (expected >= actual) {
if (actual <= expected) {
SGLOGE("actual length error, value=%{public}u", actual);
return BAD_PARAM;
}

View File

@ -58,7 +58,7 @@ ohos_shared_library("libsg_classify_sdk") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",

View File

@ -30,13 +30,13 @@ int32_t RiskAnalysisManagerCallbackStub::OnRemoteRequest(uint32_t code, MessageP
if (code == RiskAnalysisManagerCallbackStub::CMD_SET_SECURITY_MODEL_RESULT) {
uint32_t expected = sizeof(uint32_t);
uint32_t actual = data.GetReadableBytes();
if (expected >= actual) {
if (actual <= expected) {
SGLOGE("actual length error, value=%{public}u", actual);
return BAD_PARAM;
}
uint32_t modelId = data.ReadUint32();
std::string devId = data.ReadString();
std::string devId = {};
std::string result = data.ReadString();
return ResponseSecurityModelResult(devId, modelId, result);
}

View File

@ -27,6 +27,7 @@ RiskAnalysisManagerProxy::RiskAnalysisManagerProxy(const sptr<IRemoteObject> &im
int32_t RiskAnalysisManagerProxy::RequestSecurityModelResult(const std::string &devId, uint32_t modelId,
const std::string &param, const sptr<IRemoteObject> &callback)
{
SGLOGI("enter RiskAnalysisManagerProxy RequestSecurityModelResult");
MessageParcel data;
MessageParcel reply;
@ -34,13 +35,18 @@ int32_t RiskAnalysisManagerProxy::RequestSecurityModelResult(const std::string &
SGLOGE("WriteInterfaceToken error");
return WRITE_ERR;
}
data.WriteString(devId);
data.WriteUint32(modelId);
data.WriteString(param);
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_GET_SECURITY_MODEL_RESULT, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_GET_SECURITY_MODEL_RESULT, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -63,7 +69,12 @@ int32_t RiskAnalysisManagerProxy::SetModelState(uint32_t modelId, bool enable)
data.WriteBool(enable);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SET_MODEL_STATE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SET_MODEL_STATE, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;

View File

@ -28,11 +28,13 @@ ohos_unittest("libsg_classify_sdk_test") {
sources = [ "unittest/src/risk_classify_kit_test.cpp" ]
deps = [ "${sg_root_dir}/interfaces/inner_api/classify:libsg_classify_sdk" ]
deps = [
"${sg_root_dir}/interfaces/inner_api/classify:libsg_classify_sdk",
"//third_party/googletest:gmock",
]
external_deps = [
"c_utils:utils",
"googletest:gmock",
"hilog:libhilog",
]
}

View File

@ -69,7 +69,7 @@ ohos_shared_library("libsg_collect_sdk") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",

View File

@ -27,9 +27,9 @@
#ifdef __cplusplus
extern "C" {
#endif
int32_t ReportSecurityInfo(const struct EventInfoSt *info);
int32_t SecurityGuardConfigUpdate(int32_t fd, const char *fileName);
#ifdef __cplusplus
}
#endif
@ -38,6 +38,7 @@ namespace OHOS::Security::SecurityGuard {
class NativeDataCollectKit {
public:
static int32_t ReportSecurityInfo(const std::shared_ptr<EventInfo> &info);
static int32_t SecurityGuardConfigUpdate(int32_t fd, const std::string &fileName);
};
class SgCollectClient {

View File

@ -31,6 +31,7 @@ SgCollectClient &SgCollectClient::GetInstance()
sptr<IDataCollectManager> SgCollectClient::GetProxy()
{
std::lock_guard<std::mutex> lock(proxyMutex_);
if (proxy_ == nullptr) {
InitProxy();
}
@ -39,7 +40,6 @@ sptr<IDataCollectManager> SgCollectClient::GetProxy()
void SgCollectClient::InitProxy()
{
std::lock_guard<std::mutex> lock(proxyMutex_);
if (proxy_ == nullptr) {
auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (registry == nullptr) {
@ -99,17 +99,34 @@ int32_t NativeDataCollectKit::ReportSecurityInfo(const std::shared_ptr<EventInfo
}
return SUCCESS;
}
int32_t NativeDataCollectKit::SecurityGuardConfigUpdate(int32_t fd, const std::string &name)
{
sptr<IDataCollectManager> proxy = SgCollectClient::GetInstance().GetProxy();
if (proxy == nullptr) {
SGLOGE("proxy is nullptr");
return NULL_OBJECT;
}
SecurityGuard::SecurityConfigUpdateInfo updateInfo(fd, name);
int32_t ret = proxy->ConfigUpdate(updateInfo);
if (ret != SUCCESS) {
SGLOGE("ConfigUpdate error, ret=%{public}d", ret);
return ret;
}
return SUCCESS;
}
} // namespace OHOS::Security::SecurityGuard
static int32_t ReportSecurityInfoImpl(const struct EventInfoSt *info)
{
if (info == nullptr || info->contentLen >= CONTENT_MAX_LEN) {
if (info == nullptr || info->contentLen >= CONTENT_MAX_LEN || info->version == nullptr) {
return OHOS::Security::SecurityGuard::BAD_PARAM;
}
int64_t eventId = info->eventId;
std::string version = reinterpret_cast<const char *>(info->version);
uint8_t tmp[CONTENT_MAX_LEN] = {};
(void) memset_s(tmp, CONTENT_MAX_LEN, 0, CONTENT_MAX_LEN);
(void)memset_s(tmp, CONTENT_MAX_LEN, 0, CONTENT_MAX_LEN);
errno_t rc = memcpy_s(tmp, CONTENT_MAX_LEN, info->content, info->contentLen);
if (rc != EOK) {
return OHOS::Security::SecurityGuard::NULL_OBJECT;
@ -128,6 +145,10 @@ int32_t ReportSecurityInfo(const struct EventInfoSt *info)
return ReportSecurityInfoImpl(info);
}
int32_t SecurityGuardConfigUpdate(int32_t fd, const char *fileName)
{
return OHOS::Security::SecurityGuard::NativeDataCollectKit::SecurityGuardConfigUpdate(fd, fileName);
}
#ifdef __cplusplus
}
#endif

View File

@ -28,13 +28,16 @@ ohos_unittest("libsg_collect_sdk_test") {
sources = [ "unittest/src/data_collect_kit_test.cpp" ]
deps = [ "${sg_root_dir}/interfaces/inner_api/collect:libsg_collect_sdk" ]
deps = [
"${sg_root_dir}/interfaces/inner_api/collect:libsg_collect_sdk",
"//third_party/googletest:gmock",
]
external_deps = [
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
"c_utils:utils",
"googletest:gmock",
"hilog:libhilog",
]
}

View File

@ -19,6 +19,7 @@
#include "nativetoken_kit.h"
#include "securec.h"
#include "token_setproc.h"
#include "accesstoken_kit.h"
#define private public
#include "security_guard_define.h"
#include "sg_collect_client.h"
@ -53,6 +54,7 @@ void DataCollectKitTest::SetUpTestCase()
};
tokenId = GetAccessTokenId(&infoParams);
SetSelfTokenID(tokenId);
AccessToken::AccessTokenKit::ReloadNativeTokenInfo();
string isEnforcing;
LoadStringFromFile("/sys/fs/selinux/enforce", isEnforcing);
if (isEnforcing.compare("1") == 0) {
@ -224,4 +226,9 @@ HWTEST_F(DataCollectKitTest, DeathRecipient001, TestSize.Level1)
SecurityGuard::SgCollectClientDeathRecipient();
recipient.OnRemoteDied(nullptr);
}
HWTEST_F(DataCollectKitTest, ConfigUpdate001, TestSize.Level1)
{
EXPECT_NE(SecurityGuardConfigUpdate(-1, "test"), SecurityGuard::SUCCESS);
}
}

View File

@ -68,7 +68,7 @@ ohos_shared_library("libsg_collector_sdk") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",

View File

@ -39,7 +39,6 @@ public:
std::vector<SecurityEvent> &events);
int32_t CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo &subscriber);
int32_t CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscriber);
private:
void HandleDecipient();
std::mutex mutex_{};

View File

@ -24,13 +24,15 @@ namespace OHOS::Security::SecurityCollector {
class SecurityEvent : public Parcelable {
public:
SecurityEvent() = default;
SecurityEvent(int64_t eventId, const std::string &version = "", const std::string &content = "")
: eventId_(eventId), version_(version), content_(content) {};
SecurityEvent(int64_t eventId, const std::string &version = "",
const std::string &content = "", const std::string &timestamp = "")
: eventId_(eventId), version_(version), content_(content), timestamp_(timestamp) {};
~SecurityEvent() override = default;
int64_t GetEventId() const { return eventId_; };
std::string GetVersion() const { return version_; };
std::string GetContent() const { return content_; };
std::string GetTimestamp() const { return timestamp_; };
bool Marshalling(Parcel& parcel) const override;
bool ReadFromParcel(Parcel &parcel);
static SecurityEvent* Unmarshalling(Parcel& parcel);
@ -39,6 +41,7 @@ private:
int64_t eventId_;
std::string version_;
std::string content_;
std::string timestamp_;
};
} // namespace OHOS::Security::SecurityCollector

View File

@ -24,6 +24,7 @@
namespace OHOS::Security::SecurityCollector {
int32_t CollectorManager::Subscribe(const std::shared_ptr<ICollectorSubscriber> &subscriber)
{
LOGI("enter CollectorManager Subscribe");
if (subscriber == nullptr) {
LOGE("subscriber is null");
return BAD_PARAM;
@ -68,6 +69,7 @@ int32_t CollectorManager::Subscribe(const std::shared_ptr<ICollectorSubscriber>
int32_t CollectorManager::Unsubscribe(const std::shared_ptr<ICollectorSubscriber> &subscriber)
{
LOGI("enter CollectorManager Unsubscribe");
if (subscriber == nullptr) {
LOGE("subscriber is null");
return BAD_PARAM;
@ -134,7 +136,7 @@ int32_t CollectorManager::QuerySecurityEvent(const std::vector<SecurityEventRule
int32_t CollectorManager::CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo &subscriber)
{
LOGI("begin CollectorStart");
LOGI("enter CollectorManager CollectorStart");
auto object = CollectorServiceLoader::GetInstance().LoadCollectorService();
auto proxy = iface_cast<ISecurityCollectorManager>(object);
if (proxy == nullptr) {
@ -158,7 +160,7 @@ int32_t CollectorManager::CollectorStart(const SecurityCollector::SecurityCollec
int32_t CollectorManager::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscriber)
{
LOGI("begin CollectorStart");
LOGI("enter CollectorManager CollectorStart");
auto object = CollectorServiceLoader::GetInstance().LoadCollectorService();
auto proxy = iface_cast<ISecurityCollectorManager>(object);
if (proxy == nullptr) {
@ -173,10 +175,10 @@ int32_t CollectorManager::CollectorStop(const SecurityCollector::SecurityCollect
}
int32_t ret = proxy->CollectorStop(subscriber, callback);
if (ret != SUCCESS) {
LOGI("CollectorStart failed, ret=%{public}d", ret);
LOGI("CollectorStop failed, ret=%{public}d", ret);
return ret;
}
LOGI("CollectorStart result, ret=%{public}d", ret);
LOGI("CollectorStop result, ret=%{public}d", ret);
return SUCCESS;
}
}

View File

@ -37,6 +37,10 @@ sptr<IRemoteObject> CollectorServiceLoader::LoadCollectorService()
}
sptr<LoadCallback> callback = new (std::nothrow) LoadCallback();
if (callback == nullptr) {
LOGE("LoadCallback new error.");
return nullptr;
}
int32_t result = registry->LoadSystemAbility(SECURITY_COLLECTOR_MANAGER_SA_ID, callback);
if (result != ERR_OK) {
LOGE("LoadSystemAbility error.");

0
interfaces/inner_api/collector/src/i_collector.cpp Normal file → Executable file
View File

0
interfaces/inner_api/collector/src/i_collector_fwk.cpp Normal file → Executable file
View File

View File

View File

@ -14,7 +14,7 @@
*/
#include "security_collector_manager_callback_service.h"
#include <cinttypes>
#include "security_collector_define.h"
#include "security_collector_log.h"

View File

@ -30,7 +30,7 @@ int32_t SecurityCollectorManagerCallbackStub::OnRemoteRequest(uint32_t code, Mes
if (code == SecurityCollectorManagerCallbackStub::CMD_COLLECTOR_NOTIFY) {
uint32_t expected = sizeof(uint64_t);
uint32_t actual = data.GetReadableBytes();
if (expected >= actual) {
if (actual <= expected) {
LOGE("actual length error, value=%{public}u", actual);
return BAD_PARAM;
}

View File

@ -27,6 +27,7 @@ SecurityCollectorManagerProxy::SecurityCollectorManagerProxy(const sptr<IRemoteO
int32_t SecurityCollectorManagerProxy::Subscribe(const SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback)
{
LOGI("enter SecurityCollectorManagerProxy Subscribe");
MessageParcel data;
MessageParcel reply;
@ -43,7 +44,12 @@ int32_t SecurityCollectorManagerProxy::Subscribe(const SecurityCollectorSubscrib
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_COLLECTOR_SUBCRIBE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_COLLECTOR_SUBCRIBE, data, reply, option);
if (ret != ERR_NONE) {
LOGE("ret=%{public}d", ret);
return ret;
@ -55,6 +61,7 @@ int32_t SecurityCollectorManagerProxy::Subscribe(const SecurityCollectorSubscrib
int32_t SecurityCollectorManagerProxy::Unsubscribe(const sptr<IRemoteObject> &callback)
{
LOGI("enter SecurityCollectorManagerProxy Unsubscribe");
MessageParcel data;
MessageParcel reply;
@ -66,7 +73,12 @@ int32_t SecurityCollectorManagerProxy::Unsubscribe(const sptr<IRemoteObject> &ca
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_COLLECTOR_UNSUBCRIBE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_COLLECTOR_UNSUBCRIBE, data, reply, option);
if (ret != ERR_NONE) {
LOGE("ret=%{public}d", ret);
return ret;
@ -81,7 +93,7 @@ int32_t SecurityCollectorManagerProxy::CollectorStart(const SecurityCollectorSub
{
MessageParcel data;
MessageParcel reply;
LOGD("==========================in CollectorControl");
LOGI("enter SecurityCollectorManagerProxy CollectorStart");
if (!data.WriteInterfaceToken(GetDescriptor())) {
LOGE("WriteInterfaceToken error");
return WRITE_ERR;
@ -93,7 +105,12 @@ int32_t SecurityCollectorManagerProxy::CollectorStart(const SecurityCollectorSub
}
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_COLLECTOR_START, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_COLLECTOR_START, data, reply, option);
if (ret != ERR_NONE) {
LOGE("ret=%{public}d", ret);
return ret;
@ -108,7 +125,7 @@ int32_t SecurityCollectorManagerProxy::CollectorStop(const SecurityCollectorSubs
{
MessageParcel data;
MessageParcel reply;
LOGD("===========================in CollectorControl.");
LOGI("enter SecurityCollectorManagerProxy CollectorStop");
if (!data.WriteInterfaceToken(GetDescriptor())) {
LOGE("WriteInterfaceToken error");
return WRITE_ERR;
@ -120,7 +137,12 @@ int32_t SecurityCollectorManagerProxy::CollectorStop(const SecurityCollectorSubs
}
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_COLLECTOR_STOP, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_COLLECTOR_STOP, data, reply, option);
if (ret != ERR_NONE) {
LOGE("ret=%{public}d", ret);
return ret;
@ -133,6 +155,7 @@ int32_t SecurityCollectorManagerProxy::CollectorStop(const SecurityCollectorSubs
int32_t SecurityCollectorManagerProxy::QuerySecurityEvent(const std::vector<SecurityEventRuler> rulers,
std::vector<SecurityEvent> &events)
{
LOGI("enter SecurityCollectorManagerProxy QuerySecurityEvent");
MessageParcel data;
MessageParcel reply;
@ -154,7 +177,12 @@ int32_t SecurityCollectorManagerProxy::QuerySecurityEvent(const std::vector<Secu
}
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SECURITY_EVENT_QUERY, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SECURITY_EVENT_QUERY, data, reply, option);
if (ret != ERR_NONE) {
LOGE("ret=%{public}d", ret);
return ret;

View File

@ -27,6 +27,9 @@ bool SecurityEvent::Marshalling(Parcel& parcel) const
if (!parcel.WriteString(content_)) {
return false;
}
if (!parcel.WriteString(timestamp_)) {
return false;
}
return true;
};
@ -41,6 +44,9 @@ bool SecurityEvent::ReadFromParcel(Parcel &parcel)
if (!parcel.ReadString(content_)) {
return false;
}
if (!parcel.ReadString(timestamp_)) {
return false;
}
return true;
};

View File

@ -13,25 +13,25 @@
* limitations under the License.
*/
#ifndef SECURITY_CONFIG_UPDATE_INFO_H
#define SECURITY_CONFIG_UPDATE_INFO_H
#ifndef SECURITY_CONFIG_UPDATE_H
#define SECURITY_CONFIG_UPDATE_H
#include <string>
#include "parcel.h"
namespace OHOS::Security::SecurityGuard {
class SecurityConfigUpdateInfo : public Parcelable {
public:
SecurityConfigUpdateInfo() = default;
SecurityConfigUpdateInfo(int32_t fd, const std::string &name = "") : fd_(fd), fileName_(name) {};
~SecurityConfigUpdateInfo() override = default;
bool Marshalling(Parcel &parcle) const override
bool Marshalling(Parcel& parcel) const override
{
if (!parcle.WriteInt32(fd_)) {
if (!parcel.WriteInt32(fd_)) {
return false;
}
if (!parcle.WriteString(fileName_)) {
if (!parcel.WriteString(fileName_)) {
return false;
}
return true;
@ -46,9 +46,9 @@ public:
}
return true;
}
static SecurityConfigUpdateInfo* Unmarshalling(Parcel &parcel)
static SecurityConfigUpdateInfo* Unmarshalling(Parcel& parcel)
{
SecurityConfigUpdateInfo *info = new(std::nothrow) SecurityConfigUpdateInfo();
SecurityConfigUpdateInfo *info = new (std::nothrow) SecurityConfigUpdateInfo();
if (info != nullptr && !info->ReadFromParcel(parcel)) {
delete info;
info = nullptr;
@ -56,11 +56,11 @@ public:
return info;
}
int32_t GetFd() const { return fd_; };
std::string GetFileName() const { return fileName_; }
std::string GetFileName() const { return fileName_; };
private:
int32_t fd_ {};
std::string fileName_ {};
int32_t fd_{};
std::string fileName_{};
};
} // OHOS::Security::SecurityGuard
} // namespace OHOS::Security::SecurityGuard
#endif //SECURITY_CONFIG_UPDATE_INFO_H
#endif // SECURITY_CONFIG_UPDATE_H

View File

@ -0,0 +1,162 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_EVENT_CONFIG_H
#define SECURITY_EVENT_CONFIG_H
#include <string>
#include <vector>
#include "parcel.h"
#include "security_event_info.h"
namespace OHOS::Security::SecurityGuard {
class SecurityEventConfig : public Parcelable {
public:
SecurityEventConfig() = default;
SecurityEventConfig(const EventCfg &config) : config_(config){};
~SecurityEventConfig() override = default;
EventCfg GetEventConfig() const
{
return config_;
};
bool Marshalling(Parcel &parcel) const override
{
if (!parcel.WriteInt64(config_.eventId)) {
return false;
}
if (!parcel.WriteString(config_.eventName)) {
return false;
}
if (!parcel.WriteUint32(config_.version)) {
return false;
}
if (!parcel.WriteUint32(config_.eventType)) {
return false;
}
if (!parcel.WriteUint32(config_.collectOnStart)) {
return false;
}
if (!parcel.WriteUint32(config_.dataSensitivityLevel)) {
return false;
}
if (!parcel.WriteUint32(config_.storageRamNums)) {
return false;
}
if (!parcel.WriteInt32(config_.storageRomNums)) {
return false;
}
if (!parcel.WriteUint32(config_.storageTime)) {
return false;
}
uint32_t ownerSize = config_.owner.size();
if (!parcel.WriteUint32(ownerSize)) {
return false;
}
for (uint32_t index = 0; index < ownerSize; index++) {
if (!parcel.WriteString(config_.owner[index])) {
return false;
}
}
if (!parcel.WriteUint32(config_.source)) {
return false;
}
if (!parcel.WriteString(config_.dbTable)) {
return false;
}
if (!parcel.WriteString(config_.prog)) {
return false;
}
return true;
};
bool ReadFromParcel(Parcel &parcel)
{
if (!parcel.ReadInt64(config_.eventId)) {
return false;
}
if (!parcel.ReadString(config_.eventName)) {
return false;
}
if (!parcel.ReadUint32(config_.version)) {
return false;
}
if (!parcel.ReadUint32(config_.eventType)) {
return false;
}
if (!parcel.ReadUint32(config_.collectOnStart)) {
return false;
}
if (!parcel.ReadUint32(config_.dataSensitivityLevel)) {
return false;
}
if (!parcel.ReadUint32(config_.storageRamNums)) {
return false;
}
if (!parcel.ReadUint32(config_.storageRomNums)) {
return false;
}
if (!parcel.ReadInt32(config_.storageTime)) {
return false;
}
uint32_t ownerSize = 0;
if (!parcel.ReadUint32(ownerSize)) {
return false;
}
for (uint32_t index = 0; index < ownerSize; index++) {
if (!parcel.ReadString(config_.owner[index])) {
return false;
}
}
if (!parcel.ReadUint32(config_.source)) {
return false;
}
if (!parcel.ReadString(config_.dbTable)) {
return false;
}
if (!parcel.ReadString(config_.prog)) {
return false;
}
return true;
};
static SecurityEventConfig *Unmarshalling(Parcel &parcel)
{
SecurityEventConfig *config = new (std::nothrow) SecurityEventConfig();
if (config != nullptr && !config->ReadFromParcel(parcel)) {
delete config;
config = nullptr;
}
return config;
};
private:
EventCfg config_{};
};
} // namespace OHOS::Security::SecurityGuard
#endif // SECURITY_EVENT_CONFIG_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,26 +13,29 @@
* limitations under the License.
*/
#ifndef SECURITY_GUARD_GLOBAL_APP_CONFIG_H
#define SECURITY_GUARD_GLOBAL_APP_CONFIG_H
#include <vector>
#include "nlohmann/json.hpp"
#ifndef SECURITY_EVENT_CONFIG_INFO_H
#define SECURITY_EVENT_CONFIG_INFO_H
#include "base_config.h"
#include "config_define.h"
#include <string>
#include <vector>
namespace OHOS::Security::SecurityGuard {
class GlobalAppConfig : public BaseConfig {
public:
GlobalAppConfig() = default;
~GlobalAppConfig() override = default;
bool Load(int mode) override;
bool Parse() override;
bool Update() override;
private:
bool ParseAppListConfig(std::vector<AppInfo>&, const nlohmann::json&);
using EventCfg = struct {
int64_t eventId;
std::string eventName;
uint32_t version;
uint32_t eventType;
uint32_t collectOnStart;
uint32_t dataSensitivityLevel;
uint32_t storageRamNums;
uint32_t storageRomNums;
int32_t storageTime;
std::vector<std::string> owner;
uint32_t source;
std::string dbTable;
std::string prog;
};
} // OHOS::Security::SecurityGuard
#endif // SECURITY_GUARD_MODEL_CONFIG_H
} // namespace OHOS::Security::SecurityGuard
#endif // SECURITY_EVENT_CONFIG_INFO_H

View File

@ -27,6 +27,8 @@ ohos_source_set("sg_collect_stamp") {
"${sg_root_dir}/interfaces/inner_api/obtaindata/include",
"${sg_root_dir}/interfaces/inner_api/collect/include",
"${sg_root_dir}/frameworks/common/log/include",
"${sg_root_dir}/interfaces/inner_api/common/include",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/include",
]
sources = [
@ -43,7 +45,7 @@ ohos_source_set("sg_collect_stamp") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",
@ -52,3 +54,65 @@ ohos_source_set("sg_collect_stamp") {
"samgr:samgr_proxy",
]
}
config("security_guard_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${sg_root_dir}/frameworks/common/interfaces",
"${sg_root_dir}/interfaces/inner_api/common/include",
"${sg_root_dir}/interfaces/inner_api/collector/include",
"${sg_root_dir}/interfaces/inner_api/obtaindata/include",
]
}
ohos_shared_library("libsg_data_collect_manager_sdk") {
innerapi_tags = [ "platformsdk" ]
subsystem_name = "security"
part_name = "security_guard"
output_name = "libsg_data_collect_manager_sdk"
configs = [ "${sg_root_dir}/resource/config/build:coverage_flags" ]
public_configs = [ ":security_guard_config" ]
include_dirs = [
"include",
"${sg_root_dir}/frameworks/common/interfaces",
"${sg_root_dir}/frameworks/common/constants/include",
"${sg_root_dir}/interfaces/inner_api/collect/include",
"${sg_root_dir}/interfaces/inner_api/collector/include",
"${sg_root_dir}/interfaces/inner_api/common/include",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/include",
"${sg_root_dir}/frameworks/common/log/include",
"${sg_root_dir}/frameworks/common/utils/include",
]
sources = [
"${sg_root_dir}/frameworks/common/utils/src/security_guard_utils.cpp",
"${sg_root_dir}/interfaces/inner_api/collector/src/security_event.cpp",
"${sg_root_dir}/interfaces/inner_api/collector/src/security_event_ruler.cpp",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/src/data_collect_manager.cpp",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/src/data_collect_manager_callback_service.cpp",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/src/data_collect_manager_callback_stub.cpp",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/src/data_collect_manager_proxy.cpp",
"${sg_root_dir}/interfaces/inner_api/obtaindata/src/security_event_query_callback_service.cpp",
"${sg_root_dir}/interfaces/inner_api/obtaindata/src/security_event_query_callback_stub.cpp",
]
sanitize = {
integer_overflow = true
ubsan = true
boundary_sanitize = true
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
}

View File

@ -19,15 +19,15 @@
#include <map>
#include <mutex>
#include "singleton.h"
#include "i_collector_subscriber.h"
#include "security_event_query_callback.h"
#include "data_collect_manager_callback_service.h"
#include "security_event_query_callback.h"
#include "security_event_ruler.h"
namespace OHOS::Security::SecurityGuard {
class DataCollectManager : public Singleton<DataCollectManager> {
public:
int32_t QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
std::shared_ptr<SecurityEventQueryCallback> callback);
int32_t QuerySecurityEventConfig(std::string &result);
};
} // namespace OHOS::Security::SecurityGuard
#endif // SECURITY_GUARD_DATA_COLLECT_MANAGER_H

View File

@ -41,6 +41,7 @@ public:
int32_t CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback) override;
int32_t ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &updateInfo) override;
int32_t QuerySecurityEventConfig(std::string &result) override;
private:
static inline BrokerDelegator<DataCollectManagerProxy> delegator_;
};

View File

@ -15,6 +15,7 @@
#include "iservice_registry.h"
#include "data_collect_manager.h"
#include "security_event_ruler.h"
#include "data_collect_manager_callback_service.h"
#include "security_event_query_callback_service.h"
#include "security_guard_define.h"
#include "security_guard_log.h"
@ -49,4 +50,25 @@ int32_t DataCollectManager::QuerySecurityEvent(std::vector<SecurityCollector::Se
}
return 0;
}
int32_t DataCollectManager::QuerySecurityEventConfig(std::string &result)
{
SGLOGI("Start DataCollectManager QuerySecurityEventConfig");
auto registry = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (registry == nullptr) {
SGLOGE("GetSystemAbilityManager error");
return FAILED;
}
auto object = registry->GetSystemAbility(DATA_COLLECT_MANAGER_SA_ID);
if (object == nullptr) {
SGLOGE("object is nullptr");
return FAILED;
}
auto proxy = iface_cast<IDataCollectManager>(object);
if (proxy == nullptr) {
SGLOGE("proxy is null");
return FAILED;
}
return proxy->QuerySecurityEventConfig(result);
}
}

View File

@ -30,11 +30,11 @@ int32_t DataCollectManagerCallbackStub::OnRemoteRequest(uint32_t code, MessagePa
if (code == DataCollectManagerCallbackStub::CMD_SET_REQUEST_DATA) {
uint32_t expected = sizeof(uint32_t);
uint32_t actual = data.GetReadableBytes();
if (expected >= actual) {
if (actual <= expected) {
SGLOGE("actual length error, value=%{public}u", actual);
return BAD_PARAM;
}
std::string devId = data.ReadString();
std::string devId = {};
std::string riskData = data.ReadString();
uint32_t status = data.ReadUint32();
SGLOGI("status=%{public}u", status);

View File

@ -14,7 +14,7 @@
*/
#include "data_collect_manager_proxy.h"
#include <cinttypes>
#include "security_guard_define.h"
#include "security_guard_log.h"
@ -27,6 +27,7 @@ DataCollectManagerProxy::DataCollectManagerProxy(const sptr<IRemoteObject> &impl
int32_t DataCollectManagerProxy::RequestDataSubmit(int64_t eventId, std::string &version,
std::string &time, std::string &content)
{
SGLOGD("enter DataCollectManagerProxy RequestDataSubmit");
SGLOGD("eventId=%{public}" PRId64 ", version=%{public}s", eventId, version.c_str());
MessageParcel data;
MessageParcel reply;
@ -58,6 +59,7 @@ int32_t DataCollectManagerProxy::RequestDataSubmit(int64_t eventId, std::string
int32_t DataCollectManagerProxy::RequestRiskData(std::string &devId, std::string &eventList,
const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy RequestRiskData");
MessageParcel data;
MessageParcel reply;
@ -65,7 +67,6 @@ int32_t DataCollectManagerProxy::RequestRiskData(std::string &devId, std::string
SGLOGE("WriteInterfaceToken error");
return WRITE_ERR;
}
data.WriteString(devId);
data.WriteString(eventList);
data.WriteRemoteObject(callback);
@ -88,6 +89,7 @@ int32_t DataCollectManagerProxy::RequestRiskData(std::string &devId, std::string
int32_t DataCollectManagerProxy::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy Subscribe");
MessageParcel data;
MessageParcel reply;
@ -104,7 +106,12 @@ int32_t DataCollectManagerProxy::Subscribe(const SecurityCollector::SecurityColl
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_DATA_SUBSCRIBE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_DATA_SUBSCRIBE, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -116,6 +123,7 @@ int32_t DataCollectManagerProxy::Subscribe(const SecurityCollector::SecurityColl
int32_t DataCollectManagerProxy::Unsubscribe(const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy Unsubscribe");
MessageParcel data;
MessageParcel reply;
@ -127,7 +135,12 @@ int32_t DataCollectManagerProxy::Unsubscribe(const sptr<IRemoteObject> &callback
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_DATA_UNSUBSCRIBE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_DATA_UNSUBSCRIBE, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -140,6 +153,7 @@ int32_t DataCollectManagerProxy::Unsubscribe(const sptr<IRemoteObject> &callback
int32_t DataCollectManagerProxy::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy QuerySecurityEvent");
MessageParcel data;
MessageParcel reply;
@ -163,7 +177,12 @@ int32_t DataCollectManagerProxy::QuerySecurityEvent(std::vector<SecurityCollecto
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SECURITY_EVENT_QUERY, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SECURITY_EVENT_QUERY, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -176,6 +195,7 @@ int32_t DataCollectManagerProxy::QuerySecurityEvent(std::vector<SecurityCollecto
int32_t DataCollectManagerProxy::CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy CollectorStart");
MessageParcel data;
MessageParcel reply;
@ -192,7 +212,12 @@ int32_t DataCollectManagerProxy::CollectorStart(const SecurityCollector::Securit
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SECURITY_COLLECTOR_START, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SECURITY_COLLECTOR_START, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -205,6 +230,7 @@ int32_t DataCollectManagerProxy::CollectorStart(const SecurityCollector::Securit
int32_t DataCollectManagerProxy::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
const sptr<IRemoteObject> &callback)
{
SGLOGI("enter DataCollectManagerProxy CollectorStop");
MessageParcel data;
MessageParcel reply;
@ -221,7 +247,12 @@ int32_t DataCollectManagerProxy::CollectorStop(const SecurityCollector::Security
data.WriteRemoteObject(callback);
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SECURITY_COLLECTOR_STOP, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SECURITY_COLLECTOR_STOP, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -233,6 +264,7 @@ int32_t DataCollectManagerProxy::CollectorStop(const SecurityCollector::Security
int32_t DataCollectManagerProxy::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &updateInfo)
{
SGLOGI("enter DataCollectManagerProxy ConfigUpdate");
MessageParcel data;
MessageParcel reply;
@ -242,17 +274,20 @@ int32_t DataCollectManagerProxy::ConfigUpdate(const SecurityGuard::SecurityConfi
}
if (!data.WriteString(updateInfo.GetFileName())) {
SGLOGE("failed to write file for config update");
SGLOGE("failed to write string for config update");
return WRITE_ERR;
}
if (!data.WriteFileDescriptor(updateInfo.GetFd())) {
SGLOGE("failed to write file descriptor for config update");
return WRITE_ERR;
}
MessageOption option = { MessageOption::TF_SYNC };
int ret = Remote()->SendRequest(CMD_SECURITY_CONFIG_UPDATE, data, reply, option);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
int ret = remote->SendRequest(CMD_SECURITY_CONFIG_UPDATE, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
@ -261,4 +296,35 @@ int32_t DataCollectManagerProxy::ConfigUpdate(const SecurityGuard::SecurityConfi
SGLOGD("reply=%{public}d", ret);
return ret;
}
int32_t DataCollectManagerProxy::QuerySecurityEventConfig(std::string &result)
{
SGLOGI("Start DataCollectManagerProxy QuerySecurityEventConfig");
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(GetDescriptor())) {
SGLOGE("WriteInterfaceToken error");
return WRITE_ERR;
}
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
SGLOGE("Remote error");
return NULL_OBJECT;
}
MessageOption option = { MessageOption::TF_SYNC };
int ret = remote->SendRequest(CMD_SECURITY_EVENT_CONFIG_QUERY, data, reply, option);
if (ret != ERR_NONE) {
SGLOGE("ret=%{public}d", ret);
return ret;
}
if (!reply.ReadString(result)) {
SGLOGE("Failed to get the system integrity result");
return BAD_PARAM;
}
return SUCCESS;
}
}

View File

@ -69,7 +69,7 @@ ohos_shared_library("libsg_obtaindata_sdk") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",

View File

@ -37,7 +37,8 @@ public:
private:
void HandleDecipient();
std::mutex mutex_{};
sptr<AcquireDataManagerCallbackService> callback_{};
std::map<std::shared_ptr<SecurityCollector::ICollectorSubscriber>,
sptr<AcquireDataManagerCallbackService>> eventListeners_;
sptr<IRemoteObject::DeathRecipient> deathRecipient_{};
};
} // namespace OHOS::Security::SecurityGuard

View File

@ -75,7 +75,6 @@ static int32_t RequestSecurityEventInfoAsyncImpl(const DeviceIdentify *devId, co
std::string eventList(eventJson);
auto func = [callback] (std::string &devId, std::string &riskData, uint32_t status,
const std::string &errMsg)-> int32_t {
SGLOGI("riskData=%{public}s, status=%{public}u, errMsg=%{public}s", riskData.c_str(), status, errMsg.c_str());
if (devId.length() >= DEVICE_ID_MAX_LEN) {
return BAD_PARAM;
}

View File

@ -31,12 +31,13 @@ ohos_unittest("libsg_obtaindata_sdk_test") {
"unittest/src/obtaindata_kit_test.cpp",
]
deps =
[ "${sg_root_dir}/interfaces/inner_api/obtaindata:libsg_obtaindata_sdk" ]
deps = [
"${sg_root_dir}/interfaces/inner_api/obtaindata:libsg_obtaindata_sdk",
"//third_party/googletest:gmock",
]
external_deps = [
"c_utils:utils",
"googletest:gmock",
"hilog:libhilog",
]
}

View File

@ -1,91 +1,91 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "acquire_data_manager_test.h"
#include "file_ex.h"
#include "security_guard_define.h"
#include "acquire_data_manager.h"
using namespace testing::ext;
using namespace OHOS::Security::SecurityGuardTest;
namespace OHOS::Security::SecurityGuardTest {
void AcquireDataManagerTest::SetUpTestCase()
{
string isEnforcing;
LoadStringFromFile("/sys/fs/selinux/enforce", isEnforcing);
if (isEnforcing.compare("1") == 0) {
AcquireDataManagerTest::isEnforcing_ = true;
SaveStringToFile("/sys/fs/selinux/enforce", "0");
}
}
void AcquireDataManagerTest::TearDownTestCase()
{
if (AcquireDataManagerTest::isEnforcing_) {
SaveStringToFile("/sys/fs/selinux/enforce", "1");
}
}
void AcquireDataManagerTest::SetUp()
{
}
void AcquireDataManagerTest::TearDown()
{
}
bool AcquireDataManagerTest::isEnforcing_ = false;
/**
* @tc.name: Subscribe001
* @tc.desc: AcquireDataManager Subscribe
* @tc.type: FUNC
* @tc.require: AR000IENKB
*/
HWTEST_F(AcquireDataManagerTest, Subscribe001, TestSize.Level1)
{
int ret = SecurityGuard::AcquireDataManager::GetInstance().Subscribe(nullptr);
EXPECT_EQ(ret, SecurityGuard::NULL_OBJECT);
}
/**
* @tc.name: Unsubscribe001
* @tc.desc: AcquireDataManager Unsubscribe
* @tc.type: FUNC
* @tc.require: AR000IENKB
*/
HWTEST_F(AcquireDataManagerTest, Unsubscribe001, TestSize.Level1)
{
int ret = SecurityGuard::AcquireDataManager::GetInstance().Unsubscribe(nullptr);
EXPECT_EQ(ret, SecurityGuard::BAD_PARAM);
}
/**
* @tc.name: ReportSecurityInfo007
* @tc.desc: AcquireDataManager DeathRecipient OnRemoteDied
* @tc.type: FUNC
* @tc.require: SR000H96L5
*/
HWTEST_F(AcquireDataManagerTest, DeathRecipient001, TestSize.Level1)
{
SecurityGuard::AcquireDataManager::DeathRecipient recipient =
SecurityGuard::AcquireDataManager::DeathRecipient();
recipient.OnRemoteDied(nullptr);
}
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "acquire_data_manager_test.h"
#include "file_ex.h"
#include "security_guard_define.h"
#include "acquire_data_manager.h"
using namespace testing::ext;
using namespace OHOS::Security::SecurityGuardTest;
namespace OHOS::Security::SecurityGuardTest {
void AcquireDataManagerTest::SetUpTestCase()
{
string isEnforcing;
LoadStringFromFile("/sys/fs/selinux/enforce", isEnforcing);
if (isEnforcing.compare("1") == 0) {
AcquireDataManagerTest::isEnforcing_ = true;
SaveStringToFile("/sys/fs/selinux/enforce", "0");
}
}
void AcquireDataManagerTest::TearDownTestCase()
{
if (AcquireDataManagerTest::isEnforcing_) {
SaveStringToFile("/sys/fs/selinux/enforce", "1");
}
}
void AcquireDataManagerTest::SetUp()
{
}
void AcquireDataManagerTest::TearDown()
{
}
bool AcquireDataManagerTest::isEnforcing_ = false;
/**
* @tc.name: Subscribe001
* @tc.desc: AcquireDataManager Subscribe
* @tc.type: FUNC
* @tc.require: AR000IENKB
*/
HWTEST_F(AcquireDataManagerTest, Subscribe001, TestSize.Level1)
{
int ret = SecurityGuard::AcquireDataManager::GetInstance().Subscribe(nullptr);
EXPECT_EQ(ret, SecurityGuard::NULL_OBJECT);
}
/**
* @tc.name: Unsubscribe001
* @tc.desc: AcquireDataManager Unsubscribe
* @tc.type: FUNC
* @tc.require: AR000IENKB
*/
HWTEST_F(AcquireDataManagerTest, Unsubscribe001, TestSize.Level1)
{
int ret = SecurityGuard::AcquireDataManager::GetInstance().Unsubscribe(nullptr);
EXPECT_EQ(ret, SecurityGuard::BAD_PARAM);
}
/**
* @tc.name: ReportSecurityInfo007
* @tc.desc: AcquireDataManager DeathRecipient OnRemoteDied
* @tc.type: FUNC
* @tc.require: SR000H96L5
*/
HWTEST_F(AcquireDataManagerTest, DeathRecipient001, TestSize.Level1)
{
SecurityGuard::AcquireDataManager::DeathRecipient recipient =
SecurityGuard::AcquireDataManager::DeathRecipient();
recipient.OnRemoteDied(nullptr);
}
}

View File

@ -1,40 +1,40 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H
#define SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H
#include <gtest/gtest.h>
#include "security_guard_api.h"
#include "security_guard_define.h"
namespace OHOS::Security::SecurityGuardTest {
class AcquireDataManagerTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
private:
static bool isEnforcing_;
};
} // namespace OHOS::Security::SecurityGuardTest
#endif // SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H
#define SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H
#include <gtest/gtest.h>
#include "security_guard_api.h"
#include "security_guard_define.h"
namespace OHOS::Security::SecurityGuardTest {
class AcquireDataManagerTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
private:
static bool isEnforcing_;
};
} // namespace OHOS::Security::SecurityGuardTest
#endif // SECURITY_GUARD_ACQUIRE_DATA_MANAGER_TEST_H

View File

@ -30,7 +30,7 @@ ohos_prebuilt_etc("security_guard_model_cfg") {
}
ohos_prebuilt_etc("security_guard_event_cfg") {
source = "hos/security_guard_event.cfg"
source = "hos/security_guard_event.json"
module_install_dir = ""
subsystem_name = "security"
@ -46,7 +46,15 @@ ohos_prebuilt_etc("security_audit_cfg") {
}
ohos_prebuilt_etc("real_time_upload_event_cfg") {
source = "hos/real_time_upload_event.cfg"
source = "hos/real_time_upload_event.json"
module_install_dir = ""
subsystem_name = "security"
part_name = "security_guard"
}
ohos_prebuilt_etc("config_update_trust_list_cfg") {
source = "hos/config_update_trust_list.json"
module_install_dir = ""
subsystem_name = "security"

View File

@ -0,0 +1,26 @@
{
"trust_list_config": [{
"name": "security_guard_event.json"
},
{
"name": "security_guard_model.cfg"
},
{
"name": "signature_rule.json"
},
{
"name": "url_rule.json"
},
{
"name": "local_app_attribute.json"
},
{
"name": "global_app_attribute.json"
},
{
"name": "related_event_analysis.json"
},
{
"name": "real_time_upload_event.json"
}]
}

View File

@ -1,28 +0,0 @@
{
"uploadEvents": [
{
"eventId": "1011009110",
"securityLevel": "fatal"
},
{
"eventId": "1011009113",
"securityLevel": "fatal"
},
{
"eventId": "0x01C000000",
"securityLevel": "fatal"
},
{
"eventId": "0x01C000001",
"securityLevel": "fatal"
},
{
"eventId": "0x01C000002",
"securityLevel": "key"
},
{
"eventId": "0x01C000005",
"securityLevel": "fatal"
}
]
}

View File

@ -0,0 +1,70 @@
{
"uploadEvents": [
{
"eventId": "1011009110",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "1011009113",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x01C000000",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x01C000001",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x01C000002",
"securityLevel": "key",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x01C000005",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x012001080",
"securityLevel": "key",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x012001086",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x01C000006",
"securityLevel": "fatal",
"maxUploadNums": 1,
"resetMaxUploadNums": false
},
{
"eventId": "0x027000002",
"securityLevel": "key",
"maxUploadNums": 3,
"resetMaxUploadNums": true
},
{
"eventId": "0x027000003",
"securityLevel": "key",
"maxUploadNums": 3,
"resetMaxUploadNums": true
}
]
}

View File

@ -74,7 +74,7 @@
},
{
"moduleId":"9",
"eventId":["1037000001","0x8B001003"],
"eventId":["0x02B001003","0x02B001004","0x02B001005","0x02B001006"],
"moduleName":"libdns_event.z.so",
"modulePath":"/system/lib64/",
"collectorType":1,
@ -82,7 +82,7 @@
},
{
"moduleId":"10",
"eventId":["1064001001"],
"eventId":["1064001001", "0x01200100B", "0x01200100C", "0x01200100D", "0x01200100F", "0x012001015"],
"moduleName":"libkernel_collector_sg.z.so",
"modulePath":"/system/lib64/",
"collectorType":0,
@ -90,7 +90,7 @@
},
{
"moduleId":"11",
"eventId":["1064001002"],
"eventId":["0x012001000", "0x012001001", "0x012001002", "0x012001003", "0x012001004", "0x012001005", "0x012001006", "0x012001007", "0x012001008", "0x012001009", "0x01200100A", "0x012001020", "0x012001021"],
"moduleName":"libdtd_native_collector.z.so",
"modulePath":"/system/lib64/",
"collectorType":0,

View File

@ -1,30 +0,0 @@
{
"eventcfg": [
{
"eventId":"1011015001",
"eventName":"account",
"version":0,
"eventType":0,
"dataSensitivityLevel":1,
"storageRamNums":1,
"storageRomNums":100000,
"storageTime" : -1,
"owner":["3001000003"],
"source" : 0,
"db_table": "audit_event"
},
{
"eventId":"1011015014",
"eventName":"cert",
"version":0,
"eventType":0,
"dataSensitivityLevel":1,
"storageRamNums":1,
"storageRomNums":100000,
"storageTime" : -1,
"owner":["3001000003"],
"source" : 0,
"db_table": "audit_event"
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -313,5 +313,17 @@
"db_table": "risk_event",
"running_cntl": 0,
"caller": ["security_guard"]
},
{
"modelId": "3001000009",
"path": "/system/lib64/libsg_risk_factor_model.z.so",
"format": "so",
"start-mode": 2,
"preload": [""],
"eventList": [""],
"permissions": "ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT",
"db_table": "risk_event",
"running_cntl": 0,
"caller": ["security_guard"]
}]
}

View File

@ -1,24 +0,0 @@
{
"patches": [
{
"project":"productdefine_common",
"path":"productdefine/common",
"pr_url":"https://gitee.com/openharmony/productdefine_common/pulls/835"
},
{
"project":"vendor_hihope",
"path":"vendor/hihope",
"pr_url":"https://gitee.com/openharmony/vendor_hihope/pulls/1091"
},
{
"project":"device_board_hihope",
"path":"device/board/hihope",
"pr_url":"https://gitee.com/openharmony/device_board_hihope/pulls/320"
},
{
"project":"security_selinux_adapter",
"path":"base/security/selinux_adapter",
"pr_url":"https://gitee.com/openharmony/security_selinux_adapter/pulls/3763"
}
]
}

0
resource/config/build/BUILD.gn Normal file → Executable file
View File

12
sa_profile/3526.json Normal file
View File

@ -0,0 +1,12 @@
{
"process": "security_guard",
"systemability": [
{
"name": 3526,
"libpath": "libreal_time_detect_service.z.so",
"run-on-create": true,
"distributed": false,
"dump_level": 1
}
]
}

View File

@ -18,6 +18,7 @@ ohos_sa_profile("sg_sa_profile_standard") {
sources = [
"3523.json",
"3524.json",
"3526.json",
]
part_name = "security_guard"
}

View File

@ -1,37 +1,41 @@
{
"services": [
{
"name" : "security_collector",
"path" : [
"/system/bin/sa_main",
"/system/profile/security_collector.json"
],
"ondemand": true,
"dynamic": true,
"uid" : "security_collector",
"gid" : [
"security_collector",
"shell",
"oeminfo_nvme_server"
],
"apl" : "system_basic",
"secon" : "u:r:security_collector:s0",
"caps" : [
"CAP_SYS_PTRACE",
"CAP_NET_ADMIN",
"CAP_SYS_ADMIN",
"CAP_DAC_READ_SEARCH"
],
"permission" : [
"ohos.permission.securityguard.REPORT_SECURITY_INFO",
"ohos.permission.READ_DFX_SYSEVENT",
"ohos.permission.STORAGE_MANAGER",
"ohos.permission.RUNNING_STATE_OBSERVER",
"ohos.permission.VERIFY_ACTIVATION_LOCK",
"ohos.permission.ATTEST_KEY",
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS",
"ohos.permission.REPORT_SECURITY_EVENT"
],
"writepid" : ["/dev/cpuset/system-background/tasks"]
}]
}
{
"name": "security_collector",
"path": [
"/system/bin/sa_main",
"/system/profile/security_collector.json"
],
"ondemand": true,
"dynamic": true,
"uid": "security_collector",
"gid": [
"security_collector",
"shell",
"oeminfo_nvme_server"
],
"apl": "system_basic",
"secon": "u:r:security_collector:s0",
"caps": [
"CAP_SYS_PTRACE",
"CAP_NET_ADMIN",
"CAP_SYS_ADMIN",
"CAP_DAC_READ_SEARCH"
],
"permission": [
"ohos.permission.securityguard.REPORT_SECURITY_INFO",
"ohos.permission.STORAGE_MANAGER",
"ohos.permission.INPUT_MONITORING",
"ohos.permission.RUNNING_STATE_OBSERVER",
"ohos.permission.VERIFY_ACTIVATION_LOCK",
"ohos.permission.ATTEST_KEY",
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS",
"ohos.permission.REPORT_SECURITY_EVENT",
"ohos.permission.MANAGE_SECURE_SETTINGS"
],
"writepid": [
"/dev/cpuset/system-background/tasks"
]
}
]
}

View File

@ -1,43 +1,53 @@
{
"jobs" : [{
"name" : "services:security_guard",
"cmds" : [
"jobs": [
{
"name": "services:security_guard",
"cmds": [
"mkdir /data/service/el1/public/database 0711 ddms ddms",
"mkdir /data/service/el1/public/database/security_guard_service 02770 security_guard ddms",
"mkdir /data/service/el1/public/security_guard 0700 security_guard security_guard",
"mkdir /data/service/el1/public/security_guard/tmp 0700 security_guard security_guard",
"chown security_guard security_guard /dev/hkids"
]
}
}
],
"services" : [{
"name" : "security_guard",
"path" : ["/system/bin/sa_main", "/system/profile/security_guard.json"],
"uid" : "security_guard",
"gid" : ["security_guard", "shell"],
"apl" : "system_basic",
"secon" : "u:r:security_guard:s0",
"permission" : [
"ohos.permission.securityguard.REPORT_SECURITY_INFO",
"ohos.permission.READ_DFX_SYSEVENT",
"ohos.permission.ACCESS_SERVICE_DM",
"ohos.permission.hsdr.HSDR_ACCESS",
"ohos.permission.hsdr.REQUEST_HSDR",
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS",
"ohos.permission.GET_NETWORK_INFO",
"ohos.permission.ATTEST_KEY",
"ohos.permission.QUERY_SECURITY_EVENT",
"ohos.permission.REPORT_SECURITY_EVENT",
"ohos.permission.QUERY_SECURITY_MODEL_RESULT",
"ohos.permission.QUERY_SECURITY_POLICY_FROM_CLOUD",
"ohos.permission.REPORT_SECURITY_EVENT_TO_CLOUD",
"ohos.permission.COLLECT_SECURITY_EVENT"
],
"services": [
{
"name": "security_guard",
"path": [
"/system/bin/sa_main",
"/system/profile/security_guard.json"
],
"uid": "security_guard",
"gid": [
"security_guard",
"shell"
],
"apl": "system_basic",
"secon": "u:r:security_guard:s0",
"permission": [
"ohos.permission.securityguard.REPORT_SECURITY_INFO",
"ohos.permission.READ_DFX_SYSEVENT",
"ohos.permission.ACCESS_SERVICE_DM",
"ohos.permission.hsdr.HSDR_ACCESS",
"ohos.permission.hsdr.REQUEST_HSDR",
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS",
"ohos.permission.GET_NETWORK_INFO",
"ohos.permission.ATTEST_KEY",
"ohos.permission.QUERY_SECURITY_EVENT",
"ohos.permission.REPORT_SECURITY_EVENT",
"ohos.permission.QUERY_SECURITY_MODEL_RESULT",
"ohos.permission.QUERY_SECURITY_POLICY_FROM_CLOUD",
"ohos.permission.REPORT_SECURITY_EVENT_TO_CLOUD",
"ohos.permission.COLLECT_SECURITY_EVENT",
"ohos.permission.MANAGE_SECURITY_GUARD_CONFIG",
"ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT"
],
"permission_acls": [
"ohos.permission.COLLECT_SECURITY_EVENT"
],
"jobs" : {
"on-start" : "services:security_guard"
"jobs": {
"on-start": "services:security_guard"
}
}
]

View File

@ -13,4 +13,6 @@
sg_root_dir = "//base/security/security_guard"
fuzz_test_output_path = "security_guard/security_guard"
security_guard_enable = "true"
declare_args() {
security_guard_enable = true
}

View File

@ -33,7 +33,7 @@ ohos_source_set("sg_bigdata_stamp") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
external_deps = [
"c_utils:utils",

View File

@ -30,21 +30,19 @@ ohos_shared_library("sg_config_manager") {
"${sg_root_dir}/frameworks/common/utils/include",
"${sg_root_dir}/services/bigdata/include",
"${sg_root_dir}/services/data_collect/store/include",
"${sg_root_dir}/interfaces/inner_api/common/include",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/include",
]
sources = [
"${sg_root_dir}/frameworks/common/json/src/json_cfg.cpp",
"${sg_root_dir}/frameworks/common/utils/src/security_guard_utils.cpp",
"${sg_root_dir}/services/config_manager/src/app_info_rdb_helper.cpp",
"${sg_root_dir}/services/config_manager/src/base_config.cpp",
"${sg_root_dir}/services/config_manager/src/config_data_manager.cpp",
"${sg_root_dir}/services/config_manager/src/config_database_helper.cpp",
"${sg_root_dir}/services/config_manager/src/config_manager.cpp",
"${sg_root_dir}/services/config_manager/src/config_operator.cpp",
"${sg_root_dir}/services/config_manager/src/config_subscriber.cpp",
"${sg_root_dir}/services/config_manager/src/event_config.cpp",
"${sg_root_dir}/services/config_manager/src/global_app_config.cpp",
"${sg_root_dir}/services/config_manager/src/local_app_config.cpp",
"${sg_root_dir}/services/config_manager/src/model_cfg_marshalling.cpp",
"${sg_root_dir}/services/config_manager/src/model_config.cpp",
]
@ -57,19 +55,13 @@ ohos_shared_library("sg_config_manager") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
deps = [
"${sg_root_dir}/services/bigdata:sg_bigdata_stamp",
"${sg_root_dir}/services/data_collect:sg_collect_service_database",
]
deps = [ "${sg_root_dir}/services/bigdata:sg_bigdata_stamp" ]
external_deps = [
"ability_base:want",
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_core",
"json:nlohmann_json_static",
"relational_store:native_rdb",
]
}

View File

@ -1,37 +0,0 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_APP_INFO_RDB_HELPER_H
#define SECURITY_GUARD_APP_INFO_RDB_HELPER_H
#include "rdb_predicates.h"
#include "values_bucket.h"
#include "config_database_helper.h"
#include "store_define.h"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {
class AppInfoRdbHelper : public ConfigDatabaseHelper {
public:
static ConfigDatabaseHelper &GetInstance();
int Init() override;
private:
AppInfoRdbHelper();
~AppInfoRdbHelper() = default;
};
} // namespace OHOS::Security::SecurityGuard
#endif // SECURITY_GUARD_RISK_EVENT_RDB_HELPER_H

View File

@ -19,7 +19,7 @@
#include <mutex>
#include <set>
#include <unordered_map>
#include "security_event_info.h"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {
@ -37,10 +37,10 @@ public:
std::vector<int64_t> GetEventIds(uint32_t modelId);
std::vector<int64_t> GetAllEventIds();
std::vector<uint32_t> GetAllModelIds();
std::vector<EventCfg> GetAllEventConfigs();
bool GetModelConfig(uint32_t modelId, ModelCfg &config);
bool GetEventConfig(int64_t eventId, EventCfg &config);
std::string GetTableFromEventId(int64_t eventId);
std::vector<AppInfo> GetAppInfosByName(const std::string &appName);
private:
std::unordered_map<uint32_t, std::set<int64_t>> modelToEventMap_;
std::unordered_map<uint32_t, ModelCfg> modelMap_;

View File

@ -1,44 +0,0 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_CONFIG_DATABASE_HELPER_H
#define SECURITY_GUARD_CONFIG_DATABASE_HELPER_H
#include "database.h"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {
class ConfigDatabaseHelper : public Database {
public:
explicit ConfigDatabaseHelper(std::string dbTable);
~ConfigDatabaseHelper() = default;
virtual int Init();
virtual int InsertAppInfo(const AppInfo& info);
virtual int QueryAllAppInfo(std::vector<AppInfo> &infos);
virtual int QueryAppInfosByName(const std::string &appName, std::vector<AppInfo> &infos);
virtual int DeleteAppInfoByNameAndGlobbalFlag(const std::string &appName, int isGlobalApp);
virtual int QueryAppInfoByAttribute(const std::string attr, std::vector<AppInfo> &infos);
virtual int DeleteAppInfoByIsGlobalApp(int isGlobalApp);
virtual int InsertAllAppInfo(const std::vector<AppInfo> &infos);
protected:
int32_t QueryAppInfoBase(const NativeRdb::RdbPredicates &predicates, std::vector<AppInfo> &infos);
int32_t GetResultSetTableInfo(const std::shared_ptr<NativeRdb::ResultSet> &resultSet, AppInfoTableInfo &table);
void SetValuesBucket(const AppInfo &event, NativeRdb::ValuesBucket &values);
std::string CreateTable();
std::string dbPath_{};
std::string dbTable_{};
};
} // namespace OHOS::Security::SecurityGuard {
#endif // SECURITY_GUARD_DATABASE_HELPER_H

View File

@ -46,6 +46,22 @@ using AppDetectionCfg = struct {
std::string falseResult;
};
using AppAttribute = enum {
NORMAL,
PAYMENT,
MALICIOUS,
MONITORING,
ATTRMAX
};
using AppInfo = struct {
std::string appName;
std::string appHash;
std::vector<std::string> attrs;
int isGlobalApp;
int isUpdate;
};
using ModelCfg = struct {
uint32_t modelId;
std::string path;
@ -69,27 +85,13 @@ enum class EventTypeEnum {
SUBSCRIBE_COLL = 3
};
using EventCfg = struct {
int64_t eventId;
std::string eventName;
uint32_t version;
uint32_t eventType;
uint32_t collectOnStart;
uint32_t dataSensitivityLevel;
uint32_t storageRamNums;
uint32_t storageRomNums;
int32_t storageTime;
std::vector<std::string> owner;
uint32_t source;
std::string dbTable;
std::string prog;
};
using DataMgrCfgSt = struct {
uint32_t deviceRom;
uint32_t deviceRam;
uint32_t eventMaxRamNum;
uint32_t eventMaxRomNum;
std::string prog;
};
using EventContentSt = struct {
@ -110,21 +112,6 @@ using SecEvent = struct {
std::string deviceId;
};
using AppAttribute = enum {
NORMAL,
PAYMENT,
MALICIOUS,
MONITORING,
ATTRMAX
};
using AppInfo = struct {
std::string appName;
std::string appHash;
std::vector<std::string> attrs;
int isGlobalApp;
int isUpdate;
};
using StartMode = enum {
NOT_SUPPORT,
START_ON_STARTUP,
@ -154,27 +141,27 @@ using PathIndex = enum {
};
const std::vector<std::string> CONFIG_CACHE_FILES = {
"/data/service/el1/public/security_guard/tmp/security_guard_event.cfg",
"/data/service/el1/public/security_guard/tmp/security_guard_event.json",
"/data/service/el1/public/security_guard/tmp/security_guard_model.cfg",
"/data/service/el1/public/security_guard/tmp/signature_rule.cfg",
"/data/service/el1/public/security_guard/tmp/url_rule.cfg",
"/data/service/el1/public/security_guard/tmp/signature_rule.json",
"/data/service/el1/public/security_guard/tmp/url_rule.json",
"/data/service/el1/public/security_guard/tmp/local_app_attribute.json",
"/data/service/el1/public/security_guard/tmp/global_app_attribute.json",
"/data/service/el1/public/security_guard/tmp/related_event_analysis.json"
};
const std::vector<std::string> CONFIG_UPTATE_FILES = {
"/data/service/el1/public/security_guard/security_guard_event.cfg",
"/data/service/el1/public/security_guard/security_guard_event.json",
"/data/service/el1/public/security_guard/security_guard_model.cfg",
"/data/service/el1/public/security_guard/signature_rule.cfg",
"/data/service/el1/public/security_guard/url_rule.cfg",
"/data/service/el1/public/security_guard/signature_rule.json",
"/data/service/el1/public/security_guard/url_rule.json",
"/data/service/el1/public/security_guard/local_app_attr.json",
"/data/service/el1/public/security_guard/global_app_attr.json",
"/data/service/el1/public/security_guard/related_event_analysis.json"
};
const std::vector<std::string> CONFIG_PRESET_FILES = {
"/system/etc/security_guard_event.cfg",
"/system/etc/security_guard_event.json",
"/system/etc/security_guard_model.cfg"
};

View File

@ -18,17 +18,11 @@
#include <functional>
#include <string>
#include <mutex>
namespace OHOS::Security::SecurityGuard {
using TimeEventRelatedCallBack = std::function<bool(void)>;
class ConfigSubscriber {
public:
static bool RegisterTimeEventRelatedCallBack(const TimeEventRelatedCallBack &callBack);
static bool UpdateConfig(const std::string &file);
private:
static bool UpdateRelatedEventAnalysisCfg(const std::string &file);
static TimeEventRelatedCallBack timeEventCallBack_ ;
static std::mutex callBackMutex_;
};
} // OHOS::Security::SecurityGuard

View File

@ -20,7 +20,7 @@
#include "base_config.h"
#include "config_define.h"
#include "security_event_info.h"
namespace OHOS::Security::SecurityGuard {
class EventConfig : public BaseConfig {
public:

View File

@ -1,40 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_LOCAL_APP_CONFIG_H
#define SECURITY_GUARD_LOCAL_APP_CONFIG_H
#include "nlohmann/json.hpp"
#include "base_config.h"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {
class LocalAppConfig : public BaseConfig {
public:
LocalAppConfig() = default;
~LocalAppConfig() override = default;
bool Load(int mode) override;
bool Parse() override;
bool Update() override;
private:
bool ParseAppListConfig(std::vector<AppInfo>& configs, const nlohmann::json& json);
bool UpdateInfoToDb(const std::vector<AppInfo> &configs);
bool IsNeedUpdate(const AppInfo &config, const AppInfo &dbConfig, bool &isFind);
};
} // OHOS::Security::SecurityGuard
#endif // SECURITY_GUARD_MODEL_CONFIG_H

View File

@ -20,7 +20,7 @@
#include <vector>
#include "nlohmann/json.hpp"
#include "security_event_info.h"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {

2
services/config_manager/sg_config_manager.map Normal file → Executable file
View File

@ -31,9 +31,9 @@
OHOS::Security::SecurityGuard::ConfigDataManager::GetAllModelIds*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetEventConfig*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetModelConfig*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetAppInfosByName*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetAllEventIds*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetTableFromEventId*;
OHOS::Security::SecurityGuard::ConfigDataManager::GetAllEventConfigs*;
};
local:
*;

View File

@ -1,45 +0,0 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "app_info_rdb_helper.h"
#include "rdb_event_store_callback.h"
#include "config_database_helper.h"
namespace OHOS::Security::SecurityGuard {
ConfigDatabaseHelper &AppInfoRdbHelper::GetInstance()
{
static AppInfoRdbHelper appInfoInstance;
static ConfigDatabaseHelper &instance = appInfoInstance;
return instance;
}
AppInfoRdbHelper::AppInfoRdbHelper() : ConfigDatabaseHelper(APP_INFO_TABLE)
{
dbPath_ = FOLDER_PATH + "app_info.db";
}
int AppInfoRdbHelper::Init()
{
int errCode = NativeRdb::E_ERROR;
NativeRdb::RdbStoreConfig config(dbPath_);
config.SetSecurityLevel(NativeRdb::SecurityLevel::S1);
std::string table = CreateTable();
std::vector<std::string> createTableVec;
createTableVec.push_back(table);
RdbEventStoreCallback callback(createTableVec);
CreateRdbStore(config, DB_VERSION, callback, errCode);
return errCode;
}
} // namespace OHOS::Security::SecurityGuard

View File

@ -26,15 +26,15 @@ namespace {
bool BaseConfig::Check()
{
if (!stream_.is_open() ||!stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error");
return false;
}
stream_.seekg(0, std::ios::end);
int len = static_cast<int>(stream_.tellg());
std::ios::pos_type len = stream_.tellg();
if (len == 0 || len > CFG_FILE_MAX_SIZE) {
SGLOGE("stream is empty or too large, len = %{public}d", len);
SGLOGE("stream is empty or too large");
stream_.close();
return false;
}

View File

@ -14,9 +14,9 @@
*/
#include "config_data_manager.h"
#include <cinttypes>
#include "security_guard_log.h"
#include "app_info_rdb_helper.h"
namespace OHOS::Security::SecurityGuard {
ConfigDataManager &ConfigDataManager::GetInstance()
@ -90,7 +90,7 @@ std::vector<int64_t> ConfigDataManager::GetAllEventIds()
std::lock_guard<std::mutex> lock(eventMutex_);
std::vector<int64_t> vector;
for (const auto &entry : eventMap_) {
SGLOGD("eventId=%{public}" PRId64 "", entry.first);
SGLOGD("eventId=%{public}" PRId64, entry.first);
vector.emplace_back(entry.first);
}
return vector;
@ -107,6 +107,16 @@ std::vector<uint32_t> ConfigDataManager::GetAllModelIds()
return vector;
}
std::vector<EventCfg> ConfigDataManager::GetAllEventConfigs()
{
std::lock_guard<std::mutex> lock(eventMutex_);
std::vector<EventCfg> vector;
for (const auto &entry : eventMap_) {
vector.emplace_back(entry.second);
}
return vector;
}
bool ConfigDataManager::GetModelConfig(uint32_t modelId, ModelCfg &config)
{
std::lock_guard<std::mutex> lock(modelMutex_);
@ -132,13 +142,10 @@ bool ConfigDataManager::GetEventConfig(int64_t eventId, EventCfg &config)
std::string ConfigDataManager::GetTableFromEventId(int64_t eventId)
{
std::lock_guard<std::mutex> lock(eventToTableMutex_);
if (eventToTableMap_.find(eventId) == eventToTableMap_.end()) {
SGLOGE("eventToTableMap_ did not find eventId=%{public}" PRId64, eventId);
return "";
}
return eventToTableMap_[eventId];
}
std::vector<AppInfo> ConfigDataManager::GetAppInfosByName(const std::string &appName)
{
std::vector<AppInfo> infos;
AppInfoRdbHelper::GetInstance().QueryAppInfosByName(appName, infos);
return infos;
}
} // OHOS::Security::SecurityGuard

View File

@ -1,299 +0,0 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config_database_helper.h"
#include <vector>
#include <array>
#include "string_ex.h"
#include "config_define.h"
#include "rdb_event_store_callback.h"
#include "security_guard_define.h"
#include "security_guard_log.h"
namespace OHOS::Security::SecurityGuard {
ConfigDatabaseHelper::ConfigDatabaseHelper(std::string dbTable)
{
dbTable_ = dbTable;
}
int ConfigDatabaseHelper::Init()
{
return SUCCESS;
}
int ConfigDatabaseHelper::InsertAppInfo(const AppInfo& info)
{
NativeRdb::ValuesBucket values {};
SetValuesBucket(info, values);
int64_t rowId;
int ret = Insert(rowId, dbTable_, values);
if (ret != NativeRdb::E_OK) {
SGLOGI("failed to add app info, appName=%{public}s, ret=%{public}d", info.appName.c_str(), ret);
return DB_OPT_ERR;
}
return SUCCESS;
}
int ConfigDatabaseHelper::InsertAllAppInfo(const std::vector<AppInfo>& infos)
{
SGLOGI("InsertAllAppInfo....");
std::vector<NativeRdb::ValuesBucket> values {};
for (auto iter : infos) {
NativeRdb::ValuesBucket value {};
SetValuesBucket(iter, value);
values.emplace_back(value);
}
int64_t rowId;
int ret = BatchInsert(rowId, dbTable_, values);
if (ret != NativeRdb::E_OK) {
SGLOGE("failed to batch insert event, ret=%{public}d", ret);
return DB_OPT_ERR;
}
return SUCCESS;
}
int ConfigDatabaseHelper::QueryAllAppInfo(std::vector<AppInfo> &infos)
{
SGLOGI("QueryAllAppInfo....");
NativeRdb::RdbPredicates predicates(dbTable_);
return QueryAppInfoBase(predicates, infos);
}
int32_t ConfigDatabaseHelper::QueryAppInfoBase(const NativeRdb::RdbPredicates &predicates, std::vector<AppInfo> &infos)
{
std::vector<std::string> columns {APP_NAME, APP_FINGERPRINT, APP_ATTRIBUTES, IS_GLOBAL_APP};
std::shared_ptr<NativeRdb::ResultSet> resultSet = Query(predicates, columns);
if (resultSet == nullptr) {
SGLOGE("failed to get event");
return DB_OPT_ERR;
}
AppInfoTableInfo table;
int32_t ret = GetResultSetTableInfo(resultSet, table);
if (ret != SUCCESS) {
return ret;
}
while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
AppInfo info;
resultSet->GetString(table.appNameIndex, info.appName);
resultSet->GetString(table.appHashIndex, info.appHash);
std::string attrStr;
std::vector<std::string> tmpVec;
resultSet->GetString(table.appAttrIndex, attrStr);
SplitStr(attrStr, ",", tmpVec);
info.attrs = tmpVec;
resultSet->GetInt(table.appIsGlobalAppIndex, info.isGlobalApp);
infos.emplace_back(info);
}
resultSet->Close();
return SUCCESS;
}
int32_t ConfigDatabaseHelper::GetResultSetTableInfo(const std::shared_ptr<NativeRdb::ResultSet> &resultSet,
AppInfoTableInfo &table)
{
int32_t rowCount = 0;
int32_t columnCount = 0;
std::vector<std::string> columnNames;
if (resultSet->GetRowCount(rowCount) != NativeRdb::E_OK ||
resultSet->GetColumnCount(columnCount) != NativeRdb::E_OK ||
resultSet->GetAllColumnNames(columnNames) != NativeRdb::E_OK) {
SGLOGE("get table info failed");
return DB_LOAD_ERR;
}
int32_t columnNamesCount = static_cast<int32_t>(columnNames.size());
for (int32_t i = 0; i < columnNamesCount; i++) {
std::string columnName = columnNames.at(i);
if (columnName == ID) {
table.primaryKeyIndex = i;
}
if (columnName == APP_NAME) {
table.appNameIndex = i;
}
if (columnName == APP_FINGERPRINT) {
table.appHashIndex = i;
}
if (columnName == APP_ATTRIBUTES) {
table.appAttrIndex = i;
}
if (columnName == IS_GLOBAL_APP) {
table.appIsGlobalAppIndex = i;
}
}
table.rowCount = rowCount;
table.columnCount = columnCount;
SGLOGD("info: row=%{public}d col=%{public}d appNameIdx=%{public}d appHashIdx=%{public}d "
"appAttrIdx=%{public}d", rowCount, columnCount,
table.appNameIndex, table.appHashIndex, table.appAttrIndex);
return SUCCESS;
}
int ConfigDatabaseHelper::QueryAppInfosByName(const std::string &appName, std::vector<AppInfo> &infos)
{
std::vector<std::string> columns {APP_NAME, APP_FINGERPRINT, APP_ATTRIBUTES, IS_GLOBAL_APP};
NativeRdb::RdbPredicates predicates(dbTable_);
predicates.EqualTo(APP_NAME, appName);
predicates.OrderByDesc(ID);
std::shared_ptr<NativeRdb::ResultSet> resultSet = Query(predicates, columns);
if (resultSet == nullptr) {
SGLOGI("failed to get appInfo");
return DB_OPT_ERR;
}
AppInfoTableInfo table;
int32_t ret = GetResultSetTableInfo(resultSet, table);
if (ret != SUCCESS) {
return ret;
}
while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
AppInfo info {};
resultSet->GetString(table.appNameIndex, info.appName);
resultSet->GetString(table.appHashIndex, info.appHash);
std::string attrStr;
std::vector<std::string> tmpVec;
resultSet->GetString(table.appAttrIndex, attrStr);
SplitStr(attrStr, ",", tmpVec);
info.attrs = tmpVec;
resultSet->GetInt(table.appIsGlobalAppIndex, info.isGlobalApp);
infos.emplace_back(info);
}
resultSet->Close();
return SUCCESS;
}
int ConfigDatabaseHelper::DeleteAppInfoByNameAndGlobbalFlag(const std::string &appName, int isGlobalApp)
{
SGLOGI("DeleteAppInfoByName, appName=%{public}s", appName.c_str());
NativeRdb::RdbPredicates queryPredicates(dbTable_);
queryPredicates.EqualTo(APP_NAME, appName);
queryPredicates.EqualTo(IS_GLOBAL_APP, isGlobalApp);
queryPredicates.OrderByAsc(ID);
std::vector<std::string> columns { ID };
std::shared_ptr<NativeRdb::ResultSet> resultSet = Query(queryPredicates, columns);
if (resultSet == nullptr) {
SGLOGI("failed to get event, appName=%{public}s", appName.c_str());
return DB_OPT_ERR;
}
int64_t primaryKey = -1;
std::vector<std::string> primaryKeyVec;
while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
resultSet->GetLong(0, primaryKey);
primaryKeyVec.emplace_back(std::to_string(primaryKey));
}
resultSet->Close();
int rowId;
NativeRdb::RdbPredicates deletePredicates(dbTable_);
deletePredicates.In(ID, primaryKeyVec);
deletePredicates.EqualTo(APP_NAME, appName);
deletePredicates.EqualTo(IS_GLOBAL_APP, isGlobalApp);
int ret = Delete(rowId, deletePredicates);
if (ret != NativeRdb::E_OK) {
SGLOGE("failed to delete event, appName=%{public}s, ret=%{public}d", appName.c_str(), ret);
return DB_OPT_ERR;
}
return SUCCESS;
}
int ConfigDatabaseHelper::DeleteAppInfoByIsGlobalApp(int isGlobalApp)
{
NativeRdb::RdbPredicates queryPredicates(dbTable_);
queryPredicates.EqualTo(IS_GLOBAL_APP, isGlobalApp);
queryPredicates.OrderByAsc(ID);
std::vector<std::string> columns { ID };
std::shared_ptr<NativeRdb::ResultSet> resultSet = Query(queryPredicates, columns);
if (resultSet == nullptr) {
SGLOGI("failed to get resultSet");
return DB_OPT_ERR;
}
int64_t primaryKey = -1;
std::vector<std::string> primaryKeyVec;
while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
resultSet->GetLong(0, primaryKey);
primaryKeyVec.emplace_back(std::to_string(primaryKey));
}
resultSet->Close();
int rowId;
NativeRdb::RdbPredicates deletePredicates(dbTable_);
deletePredicates.In(ID, primaryKeyVec);
deletePredicates.EqualTo(IS_GLOBAL_APP, isGlobalApp);
int ret = Delete(rowId, deletePredicates);
if (ret != NativeRdb::E_OK) {
SGLOGE("failed to delete App, ret=%{public}d", ret);
return DB_OPT_ERR;
}
return SUCCESS;
}
int ConfigDatabaseHelper::QueryAppInfoByAttribute(const std::string attr, std::vector<AppInfo> &infos)
{
NativeRdb::RdbPredicates predicates(dbTable_);
std::vector<std::string> columns {APP_NAME, APP_FINGERPRINT, APP_ATTRIBUTES, IS_GLOBAL_APP};
std::shared_ptr<NativeRdb::ResultSet> resultSet = Query(predicates, columns);
if (resultSet == nullptr) {
SGLOGI("failed to get event");
return DB_OPT_ERR;
}
AppInfoTableInfo table;
int32_t ret = GetResultSetTableInfo(resultSet, table);
if (ret != SUCCESS) {
return ret;
}
while (resultSet->GoToNextRow() == NativeRdb::E_OK) {
AppInfo info;
std::string attrStr;
std::vector<std::string> tmpVec;
resultSet->GetString(table.appAttrIndex, attrStr);
if (attrStr.find(attr) == std::string::npos) {
continue;
}
SplitStr(attrStr, ",", tmpVec);
info.attrs = tmpVec;
resultSet->GetString(table.appNameIndex, info.appName);
resultSet->GetString(table.appHashIndex, info.appHash);
infos.emplace_back(info);
}
resultSet->Close();
return SUCCESS;
}
void ConfigDatabaseHelper::SetValuesBucket(const AppInfo &event, NativeRdb::ValuesBucket &values)
{
std::string attrStr;
uint32_t index = 1;
// construct attr vector to string, exp: 111,222,333
for (auto iter : event.attrs) {
attrStr.append(iter);
if (index == event.attrs.size()) {
break;
}
attrStr.append(",");
index++;
}
values.PutString(APP_NAME, event.appName);
values.PutString(APP_FINGERPRINT, event.appHash);
values.PutString(APP_ATTRIBUTES, attrStr);
values.PutInt(IS_GLOBAL_APP, event.isGlobalApp);
}
std::string ConfigDatabaseHelper::CreateTable()
{
std::string table;
table.append("CREATE TABLE IF NOT EXISTS ").append(dbTable_);
table.append("(").append(ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT, ");
table.append(APP_NAME).append(" TEXT NOT NULL, ");
table.append(APP_FINGERPRINT).append(" TEXT NOT NULL, ");
table.append(APP_ATTRIBUTES).append(" TEXT NOT NULL, ");
table.append(IS_GLOBAL_APP).append(" INTEGER NOT NULL)");
return table;
}
} // namespace OHOS::Security::SecurityGuard

View File

@ -17,7 +17,6 @@
#include "config_subscriber.h"
#include "security_guard_log.h"
#include "app_info_rdb_helper.h"
namespace OHOS::Security::SecurityGuard {
ConfigManager &ConfigManager::GetInstance()
{
@ -27,7 +26,5 @@ ConfigManager &ConfigManager::GetInstance()
void ConfigManager::StartUpdate()
{
int ret = AppInfoRdbHelper::GetInstance().Init();
SGLOGI("app config rdb init result is %{public}d", ret);
};
} // OHOS::Security::SecurityGuard

View File

@ -26,41 +26,10 @@
#include "config_define.h"
#include "config_manager.h"
#include "model_config.h"
#include "local_app_config.h"
#include "global_app_config.h"
#include "security_guard_log.h"
#include "security_guard_utils.h"
namespace OHOS::Security::SecurityGuard {
TimeEventRelatedCallBack ConfigSubscriber::timeEventCallBack_ {nullptr};
std::mutex ConfigSubscriber::callBackMutex_ {};
bool ConfigSubscriber::RegisterTimeEventRelatedCallBack(const TimeEventRelatedCallBack &callBack)
{
std::lock_guard<std::mutex> lock(callBackMutex_);
if (callBack == nullptr) {
SGLOGE("callBack is null");
return false;
}
SGLOGI("RegisterTimeEventRelatedCallBack...");
timeEventCallBack_ = callBack;
return true;
}
bool ConfigSubscriber::UpdateRelatedEventAnalysisCfg(const std::string &file)
{
bool isSuccess = false;
{
std::lock_guard<std::mutex> lock(callBackMutex_);
if (timeEventCallBack_ != nullptr) {
isSuccess = timeEventCallBack_();
}
}
if (isSuccess) {
return SecurityGuardUtils::CopyFile(file, CONFIG_UPTATE_FILES[RELATED_EVENT_ANALYSIS_CFG_INDEX]);
}
return isSuccess;
}
bool ConfigSubscriber::UpdateConfig(const std::string &file)
{
@ -70,16 +39,6 @@ bool ConfigSubscriber::UpdateConfig(const std::string &file)
isSuccess = ConfigManager::UpdataConfig<EventConfig>();
} else if (file == CONFIG_CACHE_FILES[MODEL_CFG_INDEX]) {
isSuccess = ConfigManager::UpdataConfig<ModelConfig>();
} else if (file == CONFIG_CACHE_FILES[SIG_RULE_CFG_INDEX]) {
isSuccess = SecurityGuardUtils::CopyFile(file, CONFIG_UPTATE_FILES[SIG_RULE_CFG_INDEX]);
} else if (file == CONFIG_CACHE_FILES[URL_RULE_CFG_INDEX]) {
isSuccess = SecurityGuardUtils::CopyFile(file, CONFIG_UPTATE_FILES[URL_RULE_CFG_INDEX]);
} else if (file == CONFIG_CACHE_FILES[RELATED_EVENT_ANALYSIS_CFG_INDEX]) {
isSuccess = UpdateRelatedEventAnalysisCfg(file);
} else if (file == CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX]) {
isSuccess = ConfigManager::UpdataConfig<LocalAppConfig>();
} else if (file == CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX]) {
isSuccess = ConfigManager::UpdataConfig<GlobalAppConfig>();
}
event.path = file;
event.time = SecurityGuardUtils::GetDate();
@ -87,9 +46,12 @@ bool ConfigSubscriber::UpdateConfig(const std::string &file)
SGLOGD("file path=%{public}s, TIME=%{public}s, ret=%{public}d", event.path.c_str(), event.time.c_str(),
event.ret);
BigData::ReportConfigUpdateEvent(event);
bool success = RemoveFile(file);
if (!success) {
SGLOGW("remove file error, %{public}s", strerror(errno));
if (file != CONFIG_CACHE_FILES[EVENT_CFG_INDEX] && file != CONFIG_CACHE_FILES[MODEL_CFG_INDEX]) {
return true;
}
if (!RemoveFile(file)) {
SGLOGE("remove file error, %{public}s", strerror(errno));
}
return isSuccess;
}

View File

@ -51,7 +51,7 @@ bool EventConfig::Load(int mode)
return false;
}
stream_ = std::ifstream(path, std::ios::in);
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error, %{public}s", strerror(errno));
return false;
}
@ -60,7 +60,7 @@ bool EventConfig::Load(int mode)
bool EventConfig::Parse()
{
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error");
return false;
}
@ -86,7 +86,7 @@ bool EventConfig::Parse()
bool EventConfig::Update()
{
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error");
return false;
}
@ -105,7 +105,10 @@ bool EventConfig::Update()
return false;
}
SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[EVENT_CFG_INDEX], CONFIG_UPTATE_FILES[EVENT_CFG_INDEX]);
if (!SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[EVENT_CFG_INDEX], CONFIG_UPTATE_FILES[EVENT_CFG_INDEX])) {
SGLOGE("copyFile error");
return false;
}
ConfigDataManager::GetInstance().ResetEventMap();
EventConfig::CacheEventConfig(configs);
EventConfig::CacheEventToTable(configs);

View File

@ -1,134 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "global_app_config.h"
#include <unordered_set>
#include "app_info_rdb_helper.h"
#include "security_guard_log.h"
#include "security_guard_utils.h"
#include "security_guard_define.h"
#include "file_ex.h"
#include "json_cfg.h"
namespace OHOS::Security::SecurityGuard {
namespace {
const char* APPS = "apps";
const char* NAME = "name";
const char* FINGERPRINTER = "fingerprint";
const char* ATTRIBUTE = "attribute";
constexpr uint32_t HASHLENGTH = 64;
constexpr uint32_t MAXAPPNAMELENGTH = 256;
}
bool GlobalAppConfig::Load(int mode)
{
std::string path;
if (mode == INIT_MODE) {
if (FileExists(CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX])) {
path = CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX];
} else {
return true;
}
}
if (mode == UPDATE_MODE) {
if (FileExists(CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX])) {
path = CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX];
}
}
SGLOGD("path=%{public}s", path.c_str());
if (path.empty()) {
SGLOGE("path is empty");
return false;
}
stream_ = std::ifstream(path, std::ios::in);
if (!stream_.is_open() || !stream_) {
SGLOGE("stream error, %{public}s", strerror(errno));
return false;
}
return true;
}
bool GlobalAppConfig::Parse()
{
return true;
}
bool GlobalAppConfig::Update()
{
if (!stream_.is_open() || !stream_) {
SGLOGE("stream error");
return false;
}
nlohmann::json jsonObj = nlohmann::json::parse(stream_, nullptr, false);
stream_.close();
if (jsonObj.is_discarded()) {
SGLOGE("Parse GlobalAppConfig json error");
return false;
}
std::vector<AppInfo> configs;
if (!ParseAppListConfig(configs, jsonObj)) {
SGLOGE("parse GlobalAppConfig error");
return false;
}
for (size_t i = 0; i < configs.size(); i++) {
for (size_t j = i + 1; j < configs.size(); j++) {
if (configs[i].appName == configs[j].appName) {
SGLOGE("app%{public}s name repeate", configs[i].appName.c_str());
return false;
}
}
}
if (AppInfoRdbHelper::GetInstance().DeleteAppInfoByIsGlobalApp(1) != SUCCESS) {
SGLOGE("DeleteAppInfoByIsGlobalApp error");
return false;
}
if (AppInfoRdbHelper::GetInstance().InsertAllAppInfo(configs)) {
SGLOGE("InsertAllAppInfo error");
return false;
}
SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[GLOBAL_APP_CFG_INDEX], CONFIG_UPTATE_FILES[GLOBAL_APP_CFG_INDEX]);
return true;
}
bool GlobalAppConfig::ParseAppListConfig(std::vector<AppInfo>& configs, const nlohmann::json& json)
{
if (json.find(APPS) == json.end() || !json.at(APPS).is_array()) {
SGLOGE("check %{public}s error", APPS);
return false;
}
for (auto it : json.at(APPS)) {
AppInfo config {};
config.isGlobalApp = 1;
if (!JsonCfg::Unmarshal(config.appHash, it, FINGERPRINTER) || config.appHash.size() != HASHLENGTH) {
SGLOGE("parse %{public}s error", FINGERPRINTER);
return false;
}
if (!JsonCfg::Unmarshal(config.appName, it, NAME) || config.appName.size() > MAXAPPNAMELENGTH ||
config.appName.empty()) {
SGLOGE("parse %{public}s error", NAME);
return false;
}
std::unordered_set<std::string> tmp = {"monitoring", "payment", "malicious"};
if (!JsonCfg::Unmarshal(config.attrs, it, ATTRIBUTE) || config.attrs.size() >= ATTRMAX) {
SGLOGE("parse %{public}s error", ATTRIBUTE);
return false;
}
for (auto iter : config.attrs) {
if (tmp.count(iter) == 0) {
SGLOGE("check %{public}s error", ATTRIBUTE);
return false;
}
}
configs.emplace_back(config);
}
return true;
}
}

View File

@ -1,190 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "local_app_config.h"
#include <unordered_set>
#include "app_info_rdb_helper.h"
#include "security_guard_log.h"
#include "security_guard_utils.h"
#include "security_guard_define.h"
#include "file_ex.h"
#include "json_cfg.h"
namespace OHOS::Security::SecurityGuard {
namespace {
const char* APPS = "apps";
const char* NAME = "name";
const char* FINGERPRINTER = "fingerprint";
const char* ATTRIBUTE = "attribute";
const char* ISUPDATE = "isUpdate";
constexpr uint32_t HASHLENGTH = 64;
constexpr uint32_t MAXAPPNAMELENGTH = 256;
}
bool LocalAppConfig::Load(int mode)
{
std::string path;
if (mode == INIT_MODE) {
if (FileExists(CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX])) {
path = CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX];
} else {
return true;
}
}
if (mode == UPDATE_MODE) {
if (FileExists(CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX])) {
path = CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX];
}
}
SGLOGI("path=%{public}s", path.c_str());
if (path.empty()) {
SGLOGE("path is empty");
return false;
}
stream_ = std::ifstream(path, std::ios::in);
if (!stream_.is_open() || !stream_) {
SGLOGE("stream error, %{public}s", strerror(errno));
return false;
}
return true;
}
bool LocalAppConfig::Parse()
{
return true;
}
bool LocalAppConfig::Update()
{
if (!stream_.is_open() || !stream_) {
SGLOGE("stream error");
return false;
}
nlohmann::json jsonObj = nlohmann::json::parse(stream_, nullptr, false);
stream_.close();
if (jsonObj.is_discarded()) {
SGLOGE("Parse LocalAppConfig json error");
return false;
}
std::vector<AppInfo> configs;
if (!ParseAppListConfig(configs, jsonObj)) {
SGLOGE("Parse LocalAppConfig error");
return false;
}
for (size_t i = 0; i < configs.size(); i++) {
for (size_t j = i + 1; j < configs.size(); j++) {
if (configs[i].appName == configs[j].appName) {
SGLOGE("app%{public}s name repeate", configs[i].appName.c_str());
return false;
}
}
}
if (!UpdateInfoToDb(configs)) {
SGLOGE("UpdateInfoToDb error");
return false;
}
SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[LOCAL_APP_CFG_INDEX], CONFIG_UPTATE_FILES[LOCAL_APP_CFG_INDEX]);
return true;
}
bool LocalAppConfig::ParseAppListConfig(std::vector<AppInfo>& configs, const nlohmann::json& json)
{
if (json.find(APPS) == json.end() || !json.at(APPS).is_array()) {
SGLOGE("check %{public}s error", APPS);
return false;
}
for (auto it : json.at(APPS)) {
AppInfo config {};
if (!JsonCfg::Unmarshal(config.appHash, it, FINGERPRINTER) || config.appHash.size() != HASHLENGTH) {
SGLOGE("parse %{public}s error", FINGERPRINTER);
return false;
}
if (!JsonCfg::Unmarshal(config.appName, it, NAME) || config.appName.size() > MAXAPPNAMELENGTH ||
config.appName.empty()) {
SGLOGE("parse %{public}s error", NAME);
return false;
}
std::unordered_set<std::string> tmp = {"monitoring", "payment", "malicious"};
if (!JsonCfg::Unmarshal(config.attrs, it, ATTRIBUTE) || config.attrs.size() >= ATTRMAX) {
SGLOGE("parse %{public}s error", ATTRIBUTE);
return false;
}
for (auto iter : config.attrs) {
if (tmp.count(iter) == 0) {
SGLOGE("check %{public}s error", ATTRIBUTE);
return false;
}
}
if (!JsonCfg::Unmarshal(config.isUpdate, it, ISUPDATE) || (config.isUpdate != 0 && config.isUpdate != 1)) {
SGLOGE("parse %{public}s error", ISUPDATE);
return false;
}
configs.emplace_back(config);
}
return true;
}
bool LocalAppConfig::IsNeedUpdate(const AppInfo &config, const AppInfo &dbConfig, bool &isFind)
{
if (config.appName == dbConfig.appName) {
isFind = true;
if (config.isUpdate == 1) {
AppInfoRdbHelper::GetInstance().DeleteAppInfoByNameAndGlobbalFlag(config.appName, 0);
if (AppInfoRdbHelper::GetInstance().InsertAppInfo(config) != SUCCESS) {
SGLOGE("InsertAppInfo error");
return false;
}
}
}
return true;
}
bool LocalAppConfig::UpdateInfoToDb(const std::vector<AppInfo> &configs)
{
SGLOGI("UpdateInfoToDb ..................");
std::vector<AppInfo> dbConfigs;
if (AppInfoRdbHelper::GetInstance().QueryAllAppInfo(dbConfigs) != SUCCESS) {
SGLOGE("QueryAllAppInfo error");
return false;
}
for (auto iter : dbConfigs) {
bool isFind = false;
SGLOGI("appName %{public}s isGlobalApp %{public}d", iter.appName.c_str(), iter.isGlobalApp);
if (iter.isGlobalApp == 1) {
continue;
}
for (auto it : configs) {
if (!IsNeedUpdate(it, iter, isFind)) {
return false;
}
}
if (!isFind) {
AppInfoRdbHelper::GetInstance().DeleteAppInfoByNameAndGlobbalFlag(iter.appName, 0);
}
}
for (auto iter : configs) {
bool isFind = false;
for (auto it : dbConfigs) {
if (it.appName == iter.appName && it.isGlobalApp == 0) {
isFind = true;
break;
}
}
if (!isFind && (iter.isUpdate == 1)) {
if (AppInfoRdbHelper::GetInstance().InsertAppInfo(iter) != SUCCESS) {
SGLOGE("InsertAppInfo error");
return false;
}
}
}
return true;
}
}

0
services/config_manager/src/model_cfg_marshalling.cpp Executable file → Normal file
View File

View File

@ -45,7 +45,7 @@ bool ModelConfig::Load(int mode)
return false;
}
stream_ = std::ifstream(path, std::ios::in);
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error, %{public}s", strerror(errno));
return false;
}
@ -54,7 +54,7 @@ bool ModelConfig::Load(int mode)
bool ModelConfig::Parse()
{
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error");
return false;
}
@ -80,7 +80,7 @@ bool ModelConfig::Parse()
bool ModelConfig::Update()
{
if (!stream_.is_open() || !stream_) {
if (!stream_.is_open()) {
SGLOGE("stream error");
return false;
}
@ -99,7 +99,10 @@ bool ModelConfig::Update()
return false;
}
SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[MODEL_CFG_INDEX], CONFIG_UPTATE_FILES[MODEL_CFG_INDEX]);
if (!SecurityGuardUtils::CopyFile(CONFIG_CACHE_FILES[MODEL_CFG_INDEX], CONFIG_UPTATE_FILES[MODEL_CFG_INDEX])) {
SGLOGE("copyFile error");
return false;
}
ConfigDataManager::GetInstance().ResetModelMap();
CacheModelConfig(configs);
CacheModelToEvent(configs);

View File

@ -14,55 +14,6 @@
import("//base/security/security_guard/security_guard.gni")
import("//build/ohos.gni")
ohos_source_set("sg_uevent_listener_stamp") {
subsystem_name = "security"
part_name = "security_guard"
configs = [
"${sg_root_dir}/services/risk_classify:security_guard_model_configs",
"${sg_root_dir}/resource/config/build:coverage_flags",
]
include_dirs = [
"${sg_root_dir}/services/risk_collect/include",
"${sg_root_dir}/frameworks/common/constants/include",
"${sg_root_dir}/frameworks/common/database/include",
"${sg_root_dir}/frameworks/common/log/include",
"${sg_root_dir}/services/config_manager/include",
"${sg_root_dir}/frameworks/common/task_handler/include",
"${sg_root_dir}/frameworks/common/json/include",
"${sg_root_dir}/frameworks/common/utils/include",
"${sg_root_dir}/services/data_collect/store/include",
]
sources = [
"${sg_root_dir}/frameworks/common/json/src/json_cfg.cpp",
"${sg_root_dir}/frameworks/common/utils/src/security_guard_utils.cpp",
"${sg_root_dir}/services/risk_collect/src/data_format.cpp",
]
sanitize = {
integer_overflow = true
ubsan = true
boundary_sanitize = true
cfi = true
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
deps = [ "${sg_root_dir}/frameworks/common/task_handler:sg_task_stamp" ]
external_deps = [
"c_utils:utils",
"hdf_core:libhdf_ipc_adapter",
"hilog:libhilog",
"init:libbegetutil",
"json:nlohmann_json_static",
"relational_store:native_rdb",
]
}
ohos_shared_library("sg_collect_service") {
subsystem_name = "security"
part_name = "security_guard"
@ -80,10 +31,8 @@ ohos_shared_library("sg_collect_service") {
"${sg_root_dir}/frameworks/common/interfaces",
"${sg_root_dir}/services/bigdata/include",
"${sg_root_dir}/services/config_manager/include",
"${sg_root_dir}/services/data_collect/collect/hiview",
"${sg_root_dir}/services/data_collect/sa/include",
"${sg_root_dir}/services/data_collect/store/include",
"${sg_root_dir}/services/risk_collect/include",
"${sg_root_dir}/frameworks/common/constants/include",
"${sg_root_dir}/frameworks/common/json/include",
"${sg_root_dir}/frameworks/common/task_handler/include",
@ -91,17 +40,19 @@ ohos_shared_library("sg_collect_service") {
"${sg_root_dir}/frameworks/common/log/include",
"${sg_root_dir}/frameworks/common/utils/include",
"${sg_root_dir}/services/security_collector/include",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/include",
]
sources = [
"${sg_root_dir}/frameworks/common/json/src/json_cfg.cpp",
"${sg_root_dir}/frameworks/common/utils/src/security_guard_utils.cpp",
"${sg_root_dir}/interfaces/inner_api/collector/src/security_collector_subscribe_info.cpp",
"${sg_root_dir}/services/data_collect/collect/hiview/hiview_collector.cpp",
"${sg_root_dir}/services/data_collect/collect/hiview/hiview_listener.cpp",
"${sg_root_dir}/services/data_collect/sa/acquire_data_callback_proxy.cpp",
"${sg_root_dir}/services/data_collect/sa/acquire_data_subscribe_manager.cpp",
"${sg_root_dir}/services/data_collect/sa/data_collect_manager_callback_proxy.cpp",
"${sg_root_dir}/services/data_collect/sa/data_collect_manager_service.cpp",
"${sg_root_dir}/services/data_collect/sa/data_collect_manager_stub.cpp",
"${sg_root_dir}/services/data_collect/sa/data_format.cpp",
"${sg_root_dir}/services/data_collect/sa/security_event_query_callback_proxy.cpp",
"${sg_root_dir}/services/data_collect/store/src/database_helper.cpp",
"${sg_root_dir}/services/data_collect/store/src/database_manager.cpp",
@ -119,23 +70,21 @@ ohos_shared_library("sg_collect_service") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
deps = [
"${sg_root_dir}/frameworks/common/task_handler:sg_task_stamp",
"${sg_root_dir}/interfaces/inner_api/collect:libsg_collect_sdk",
"${sg_root_dir}/interfaces/inner_api/collector:libsg_collector_sdk",
"${sg_root_dir}/services/bigdata:sg_bigdata_stamp",
"${sg_root_dir}/services/config_manager:sg_config_manager",
"${sg_root_dir}/services/data_collect:sg_collect_service_database",
"${sg_root_dir}/services/data_collect:sg_uevent_listener_stamp",
]
external_deps = [
"ability_base:want",
"access_token:libaccesstoken_sdk",
"access_token:libtokenid_sdk",
"access_token:libtokenid_sdk",
"c_utils:utils",
"ffrt:libffrt",
"hilog:libhilog",
"hisysevent:libhisysevent",
"hisysevent:libhisyseventmanager",
@ -160,6 +109,7 @@ ohos_shared_library("sg_collect_service_database") {
"${sg_root_dir}/frameworks/common/database/include",
"${sg_root_dir}/frameworks/common/log/include",
"${sg_root_dir}/services/data_collect/store/include",
"${sg_root_dir}/interfaces/inner_api/data_collect_manager/include",
]
sources = [
@ -175,12 +125,11 @@ ohos_shared_library("sg_collect_service_database") {
cfi_cross_dso = true
debug = false
}
stack_protector_ret = true
branch_protector_ret = "pac_ret"
deps = []
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"relational_store:native_rdb",
]

View File

@ -1,36 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hiview_collector.h"
#include "hisysevent_manager.h"
#include "hisysevent_rules.h"
#include "hiview_listener.h"
#include "security_guard_log.h"
namespace OHOS::Security::SecurityGuard {
void HiviewCollector::Collect(std::vector<std::pair<std::string, std::string>> domainEventList)
{
std::vector<HiviewDFX::ListenerRule> rules;
for (auto domainEvent : domainEventList) {
HiviewDFX::ListenerRule rule(domainEvent.first, domainEvent.second);
rules.push_back(rule);
}
auto listener = std::make_shared<HiviewListener>();
int32_t ret = HiviewDFX::HiSysEventManager::AddListener(listener, rules);
SGLOGI("Add hiview listener result is %{public}d", ret);
}
} // OHOS::Security::SecurityGuard

View File

@ -1,133 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hiview_listener.h"
#include <unordered_set>
#include "database_manager.h"
#include "security_guard_log.h"
#include "security_guard_utils.h"
namespace OHOS::Security::SecurityGuard {
namespace {
constexpr int CONTENT_MAX_LEN = 900;
constexpr int64_t PASTEBOARD_EVENT_ID = 1011015000;
constexpr int64_t BUNDLE_INSTALL_EVENT_ID = 0x818800800;
constexpr int64_t BUNDLE_UPDATE_EVENT_ID = 0x818800801;
const std::unordered_set<std::string> HAP_INSTALL_UPDATE_STR = {"USERID", "BUNDLE_NAME",
"VERSION", "APP_DISTRIBUTION_TYPE", "INSTALL_TIME", "CALLING_UID", "CALLING_APPID",
"CALLING_BUNDLE_NAME", "FINGERPRINT", "HIDE_DESKTOP_ICON", "INSTALL_TYPE", "HASH_VALUE"};
}
void HiviewListener::OnEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent)
{
if (sysEvent == nullptr) {
return;
}
SGLOGD("Hiview OnEvent: %{public}s", sysEvent->AsJson().c_str());
SecEvent event;
if (!GetSecEvent(sysEvent, event)) {
SGLOGE("Unknown event");
return;
}
DatabaseManager::GetInstance().InsertEvent(HIVIEW_SOURCE, event);
}
void HiviewListener::OnServiceDied()
{
SGLOGI("Hiview service disconnect");
}
bool HiviewListener::GetSecEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent, SecEvent& event)
{
std::unordered_map<std::string, int64_t> domainName2Id = {
{"PASTEBOARD-USE_BEHAVIOUR", PASTEBOARD_EVENT_ID},
{"BUNDLE_MANAGER-BUNDLE_INSTALL", BUNDLE_INSTALL_EVENT_ID},
{"BUNDLE_MANAGER-BUNDLE_UPDATE", BUNDLE_UPDATE_EVENT_ID}
};
std::string domainName = sysEvent->GetDomain() + "-" + sysEvent->GetEventName();
if (domainName2Id.count(domainName) == 0) {
SGLOGE("The eventId is not applied for");
return false;
}
std::string eventJsonStr = sysEvent->AsJson();
if (eventJsonStr.empty() || !nlohmann::json::accept(eventJsonStr)) {
SGLOGE("eventJsonStr err");
return false;
}
nlohmann::json eventJson = nlohmann::json::parse(eventJsonStr);
if (eventJson.is_discarded()) {
SGLOGE("json err");
return false;
}
int64_t sysEventId = domainName2Id[domainName];
filterInstallOrUpdateContent(sysEventId, eventJson);
if (eventJson.dump().size() >= CONTENT_MAX_LEN) {
SGLOGE("The JSON length is too long.");
return false;
}
event = {
.eventId = sysEventId,
.version = "1.0",
.date = SecurityGuardUtils::GetDate(),
.content = eventJson.dump()
};
return true;
}
void HiviewListener::filterInstallOrUpdateContent(int64_t eventId, nlohmann::json& jsonObj)
{
if ((eventId != BUNDLE_INSTALL_EVENT_ID) && (eventId != BUNDLE_UPDATE_EVENT_ID)) {
return;
}
if (!filterHashValue(jsonObj)) {
return;
}
for (auto it = jsonObj.begin(); it != jsonObj.end();) {
if (HAP_INSTALL_UPDATE_STR.find(it.key()) == HAP_INSTALL_UPDATE_STR.end()) {
it = jsonObj.erase(it);
} else {
++it;
}
}
}
bool HiviewListener::filterHashValue(nlohmann::json& jsonObj)
{
if (jsonObj.contains("FILE_PATH") && jsonObj.contains("HASH_VALUE")) {
bool isFindHap = false;
size_t index = 0;
const auto& filePath = jsonObj["FILE_PATH"];
for (size_t i = 0; i < filePath.size(); i++) {
const std::string& path = filePath[i];
if (path.find(".hap") != std::string::npos) {
isFindHap = true;
index = i;
break;
}
}
if (!isFindHap || (jsonObj["HASH_VALUE"].size() <= index)) {
SGLOGE("Failed to find the hash value of hap");
return false;
}
jsonObj["HASH_VALUE"] = jsonObj["HASH_VALUE"][index];
}
return true;
}
} // OHOS::Security::SecurityGuard

View File

@ -1,39 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SECURITY_GUARD_HIVIEW_LISTENER_H
#define SECURITY_GUARD_HIVIEW_LISTENER_H
#include "hisysevent_listener.h"
#include "nlohmann/json.hpp"
#include "config_define.h"
namespace OHOS::Security::SecurityGuard {
class HiviewListener : public HiviewDFX::HiSysEventListener {
public:
HiviewListener() : HiSysEventListener() {}
virtual ~HiviewListener() {}
void OnEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent);
void OnServiceDied();
private:
bool GetSecEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent, SecEvent& event);
void filterInstallOrUpdateContent(int64_t eventId, nlohmann::json& jsonObj);
bool filterHashValue(nlohmann::json& jsonObj);
};
} // OHOS::Security::SecurityGuard
#endif // SECURITY_GUARD_HIVIEW_LISTENER_H

View File

@ -39,6 +39,6 @@ int32_t AcquireDataCallbackProxy::OnNotify(const SecurityCollector::Event &event
}
MessageOption option = { MessageOption::TF_SYNC };
return Remote()->SendRequest(CMD_DATA_SUBSCRIBE_CALLBACK, data, reply, option);
return remote->SendRequest(CMD_DATA_SUBSCRIBE_CALLBACK, data, reply, option);
}
}

Some files were not shown because too many files have changed in this diff Show More