diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1f7cd3c983eae56b15f2f1145ddf5ae3f1da311d --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,45 @@ +# 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. + +import("//build/ohos.gni") + +group("security_component_build_module") { + if (is_standard_system) { + deps = [ + "interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + "interfaces/inner_api/security_component:libsecurity_component_sdk", + "services/security_component_service/sa:security_component_service", + "services/security_component_service/sa/sa_profile:security_component_sa_profile_standard", + ] + } +} + +group("security_component_build_module_test") { + testonly = true + deps = [] + if (is_standard_system) { + deps += [ + "interfaces/inner_api/enhance_kits/test:unittest", + "interfaces/inner_api/security_component/test:unittest", + "services/security_component_service/sa/test:unittest", + ] + } +} + +group("security_component_build_fuzz_test") { + testonly = true + deps = [] + if (is_standard_system) { + deps += [ "test/fuzztest/security_component:fuzztest" ] + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4a459866a57c25462afad17f3fe0b50d440da080 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 5ce308bef2a03f37674bdcaefb3fa2a47acc8ef2..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# security_component - -null \ No newline at end of file diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..141edb1bece8abd4c986af7b010360f6e2d92dc4 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,47 @@ +# 安全控件管理服务 + +## 简介 + +安全控件是OpenHarmony提供的一组系统实现的ArkUI基础组件。当用户点击了这类组件后,应用将被授予临时授权,应用开发者仅需要像使用Button等组件那样集成到应用自己的页面即可。 +安全控件管理服务主要提供如下功能: + +- 提供应用安全控件的注册、临时授权、取消注册等Native接口实现。 +- 负责安全控件的合法性检查,只有合法的安全控件才能授权成功。 +- 提供其他SA查询临时授权的Native接口实现。提供安全增强相关接口及适配层,供厂商定制安全增强功能使用。 + +## 目录 + +``` +/base/security/security_component +├── frameworks # 框架层,基础功能代码存放目录 +│ ├── common # 框架公共代码存放目录 +│ ├── enhance_adapter # 能力增强适配代码存放目录 +│ └── security_component # 安全控件服务框架代码存放目录 +├── interfaces # 接口层 +│ └── inner_api # 内部接口层 +│ ├── enhance_kits # 安全控件配置接口代码存放目录 +│ └── security_component # 安全控件服务接口层代码存放目录 +└── services # 服务层 + └── security_component_service/sa + └── sa_main # 安全控件服务侧代码存放目录 + +``` + +## 使用 +### 接口说明 + +| **接口申明** | **接口描述** | +| --- | --- | +| int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId); | 注册安全控件 | +| int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo); | 更新安全控件信息 | +| int32_t UnregisterSecurityComponent(int32_t scId); | 取消注册安全控件 | +| int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, const SecCompClickEvent& touchInfo); | 上报点击事件,申请临时授权 | +| int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); | 设置安全控件增强的配置,供多模服务使用 | +| int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, uint8_t* enhanceData, uint32_t& enHancedataLen); | 获取点击事件的安全增强数据,供多模服务使用 | +| bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); | 校验后取消保存控件权限 | + +## 相关仓 + +**[arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine/blob/master/README_zh.md)** + +**[multimodalinput\_input](https://gitee.com/openharmony/multimodalinput_input/blob/master/README_zh.md)** diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..f9134f4ea7e0f1d30d59bd1757d789d68d15f111 --- /dev/null +++ b/bundle.json @@ -0,0 +1,106 @@ +{ + "name": "@openharmony/security_component", + "description": "security_component", + "version": "4.0.0", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "base/security/security_component" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "security_component", + "subsystem": "security", + "syscap": [], + "hisysevent_config": [ + "//base/security/security_component/hisysevent.yaml" + ], + "features": [ "security_component_feature_coverage = false" ], + "adapted_system_type": [ + "standard" + ], + "rom": "2048KB", + "ram": "5102KB", + "deps": { + "components": [ + "ability_base", + "ability_runtime", + "access_token", + "c_utils", + "eventhandler", + "hilog", + "hisysevent", + "hitrace", + "graphic_2d", + "ipc", + "safwk", + "samgr", + "window_manager" + ], + "third_party": [ + "cJSON", + "googletest" + ] + }, + "build": { + "sub_component": [ + "//base/security/security_component:security_component_build_module" + ], + "inner_kits": [ + { + "name": "//base/security/security_component/interfaces/inner_api/security_component:libsecurity_component_sdk", + "header": { + "header_files": [ + "i_sec_comp_probe.h", + "sec_comp_kit.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/security_component/include" + } + }, + { + "name": "//base/security/security_component/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + "header": { + "header_files": [ + "sec_comp_enhance_kit.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/enhance_kits/include" + } + }, + { + "name": "//base/security/security_component/frameworks:libsecurity_component_framework", + "header": { + "header_files": [ + "location_button.h", + "paste_button.h", + "save_button.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/security_component/include" + } + }, + { + "name": "//base/security/security_component/frameworks:libsecurity_component_enhance_adapter", + "header": { + "header_files": [ + "sec_comp_enhance_adapter.h" + ], + "header_base": "//base/security/security_component/frameworks/enhance_adapter/include" + } + }, + { + "name": "//base/security/security_component/services/security_component_service/sa:security_component_service", + "header": { + "header_files": [ + "sec_comp_manager.h" + ], + "header_base": "//base/security/security_component/services/security_component_service/sa/sa_main" + } + } + ], + "test": [ + "//base/security/security_component:security_component_build_module_test", + "//base/security/security_component:security_component_build_fuzz_test" + ] + } + } +} diff --git a/config/BUILD.gn b/config/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9cf755498a2f8653a6faf5b583296483493faf47 --- /dev/null +++ b/config/BUILD.gn @@ -0,0 +1,23 @@ +# 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. + +declare_args() { + security_component_feature_coverage = false +} + +config("coverage_flags") { + if (security_component_feature_coverage) { + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + } +} diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c0647d2d1af3beae7fb765ce5cb9496b492b50b9 --- /dev/null +++ b/frameworks/BUILD.gn @@ -0,0 +1,94 @@ +# 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. + +import("//build/ohos.gni") + +sec_comp_root_dir = ".." + +config("libsecurity_component_framework_config") { + include_dirs = [ + "common/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] +} + +ohos_shared_library("libsecurity_component_framework") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_framework" + + include_dirs = [ + "common/include", + "security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + ] + + sources = [ + "common/src/sec_comp_tool.cpp", + "security_component/src/location_button.cpp", + "security_component/src/paste_button.cpp", + "security_component/src/save_button.cpp", + "security_component/src/sec_comp_base.cpp", + "security_component/src/sec_comp_click_event_parcel.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":libsecurity_component_framework_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} + +config("libsecurity_component_enhance_adapter_config") { + include_dirs = [ + "common/include", + "enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + ] +} + +ohos_shared_library("libsecurity_component_enhance_adapter") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_enhance_adapter" + + include_dirs = [ + "common/include", + "enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + ] + + sources = [ "enhance_adapter/src/sec_comp_enhance_adapter.cpp" ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":libsecurity_component_enhance_adapter_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + if (current_cpu == "arm64") { + defines = [ "_ARM64_" ] + } +} diff --git a/frameworks/common/include/sec_comp_err.h b/frameworks/common/include/sec_comp_err.h new file mode 100644 index 0000000000000000000000000000000000000000..8cacb68c3e7bc94f9d77bf292a238885ba056370 --- /dev/null +++ b/frameworks/common/include/sec_comp_err.h @@ -0,0 +1,54 @@ +/* + * 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 FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H +#define FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum SCErrCode : int32_t { + SC_OK = 0, + + SC_SERVICE_ERROR_VALUE_INVALID = -50, + SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL = -51, + SC_SERVICE_ERROR_MEMORY_OPERATE_FAIL = -52, + SC_SERVICE_ERROR_IPC_REQUEST_FAIL = -54, + SC_SERVICE_ERROR_SERVICE_NOT_EXIST = -55, + SC_SERVICE_ERROR_COMPONENT_INFO_INVALID = -56, + SC_SERVICE_ERROR_COMPONENT_RECT_OVERLAP = -57, + SC_SERVICE_ERROR_COMPONENT_NOT_EXIST = -58, + SC_SERVICE_ERROR_PERMISSION_OPER_FAIL = -59, + SC_SERVICE_ERROR_CLICK_EVENT_INVALID = -60, + SC_SERVICE_ERROR_COMPONENT_INFO_NOT_EQUAL = -61, + SC_SERVICE_ERROR_CALLER_INVALID = -62, + + SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE = -100, + SC_ENHANCE_ERROR_VALUE_INVALID = -101, + SC_ENHANCE_ERROR_OPER_FAIL = -102, + SC_ENHANCE_ERROR_CALLBACK_REDIRECT = -103, + SC_ENHANCE_ERROR_CALLBACK_REGIST_FAIL = -104, + SC_ENHANCE_ERROR_CALLBACK_HAS_EXIST = -105, + SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST = -106, + SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL = -107, + SC_ENHANCE_ERROR_CALLBACK_CHECK_FAIL = -108, + SC_ENHANCE_ERROR_IN_MALICIOUS_LIST = -109, + SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL = -110 +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H diff --git a/frameworks/common/include/sec_comp_log.h b/frameworks/common/include/sec_comp_log.h new file mode 100644 index 0000000000000000000000000000000000000000..71ab8015292daf7f0c2ffee056c31b11b4818f0b --- /dev/null +++ b/frameworks/common/include/sec_comp_log.h @@ -0,0 +1,62 @@ +/* + * 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_COMPONENT_LOG_H +#define SECURITY_COMPONENT_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#ifndef __cplusplus + +#undef LOG_DOMAIN +#define LOG_DOMAIN 0xD002F07 + +#define SC_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#else + +static constexpr unsigned int SECURITY_DOMAIN_SECURITY_COMPONENT = 0xD002F07; + +#define SC_LOG_DEBUG(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Debug(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(label, fmt, ...) OHOS::HiviewDFX::HiLog::Info(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(label, fmt, ...) OHOS::HiviewDFX::HiLog::Warn(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Error(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Fatal(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#endif // __cplusplus + +#else + +#include + +#undef LOG_TAG + +#define SC_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // SECURITY_COMPONENT_LOG_H diff --git a/frameworks/common/include/sec_comp_tool.h b/frameworks/common/include/sec_comp_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..197f67d529f7d0d79e8eeb900524610e49e9d210 --- /dev/null +++ b/frameworks/common/include/sec_comp_tool.h @@ -0,0 +1,28 @@ +/* + * 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_COMPONENT_TOOL_H +#define SECURITY_COMPONENT_TOOL_H + +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { + bool IsColorSimilar(const SecCompColor& color1, const SecCompColor& color2); + bool IsColorTransparent(const SecCompColor& color); +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_TOOL_H diff --git a/frameworks/common/src/sec_comp_tool.cpp b/frameworks/common/src/sec_comp_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36d45c48948721d9a33807f34c346408f4cd7683 --- /dev/null +++ b/frameworks/common/src/sec_comp_tool.cpp @@ -0,0 +1,142 @@ +/* + * 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 "sec_comp_tool.h" + +#include +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr double PI_CIRCLE = 3.1415926; +static constexpr double MIN_HSV_DISTANCE = 25.0; +static constexpr double MAX_RGB_VALUE = 255.0; +static constexpr uint8_t MAX_TRANSPARENT = 0x99; // 60% +static constexpr double ZERO_DOUBLE = 0.0; +static constexpr double THIRTY_ANGLE = 30.0; +static constexpr double SIXTY_ANGLE = 60.0; +static constexpr double ONE_HUNDRED_TWEENTY_ANGLE = 120.0; +static constexpr double ONE_HUNDRED_EIGHTY_ANGLE = 180.0; +static constexpr double TWO_HUNDREDS_FORTY_ANGLE = 240.0; +static constexpr double THREE_HUNDREDS_SIXTY_ANGLE = 360.0; +static constexpr double DEFAULT_R = 100.0; + +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompTool"}; +} + +static inline double MaxValue(double a, double b, double c) +{ + return ((a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c)); +} + +static inline double MinValue(double a, double b, double c) +{ + return ((a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c)); +} + +struct HsvColor { + double h; + double s; + double v; +}; + +static HsvColor RgbToHsv(uint8_t r, uint8_t g, uint8_t b) +{ + HsvColor hsv; + double red = static_cast(r) / MAX_RGB_VALUE; + double green = static_cast(g) / MAX_RGB_VALUE; + double blue = static_cast(b) / MAX_RGB_VALUE; + double max = MaxValue(red, green, blue); + double min = MinValue(red, green, blue); + double delta = max - min; + if (max == min) { + hsv.h = ZERO_DOUBLE; + } else if (max == red) { + hsv.h = fmod((SIXTY_ANGLE * ((green - blue) / delta) + THREE_HUNDREDS_SIXTY_ANGLE), + THREE_HUNDREDS_SIXTY_ANGLE); + } else if (max == green) { + hsv.h = fmod((SIXTY_ANGLE * ((blue - red) / delta) + ONE_HUNDRED_TWEENTY_ANGLE), THREE_HUNDREDS_SIXTY_ANGLE); + } else if (max == blue) { + hsv.h = fmod((SIXTY_ANGLE * ((red - green) / delta) + TWO_HUNDREDS_FORTY_ANGLE), THREE_HUNDREDS_SIXTY_ANGLE); + } + + if (max == 0) { + hsv.s = ZERO_DOUBLE; + } else { + hsv.s = delta / max; + } + + hsv.v = max; + return hsv; +} + +static inline double GetHsvDisX(const HsvColor& hsv, double r) +{ + return r * hsv.v * hsv.s * cos(hsv.h / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); +} + +static inline double GetHsvDisY(const HsvColor& hsv, double r) +{ + return r * hsv.v * hsv.s * sin(hsv.h / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); +} + +static inline double GetHsvDisZ(const HsvColor& hsv, double h) +{ + return h * (1 - hsv.v); +} + +static double HsvDistance(const HsvColor& hsv1, const HsvColor& hsv2) +{ + double rDef = DEFAULT_R; + double angle = THIRTY_ANGLE; + double h = rDef * cos(angle / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); + double r = rDef * sin(angle / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); + + double x1 = GetHsvDisX(hsv1, r); + double y1 = GetHsvDisY(hsv1, r); + double z1 = GetHsvDisZ(hsv1, h); + + double x2 = GetHsvDisX(hsv2, r); + double y2 = GetHsvDisY(hsv2, r); + double z2 = GetHsvDisZ(hsv2, h); + + double dx = x1 - x2; + double dy = y1 - y2; + double dz = z1 - z2; + + return sqrt((dx * dx) + (dy * dy) + (dz * dz)); +} + +bool IsColorSimilar(const SecCompColor& color1, const SecCompColor& color2) +{ + HsvColor hsv1 = RgbToHsv(color1.argb.red, color1.argb.green, color1.argb.blue); + HsvColor hsv2 = RgbToHsv(color2.argb.red, color2.argb.green, color2.argb.blue); + + double distance = HsvDistance(hsv1, hsv2); + SC_LOG_DEBUG(LABEL, "Compare color %{public}x %{public}x distance %{public}f", + color1.value, color2.value, distance); + return (distance < MIN_HSV_DISTANCE); +} + +bool IsColorTransparent(const SecCompColor& color) +{ + SC_LOG_DEBUG(LABEL, "Color %{public}x alpha %{public}x", color.value, color.argb.alpha); + return color.argb.alpha < MAX_TRANSPARENT; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h b/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..faada7e763671088f8072a19ca6852b19ae9b2a5 --- /dev/null +++ b/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h @@ -0,0 +1,122 @@ +/* + * 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_COMPONENT_ENHANCE_ADAPTER_H +#define SECURITY_COMPONENT_ENHANCE_ADAPTER_H + +#include +#include "iremote_object.h" +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum EnhanceInterfaceType { + SEC_COMP_ENHANCE_INPUT_INTERFACE = 0, + SEC_COMP_ENHANCE_SRV_INTERFACE = 1, + SEC_COMP_ENHANCE_CLIENT_INTERFACE = 2, +}; + +// for multimodalinput to add enhance data to PointerEvent +class SecCompInputEnhanceInterface { +public: + // for multimodalinput to set enhance cfg which is from security component enhance service + virtual int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) = 0; + + // for multimodalinput to get enhance data + virtual int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) = 0; +}; + +// for security component service to send command to enhance service +class SecCompSrvEnhanceInterface { + public: + // enable input enhance, then enhance service send config to multimodalinput + virtual int32_t EnableInputEnhance() = 0; + + // disable input enhance + virtual int32_t DisableInputEnhance() = 0; + + // send click event to enhance service for checking extra data validity + virtual int32_t CheckExtraInfo(const SecCompClickEvent& touchInfo) = 0; + + // send component info to enhance service for checking its validity + virtual int32_t CheckComponentInfoEnhnace(int32_t pid, std::shared_ptr& compInfo, + const nlohmann::json& jsonComponent) = 0; + + // get RemoteObject of enhance service to connect it + virtual sptr GetEnhanceRemoteObject() = 0; + + // start enhance service + virtual void StartEnhanceService() = 0; + + // exit enhance service + virtual void ExitEnhanceService() = 0; + + // notify process died + virtual void NotifyProcessDied(int32_t pid) = 0; +}; + +// for client +class SecCompClientEnhanceInterface { +public: + // preprocess component info which is send to security component service, e.g. RegisterSecurityComponent + virtual bool EnhanceDataPreprocess(const uintptr_t caller, std::string& componentInfo) = 0; + virtual bool EnhanceDataPreprocess(const uintptr_t caller, int32_t scId, std::string& componentInfo) = 0; + + // regiter scid to enhance client + virtual void RegisterScIdEnhance(const uintptr_t caller, int32_t scId) = 0; + // unregiter scid to enhance client + virtual void UnregisterScIdEnhance(const uintptr_t caller, int32_t scId) = 0; +}; + +class SecCompEnhanceAdapter final { +public: + static void InitEnhanceHandler(EnhanceInterfaceType type); + static int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); + static int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen); + + static int32_t CheckExtraInfo(const SecCompClickEvent& touchInfo); + static int32_t EnableInputEnhance(); + static int32_t DisableInputEnhance(); + static int32_t CheckComponentInfoEnhnace(int32_t pid, std::shared_ptr& compInfo, + const nlohmann::json& jsonComponent); + static sptr GetEnhanceRemoteObject(); + static void StartEnhanceService(); + static void ExistEnhanceService(); + static void NotifyProcessDied(int32_t pid); + + static bool EnhanceDataPreprocess(std::string& componentInfo); + static bool EnhanceDataPreprocess(int32_t scId, std::string& componentInfo); + static void RegisterScIdEnhance(int32_t scId); + static void UnregisterScIdEnhance(int32_t scId); + + static SecCompInputEnhanceInterface* inputHandler; + static bool isEnhanceInputHandlerInit; + + static SecCompSrvEnhanceInterface* srvHandler; + static bool isEnhanceSrvHandlerInit; + + static SecCompClientEnhanceInterface* clientHandler; + static bool isEnhanceClientHandlerInit; + + static std::mutex initMtx; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_ADAPTER_H diff --git a/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp b/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28d1aa9390c46972aa4dc866033be6b073806081 --- /dev/null +++ b/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp @@ -0,0 +1,235 @@ +/* + * 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 "sec_comp_enhance_adapter.h" + +#include +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEnhanceAdapter"}; + +#ifdef _ARM64_ +static const std::string LIB_PATH = "/system/lib64/"; +#else +static const std::string LIB_PATH = "/system/lib/"; +#endif +static const std::string ENHANCE_INPUT_INTERFACE_LIB = LIB_PATH + "libsec_comp_input_enhance.z.so"; +static const std::string ENHANCE_SRV_INTERFACE_LIB = LIB_PATH + "libsec_comp_service_enhance.z.so"; +static const std::string ENHANCE_CLIENT_INTERFACE_LIB = LIB_PATH + "libsec_comp_client_enhance.z.so"; +} + +SecCompInputEnhanceInterface* SecCompEnhanceAdapter::inputHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceInputHandlerInit = false; + +SecCompSrvEnhanceInterface* SecCompEnhanceAdapter::srvHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceSrvHandlerInit = false; + +SecCompClientEnhanceInterface* SecCompEnhanceAdapter::clientHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceClientHandlerInit = false; + +std::mutex SecCompEnhanceAdapter::initMtx; + +void SecCompEnhanceAdapter::InitEnhanceHandler(EnhanceInterfaceType type) +{ + std::unique_lock lck(initMtx); + std::string libPath = ""; + switch (type) { + case SEC_COMP_ENHANCE_INPUT_INTERFACE: + libPath = ENHANCE_INPUT_INTERFACE_LIB; + isEnhanceInputHandlerInit = true; + break; + case SEC_COMP_ENHANCE_SRV_INTERFACE: + libPath = ENHANCE_SRV_INTERFACE_LIB; + isEnhanceSrvHandlerInit = true; + break; + case SEC_COMP_ENHANCE_CLIENT_INTERFACE: + libPath = ENHANCE_CLIENT_INTERFACE_LIB; + isEnhanceClientHandlerInit = true; + break; + default: + break; + } + if (dlopen(libPath.c_str(), RTLD_LAZY) == nullptr) { + SC_LOG_ERROR(LABEL, "init enhance lib %{public}s failed, error %{public}s", libPath.c_str(), dlerror()); + } +} + +int32_t SecCompEnhanceAdapter::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + if (!isEnhanceInputHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_INPUT_INTERFACE); + } + if (inputHandler != nullptr) { + return inputHandler->SetEnhanceCfg(cfg, cfgLen); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + if (!isEnhanceInputHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_INPUT_INTERFACE); + } + if (inputHandler != nullptr) { + return inputHandler->GetPointerEventEnhanceData(data, dataLen, enhanceData, enHancedataLen); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::CheckExtraInfo(const SecCompClickEvent& touchInfo) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->CheckExtraInfo(touchInfo); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(std::string& componentInfo) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + return clientHandler->EnhanceDataPreprocess(enhanceCallerAddr, componentInfo); + } + return true; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(int32_t scId, std::string& componentInfo) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + return clientHandler->EnhanceDataPreprocess(enhanceCallerAddr, scId, componentInfo); + } + return true; +} + +void SecCompEnhanceAdapter::RegisterScIdEnhance(int32_t scId) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + clientHandler->RegisterScIdEnhance(enhanceCallerAddr, scId); + } +} + +void SecCompEnhanceAdapter::UnregisterScIdEnhance(int32_t scId) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + clientHandler->UnregisterScIdEnhance(enhanceCallerAddr, scId); + } +} + +int32_t SecCompEnhanceAdapter::EnableInputEnhance() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->EnableInputEnhance(); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::DisableInputEnhance() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->DisableInputEnhance(); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +void SecCompEnhanceAdapter::StartEnhanceService() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->StartEnhanceService(); + } +} + +void SecCompEnhanceAdapter::ExistEnhanceService() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->ExitEnhanceService(); + } +} + +void SecCompEnhanceAdapter::NotifyProcessDied(int32_t pid) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->NotifyProcessDied(pid); + } +} + +int32_t SecCompEnhanceAdapter::CheckComponentInfoEnhnace(int32_t pid, + std::shared_ptr& compInfo, const nlohmann::json& jsonComponent) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->CheckComponentInfoEnhnace(pid, compInfo, jsonComponent); + } + return SC_OK; +} + +sptr SecCompEnhanceAdapter::GetEnhanceRemoteObject() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + auto service = srvHandler->GetEnhanceRemoteObject(); + return service; + } + return nullptr; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/include/sec_comp_click_event_parcel.h b/frameworks/security_component/include/sec_comp_click_event_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..ea39a20663e668fe1b64fc9971ced8b482546a59 --- /dev/null +++ b/frameworks/security_component/include/sec_comp_click_event_parcel.h @@ -0,0 +1,38 @@ +/* + * 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_COMPONENT_CLICK_INFO_PARCEL_H +#define SECURITY_COMPONENT_CLICK_INFO_PARCEL_H + +#include "parcel.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompClickEventParcel final : public Parcelable { + SecCompClickEventParcel() = default; + + ~SecCompClickEventParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static SecCompClickEventParcel* Unmarshalling(Parcel& in); + + SecCompClickEvent touchInfoParams_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_CLICK_INFO_PARCEL_H diff --git a/frameworks/security_component/src/location_button.cpp b/frameworks/security_component/src/location_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b62b9e9780b262a0841ab1c1a85f5cf90ae1e7d6 --- /dev/null +++ b/frameworks/security_component/src/location_button.cpp @@ -0,0 +1,53 @@ +/* + * 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 "location_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "LocationButton"}; +} + +bool LocationButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= LocationDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= LocationIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool LocationButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + LocationButton* otherLocationButton = reinterpret_cast(other); + if (otherLocationButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not location button."); + return false; + } + return (icon_ == otherLocationButton->icon_) && (text_ == otherLocationButton->text_) && + (bg_ == otherLocationButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/paste_button.cpp b/frameworks/security_component/src/paste_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41941dc73233d2f6bb7c7eb6e004a580fdd917e0 --- /dev/null +++ b/frameworks/security_component/src/paste_button.cpp @@ -0,0 +1,53 @@ +/* + * 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 "paste_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "PasteButton"}; +} + +bool PasteButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= PasteDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= PasteIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool PasteButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + PasteButton* otherPasteButton = reinterpret_cast(other); + if (otherPasteButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not paste button."); + return false; + } + return (icon_ == otherPasteButton->icon_) && (text_ == otherPasteButton->text_) && + (bg_ == otherPasteButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/save_button.cpp b/frameworks/security_component/src/save_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22fc45c2167b9c8b9d74f0ef638236258d489bd2 --- /dev/null +++ b/frameworks/security_component/src/save_button.cpp @@ -0,0 +1,53 @@ +/* + * 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 "save_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SaveButton"}; +} + +bool SaveButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= SaveDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= SaveIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool SaveButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + SaveButton* otherSaveButton = reinterpret_cast(other); + if (otherSaveButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not save button."); + return false; + } + return (icon_ == otherSaveButton->icon_) && (text_ == otherSaveButton->text_) && + (bg_ == otherSaveButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/sec_comp_base.cpp b/frameworks/security_component/src/sec_comp_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c12e77ac6112fcebd5aa114f770b6cd752f6f7a --- /dev/null +++ b/frameworks/security_component/src/sec_comp_base.cpp @@ -0,0 +1,369 @@ +/* + * 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 "sec_comp_base.h" + +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompBase"}; +} + +const std::string JsonTagConstants::JSON_RECT = "rect"; +const std::string JsonTagConstants::JSON_SC_TYPE = "type"; +const std::string JsonTagConstants::JSON_NODE_ID = "nodeId"; +const std::string JsonTagConstants::JSON_RECT_X = "x"; +const std::string JsonTagConstants::JSON_RECT_Y = "y"; +const std::string JsonTagConstants::JSON_RECT_WIDTH = "width"; +const std::string JsonTagConstants::JSON_RECT_HEIGHT = "height"; +const std::string JsonTagConstants::JSON_WINDOW_RECT = "windowRect"; +const std::string JsonTagConstants::JSON_SIZE_TAG = "size"; +const std::string JsonTagConstants::JSON_FONT_SIZE_TAG = "fontSize"; +const std::string JsonTagConstants::JSON_ICON_SIZE_TAG = "iconSize"; +const std::string JsonTagConstants::JSON_PADDING_SIZE_TAG = "paddingSize"; +const std::string JsonTagConstants::JSON_PADDING_LEFT_TAG = "left"; +const std::string JsonTagConstants::JSON_PADDING_TOP_TAG = "top"; +const std::string JsonTagConstants::JSON_PADDING_RIGHT_TAG = "right"; +const std::string JsonTagConstants::JSON_PADDING_BOTTOM_TAG = "bottom"; +const std::string JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG = "textIconSpace"; +const std::string JsonTagConstants::JSON_RECT_WIDTH_TAG = "width"; +const std::string JsonTagConstants::JSON_RECT_HEIGHT_TAG = "height"; +const std::string JsonTagConstants::JSON_COLORS_TAG = "colors"; +const std::string JsonTagConstants::JSON_FONT_COLOR_TAG = "fontColor"; +const std::string JsonTagConstants::JSON_ICON_COLOR_TAG = "iconColor"; +const std::string JsonTagConstants::JSON_BG_COLOR_TAG = "bgColor"; +const std::string JsonTagConstants::JSON_BORDER_TAG = "border"; +const std::string JsonTagConstants::JSON_BORDER_WIDTH_TAG = "borderWidth"; +const std::string JsonTagConstants::JSON_PARENT_TAG = "parent"; +const std::string JsonTagConstants::JSON_PARENT_EFFECT_TAG = "parentEffect"; +const std::string JsonTagConstants::JSON_STYLE_TAG = "style"; +const std::string JsonTagConstants::JSON_TEXT_TAG = "text"; +const std::string JsonTagConstants::JSON_ICON_TAG = "icon"; +const std::string JsonTagConstants::JSON_BG_TAG = "bg"; + +bool SecCompBase::ParseDimension(const nlohmann::json& json, const std::string& tag, DimensionT& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_number_float()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParseColor(const nlohmann::json& json, const std::string& tag, SecCompColor& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res.value = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParseBool(const nlohmann::json& json, const std::string& tag, bool& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_boolean()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParsePadding(const nlohmann::json& json, const std::string& tag, PaddingSize& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonPadding = json.at(tag); + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_TOP_TAG, res.top)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_RIGHT_TAG, res.right)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_BOTTOM_TAG, res.bottom)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_LEFT_TAG, res.left)) { + return false; + } + return true; +} + +bool SecCompBase::ParseColors(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonColors = json.at(tag); + if (!ParseColor(jsonColors, JsonTagConstants::JSON_FONT_COLOR_TAG, fontColor_)) { + return false; + } + if (!ParseColor(jsonColors, JsonTagConstants::JSON_ICON_COLOR_TAG, iconColor_)) { + return false; + } + if (!ParseColor(jsonColors, JsonTagConstants::JSON_BG_COLOR_TAG, bgColor_)) { + return false; + } + return true; +} + +bool SecCompBase::ParseBorders(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonBorder = json.at(tag); + return ParseDimension(jsonBorder, JsonTagConstants::JSON_BORDER_WIDTH_TAG, borderWidth_); +} + +bool SecCompBase::ParseSize(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonSize = json.at(tag); + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_FONT_SIZE_TAG, fontSize_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_ICON_SIZE_TAG, iconSize_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, textIconSpace_)) { + return false; + } + + if (!ParsePadding(jsonSize, JsonTagConstants::JSON_PADDING_SIZE_TAG, padding_)) { + return false; + } + + return true; +} + +bool SecCompBase::ParseParent(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonParent = json.at(tag); + return ParseBool(jsonParent, JsonTagConstants::JSON_PARENT_EFFECT_TAG, parentEffect_); +} + +bool SecCompBase::ParseRect(const nlohmann::json& json, const std::string& tag, SecCompRect& rect) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonSize = json.at(tag); + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_X, rect.x_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_Y, rect.y_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_WIDTH, rect.width_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_HEIGHT, rect.height_)) { + return false; + } + + return true; +} + +bool SecCompBase::FromJson(const nlohmann::json& jsonSrc) +{ + SC_LOG_DEBUG(LABEL, "Button info %{public}s.", jsonSrc.dump().c_str()); + if ((jsonSrc.find(JsonTagConstants::JSON_SC_TYPE) == jsonSrc.end()) || + !jsonSrc.at(JsonTagConstants::JSON_SC_TYPE).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", JsonTagConstants::JSON_SC_TYPE.c_str()); + return false; + } + int32_t value = jsonSrc.at(JsonTagConstants::JSON_SC_TYPE).get(); + if ((value <= static_cast(SecCompType::UNKNOWN_SC_TYPE)) || + (value >= static_cast(SecCompType::MAX_SC_TYPE))) { + SC_LOG_ERROR(LABEL, "scType is invalid."); + return false; + } + type_ = static_cast(value); + + if ((jsonSrc.find(JsonTagConstants::JSON_NODE_ID) == jsonSrc.end()) || + !jsonSrc.at(JsonTagConstants::JSON_NODE_ID).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", JsonTagConstants::JSON_NODE_ID.c_str()); + return false; + } + nodeId_ = jsonSrc.at(JsonTagConstants::JSON_NODE_ID).get(); + + if (!ParseRect(jsonSrc, JsonTagConstants::JSON_RECT, rect_)) { + return false; + } + if (!ParseRect(jsonSrc, JsonTagConstants::JSON_WINDOW_RECT, windowRect_)) { + return false; + } + if (!ParseSize(jsonSrc, JsonTagConstants::JSON_SIZE_TAG)) { + return false; + } + if (!ParseColors(jsonSrc, JsonTagConstants::JSON_COLORS_TAG)) { + return false; + } + if (!ParseBorders(jsonSrc, JsonTagConstants::JSON_BORDER_TAG)) { + return false; + } + if (!ParseParent(jsonSrc, JsonTagConstants::JSON_PARENT_TAG)) { + return false; + } + if (!ParseStyle(jsonSrc, JsonTagConstants::JSON_STYLE_TAG)) { + return false; + } + + return true; +} + +void SecCompBase::ToJson(nlohmann::json& jsonRes) const +{ + jsonRes[JsonTagConstants::JSON_SC_TYPE] = type_; + jsonRes[JsonTagConstants::JSON_NODE_ID] = nodeId_; + jsonRes[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, rect_.x_}, + {JsonTagConstants::JSON_RECT_Y, rect_.y_}, + {JsonTagConstants::JSON_RECT_WIDTH, rect_.width_}, + {JsonTagConstants::JSON_RECT_HEIGHT, rect_.height_} + }; + jsonRes[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, windowRect_.x_}, + {JsonTagConstants::JSON_RECT_Y, windowRect_.y_}, + {JsonTagConstants::JSON_RECT_WIDTH, windowRect_.width_}, + {JsonTagConstants::JSON_RECT_HEIGHT, windowRect_.height_} + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, padding_.top }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, padding_.right }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, padding_.bottom }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, padding_.left }, + }; + + jsonRes[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, fontSize_ }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, iconSize_ }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, textIconSpace_ }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonRes[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, fontColor_.value }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, iconColor_.value }, + { JsonTagConstants::JSON_BG_COLOR_TAG, bgColor_.value } + }; + + jsonRes[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, borderWidth_ }, + }; + jsonRes[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, parentEffect_ }, + }; + + jsonRes[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, text_ }, + { JsonTagConstants::JSON_ICON_TAG, icon_ }, + { JsonTagConstants::JSON_BG_TAG, bg_ }, + }; +} + +std::string SecCompBase::ToJsonStr() const +{ + nlohmann::json json; + ToJson(json); + return json.dump(); +} + +bool SecCompBase::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (other == nullptr) { + SC_LOG_ERROR(LABEL, "other is nullptr."); + return false; + } + + SecCompRect rect = other->rect_; + SecCompRect windowRect = other->windowRect_; + if (isRectCheck) { + rect = rect_; + windowRect = windowRect_; + } + + auto leftValue = std::tie(type_, fontSize_, iconSize_, textIconSpace_, padding_.top, padding_.right, + padding_.bottom, padding_.left, fontColor_.value, bgColor_.value, iconColor_.value, borderWidth_, + rect, windowRect); + auto rightValue = std::tie(other->type_, other->fontSize_, other->iconSize_, other->textIconSpace_, + other->padding_.top, other->padding_.right, other->padding_.bottom, other->padding_.left, + other->fontColor_.value, other->bgColor_.value, other->iconColor_.value, other->borderWidth_, + other->rect_, other->windowRect_); + + return (leftValue == rightValue); +} + +bool SecCompBase::ParseStyle(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonStyle = json.at(tag); + if (!(jsonStyle.at(JsonTagConstants::JSON_TEXT_TAG).is_number() && + jsonStyle.at(JsonTagConstants::JSON_ICON_TAG).is_number() && + jsonStyle.at(JsonTagConstants::JSON_BG_TAG).is_number())) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + text_ = jsonStyle.at(JsonTagConstants::JSON_TEXT_TAG).get(); + icon_ = jsonStyle.at(JsonTagConstants::JSON_ICON_TAG).get(); + if (!IsParamValid()) { + SC_LOG_ERROR(LABEL, "text or icon is invalid."); + return false; + } + + bg_ = static_cast(jsonStyle.at(JsonTagConstants::JSON_BG_TAG).get()); + if ((bg_ <= SecCompBackground::UNKNOWN_BG) || (bg_ >= SecCompBackground::MAX_BG_TYPE)) { + SC_LOG_ERROR(LABEL, "bg is invalid."); + return false; + } + + return true; +} +} // namespace base +} // namespace Security +} // namespace OHOS + diff --git a/frameworks/security_component/src/sec_comp_click_event_parcel.cpp b/frameworks/security_component/src/sec_comp_click_event_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55390c9cb2015c56239e4b05757b37c0f8b498ab --- /dev/null +++ b/frameworks/security_component/src/sec_comp_click_event_parcel.cpp @@ -0,0 +1,102 @@ +/* + * 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 "sec_comp_click_event_parcel.h" + +#include "sec_comp_log.h" +#include "securec.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClickEventParcel"}; +} + +bool SecCompClickEventParcel::Marshalling(Parcel& out) const +{ + if (!(out.WriteDouble(this->touchInfoParams_.touchX)) || !(out.WriteDouble(this->touchInfoParams_.touchY))) { + SC_LOG_ERROR(LABEL, "Write touch xy pointer fail"); + return false; + } + + if (!(out.WriteUint64(this->touchInfoParams_.timestamp))) { + SC_LOG_ERROR(LABEL, "Write touch timestamp fail"); + return false; + } + + if (!(out.WriteUint32(this->touchInfoParams_.extraInfo.dataSize))) { + SC_LOG_ERROR(LABEL, "Write extraInfo dataSize fail"); + return false; + } + + if (this->touchInfoParams_.extraInfo.dataSize != 0 && + !(out.WriteBuffer(this->touchInfoParams_.extraInfo.data, this->touchInfoParams_.extraInfo.dataSize))) { + SC_LOG_ERROR(LABEL, "Write touch extraInfo data fail"); + return false; + } + + return true; +} + +SecCompClickEventParcel* SecCompClickEventParcel::Unmarshalling(Parcel& in) +{ + SecCompClickEventParcel* touchInfoParcel = new (std::nothrow) SecCompClickEventParcel(); + if (touchInfoParcel == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc policy parcel fail"); + return nullptr; + } + + SecCompClickEvent touchInfo; + if (!in.ReadDouble(touchInfo.touchX) || !in.ReadDouble(touchInfo.touchY)) { + SC_LOG_ERROR(LABEL, "Read touch xy porinter fail"); + delete touchInfoParcel; + return nullptr; + } + + if (!in.ReadUint64(touchInfo.timestamp)) { + SC_LOG_ERROR(LABEL, "Read timestamp fail"); + delete touchInfoParcel; + return nullptr; + } + + if (!in.ReadUint32(touchInfo.extraInfo.dataSize)) { + SC_LOG_ERROR(LABEL, "Read extraInfo data size fail"); + delete touchInfoParcel; + return nullptr; + } + + if (touchInfo.extraInfo.dataSize == 0) { + touchInfoParcel->touchInfoParams_ = touchInfo; + return touchInfoParcel; + } else if (touchInfo.extraInfo.dataSize > MAX_EXTRA_SIZE) { + SC_LOG_ERROR(LABEL, "Read extraInfo data size invalid"); + delete touchInfoParcel; + return nullptr; + } + + touchInfo.extraInfo.data = const_cast(in.ReadBuffer(touchInfo.extraInfo.dataSize)); + if (touchInfo.extraInfo.data == nullptr) { + SC_LOG_ERROR(LABEL, "Read extraInfo data failed"); + delete touchInfoParcel; + return nullptr; + } + + touchInfoParcel->touchInfoParams_ = touchInfo; + return touchInfoParcel; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/hisysevent.yaml b/hisysevent.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51ab79c24090920aff499264d6b30b0000427f43 --- /dev/null +++ b/hisysevent.yaml @@ -0,0 +1,94 @@ +# 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. + +domain: SEC_COMPONENT + +CALLBACK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to execute the callback} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + REASON: {type: STRING, desc: callback execution failure cause} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +CALLER_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Illegal invocation} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + +CHALLENGE_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Challenge value verification failed} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +CLICK_INFO_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to verify the click event} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +COMPONENT_INFO_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to verify the component information} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +INIT_FAILED: + __BASE: {type: FAULT, level: CRITICAL, desc: Failed to initialize the security component environment} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + REASON: {type: STRING, desc: callback execution failure cause} + +REGISTER_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: The security component is registered successfully} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +REPEAT_CALLBACK_REGISTER: + __BASE: {type: SECURITY, level: CRITICAL, desc: Repeated registration callback} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + +SERVICE_INIT_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component service starts successfully} + PID: {type: INT32, desc: pid of the service process} + +TEMP_GRANT_FAILED: + __BASE: {type: FAULT, level: CRITICAL, desc: Security component authorization failed} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +TEMP_GRANT_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component authorization successfully} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +UNREGISTER_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component unregister} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} diff --git a/interfaces/inner_api/enhance_kits/BUILD.gn b/interfaces/inner_api/enhance_kits/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4acbcce2de99b03ec301837e608eb975f7c4006c --- /dev/null +++ b/interfaces/inner_api/enhance_kits/BUILD.gn @@ -0,0 +1,55 @@ +# 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. + +import("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("sec_comp_enhance_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + ] +} + +ohos_shared_library("libsecurity_component_enhance_sdk") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_enhance_sdk" + + public_configs = [ ":sec_comp_enhance_config" ] + + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + ] + + sources = [ "src/sec_comp_enhance_kit.cpp" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..11f46ee7cb036d82c5ce9d06dbf6d91f1895a92b --- /dev/null +++ b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h @@ -0,0 +1,32 @@ +/* + * 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_COMPONENT_ENHANCE_KITS_H +#define SECURITY_COMPONENT_ENHANCE_KITS_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompEnhanceKit { + static void InitClientEnhance(); + static int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); + static int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_KITS_H diff --git a/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h new file mode 100644 index 0000000000000000000000000000000000000000..c7e0c6f15599f9156492edd8290e5984110cf9e8 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h @@ -0,0 +1,21 @@ +/* + * 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_COMPONENT_ENHANCE_KIT_C_H +#define SECURITY_COMPONENT_ENHANCE_KIT_C_H + +void InitSecCompClientEnhance(void); + +#endif // SECURITY_COMPONENT_ENHANCE_KIT_C_H + diff --git a/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp b/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b16511ce6ffab9e6aea282a579d013c4ac70186 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp @@ -0,0 +1,45 @@ +/* + * 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 "sec_comp_enhance_kit.h" + +#include "sec_comp_enhance_adapter.h" + +extern "C" void InitSecCompClientEnhance() +{ + OHOS::Security::SecurityComponent::SecCompEnhanceKit::InitClientEnhance(); +} + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void SecCompEnhanceKit::InitClientEnhance(void) +{ + SecCompEnhanceAdapter::InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); +} + +int32_t SecCompEnhanceKit::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + return SecCompEnhanceAdapter::SetEnhanceCfg(cfg, cfgLen); +} + +int32_t SecCompEnhanceKit::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + return SecCompEnhanceAdapter::GetPointerEventEnhanceData(data, dataLen, enhanceData, enHancedataLen); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/enhance_kits/test/BUILD.gn b/interfaces/inner_api/enhance_kits/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bf1409c6a69a946289966c76e9158347d6dd7242 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/BUILD.gn @@ -0,0 +1,48 @@ +# 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. + +import("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_enhance_sdk_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ "unittest/src" ] + + sources = [ "unittest/src/sec_comp_enhance_test.cpp" ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + if (current_cpu == "arm64") { + defines = [ "_ARM64_" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":sec_comp_enhance_sdk_test" ] +} diff --git a/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0dad6f062f2d29d1487a3dc288e8da88a531d47d --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp @@ -0,0 +1,135 @@ +/* + * 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 "sec_comp_enhance_test.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEnhanceTest"}; +static bool g_inputEnhanceExist = false; +static bool g_srvEnhanceExist = false; +static constexpr uint32_t SEC_COMP_ENHANCE_CFG_SIZE = 76; +#ifdef _ARM64_ +static const std::string LIB_PATH = "/system/lib64/"; +#else +static const std::string LIB_PATH = "/system/lib/"; +#endif +static const std::string ENHANCE_INPUT_INTERFACE_LIB = LIB_PATH + "libsec_comp_input_enhance.z.so"; +static const std::string ENHANCE_SRV_INTERFACE_LIB = LIB_PATH + "libsec_comp_service_enhance.z.so"; +static constexpr uint32_t MAX_HMAC_SIZE = 64; +} // namespace + +void SecCompEnhanceTest::SetUpTestCase() +{ + if (access(ENHANCE_INPUT_INTERFACE_LIB.c_str(), F_OK) == 0) { + g_inputEnhanceExist = true; + } + + if (access(ENHANCE_SRV_INTERFACE_LIB.c_str(), F_OK) == 0) { + g_srvEnhanceExist = true; + } + system("kill -9 `pidof security_compon`"); + SC_LOG_INFO(LABEL, "SetUpTestCase."); +} + +void SecCompEnhanceTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "TearDownTestCase."); +} + +void SecCompEnhanceTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompEnhanceTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: SetEnhanceCfg001 + * @tc.desc: test SetEnhanceCfg + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, SetEnhanceCfg001, TestSize.Level1) +{ + uint8_t cfgData[SEC_COMP_ENHANCE_CFG_SIZE] = { 0 }; + int32_t result = SecCompEnhanceKit::SetEnhanceCfg(cfgData, SEC_COMP_ENHANCE_CFG_SIZE); + if (g_inputEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: GetPoniterEventEnhanceData001 + * @tc.desc: test GetPoniterEventEnhanceData + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, GetPoniterEventEnhanceData001, TestSize.Level1) +{ + uint8_t originData[16] = { 0 }; + uint32_t dataLen = 16; + uint8_t* enhanceData = nullptr; + uint32_t enHancedataLen = MAX_HMAC_SIZE; + + int32_t result = SecCompEnhanceKit::GetPointerEventEnhanceData(originData, dataLen, enhanceData, enHancedataLen); + if (g_inputEnhanceExist) { + EXPECT_EQ(result, SC_SERVICE_ERROR_SERVICE_NOT_EXIST); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: EnableInputEnhance001 + * @tc.desc: test UnmarshallEnhanceCfg + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, EnableInputEnhance001, TestSize.Level1) +{ + int32_t result = SecCompEnhanceAdapter::EnableInputEnhance(); + if (g_srvEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: DisableInputEnhance001 + * @tc.desc: test DisableInputEnhance + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, DisableInputEnhance001, TestSize.Level1) +{ + int32_t result = SecCompEnhanceAdapter::DisableInputEnhance(); + if (g_srvEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} diff --git a/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h new file mode 100644 index 0000000000000000000000000000000000000000..deff0d4a99042f8654e3de4608a7f275ca6fe842 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h @@ -0,0 +1,38 @@ +/* + * 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_COMPONENT_ENHANCE_KITS_TEST +#define SECURITY_COMPONENT_ENHANCE_KITS_TEST + +#include +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_enhance_kit.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEnhanceTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_KITS_TEST \ No newline at end of file diff --git a/interfaces/inner_api/security_component/BUILD.gn b/interfaces/inner_api/security_component/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..117f24ae7594d5767943b3ca2a79f7d552c427f7 --- /dev/null +++ b/interfaces/inner_api/security_component/BUILD.gn @@ -0,0 +1,67 @@ +# 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. + +import("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("sec_comp_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "//third_party/json/include", + ] +} + +ohos_shared_library("libsecurity_component_sdk") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_sdk" + + public_configs = [ ":sec_comp_config" ] + + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + ] + + sources = [ + "src/sec_comp_caller_authorization.cpp", + "src/sec_comp_client.cpp", + "src/sec_comp_death_recipient.cpp", + "src/sec_comp_kit.cpp", + "src/sec_comp_load_callback.cpp", + "src/sec_comp_proxy.cpp", + "src/sec_comp_ui_register.cpp", + ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/interfaces/inner_api/security_component/include/i_sec_comp_probe.h b/interfaces/inner_api/security_component/include/i_sec_comp_probe.h new file mode 100644 index 0000000000000000000000000000000000000000..c83cd997c603d59e48612b1dc942ba7ecc98b795 --- /dev/null +++ b/interfaces/inner_api/security_component/include/i_sec_comp_probe.h @@ -0,0 +1,30 @@ +/* + * 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 I_SECURITY_COMPONENT_PROPE_H +#define I_SECURITY_COMPONENT_PROPE_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class ISecCompProbe { +public: + virtual int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) = 0; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_PROPE_H diff --git a/interfaces/inner_api/security_component/include/i_sec_comp_service.h b/interfaces/inner_api/security_component/include/i_sec_comp_service.h new file mode 100644 index 0000000000000000000000000000000000000000..0b6d2e72be294ef361cdbbb9c69ca476c657c41a --- /dev/null +++ b/interfaces/inner_api/security_component/include/i_sec_comp_service.h @@ -0,0 +1,45 @@ +/* + * 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 I_SECURITY_COMPONENT_SERVICE_H +#define I_SECURITY_COMPONENT_SERVICE_H + +#include +#include "access_token.h" +#include "iremote_broker.h" +#include "sec_comp_info.h" +#include "security_component_service_ipc_interface_code.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr int32_t SA_ID_SECURITY_COMPONENT_SERVICE = 3506; + +class ISecCompService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.ISecCompService"); + + virtual int32_t RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) = 0; + virtual int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) = 0; + virtual int32_t UnregisterSecurityComponent(int32_t scId) = 0; + virtual int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, + const SecCompClickEvent& touchInfo, sptr callerToken) = 0; + virtual bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) = 0; + virtual sptr GetEnhanceRemoteObject() = 0; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_SERVICE_H diff --git a/interfaces/inner_api/security_component/include/location_button.h b/interfaces/inner_api/security_component/include/location_button.h new file mode 100644 index 0000000000000000000000000000000000000000..927189cb75898764e5cf182492bd6da3bb1c4b9c --- /dev/null +++ b/interfaces/inner_api/security_component/include/location_button.h @@ -0,0 +1,57 @@ +/* + * 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 I_SECURITY_COMPONENT_LOCATION_BUTTON_H +#define I_SECURITY_COMPONENT_LOCATION_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class LocationDesc : int32_t { + CURRENT_LOCATION = 0, + ADD_LOCATION = 1, + SELECT_LOCATION = 2, + SHARE_LOCATION = 3, + SEND_LOCATION = 4, + LOCATING = 5, + LOCATION = 6, + SEND_CURRENT_LOCATION = 7, + RELOCATION = 8, + PUNCH_IN = 9, + CURRENT_POSITION = 10, + MAX_LABEL_TYPE +}; + +enum class LocationIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class LocationButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_LOCATION_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/paste_button.h b/interfaces/inner_api/security_component/include/paste_button.h new file mode 100644 index 0000000000000000000000000000000000000000..241a316f2250790efa7e7c75e239d459b91deb93 --- /dev/null +++ b/interfaces/inner_api/security_component/include/paste_button.h @@ -0,0 +1,46 @@ +/* + * 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_COMPONENT_PASTE_BUTTON_H +#define SECURITY_COMPONENT_PASTE_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class PasteDesc : int32_t { + PASTE = 0, + MAX_LABEL_TYPE +}; + +enum class PasteIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class PasteButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_LOCATION_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/save_button.h b/interfaces/inner_api/security_component/include/save_button.h new file mode 100644 index 0000000000000000000000000000000000000000..ea7b5f516ebcd6ced4efe5ce5f92fa17e0b91413 --- /dev/null +++ b/interfaces/inner_api/security_component/include/save_button.h @@ -0,0 +1,54 @@ +/* + * 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 I_SECURITY_COMPONENT_SAVE_BUTTON_H +#define I_SECURITY_COMPONENT_SAVE_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class SaveDesc : int32_t { + DOWNLOAD = 0, + DOWNLOAD_FILE = 1, + SAVE = 2, + SAVE_IMAGE = 3, + SAVE_FILE = 4, + DOWNLOAD_AND_SHARE = 5, + RECEIVE = 6, + CONTINUE_TO_RECEIVE = 7, + MAX_LABEL_TYPE +}; + +enum class SaveIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class SaveButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_SAVE_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_base.h b/interfaces/inner_api/security_component/include/sec_comp_base.h new file mode 100644 index 0000000000000000000000000000000000000000..7449a003cd6ab2eb0bfc9777c8992483e4f6e0a3 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_base.h @@ -0,0 +1,139 @@ +/* + * 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_COMPONENT_BASE_H +#define SECURITY_COMPONENT_BASE_H + +#include "nlohmann/json.hpp" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr int32_t UNKNOWN_TEXT = -2; +constexpr int32_t NO_TEXT = -1; +constexpr int32_t UNKNOWN_ICON = -2; +constexpr int32_t NO_ICON = -1; + +enum class SecCompBackground { + UNKNOWN_BG = -2, + NO_BG_TYPE = -1, + CAPSULE = 0, + CIRCLE = 1, + NORMAL = 2, + MAX_BG_TYPE +}; + +class JsonTagConstants final { +public: + static const std::string JSON_RECT; + static const std::string JSON_SC_TYPE; + static const std::string JSON_NODE_ID; + static const std::string JSON_RECT_X; + static const std::string JSON_RECT_Y; + static const std::string JSON_RECT_WIDTH; + static const std::string JSON_RECT_HEIGHT; + static const std::string JSON_WINDOW_RECT; + + static const std::string JSON_SIZE_TAG; + static const std::string JSON_FONT_SIZE_TAG; + static const std::string JSON_ICON_SIZE_TAG; + static const std::string JSON_PADDING_SIZE_TAG; + static const std::string JSON_PADDING_LEFT_TAG; + static const std::string JSON_PADDING_TOP_TAG; + static const std::string JSON_PADDING_RIGHT_TAG; + static const std::string JSON_PADDING_BOTTOM_TAG; + static const std::string JSON_TEXT_ICON_PADDING_TAG; + static const std::string JSON_RECT_WIDTH_TAG; + static const std::string JSON_RECT_HEIGHT_TAG; + static const std::string JSON_COLORS_TAG; + static const std::string JSON_FONT_COLOR_TAG; + static const std::string JSON_ICON_COLOR_TAG; + static const std::string JSON_BG_COLOR_TAG; + + static const std::string JSON_BORDER_TAG; + static const std::string JSON_BORDER_WIDTH_TAG; + static const std::string JSON_PARENT_TAG; + static const std::string JSON_PARENT_EFFECT_TAG; + + static const std::string JSON_STYLE_TAG; + static const std::string JSON_TEXT_TAG; + static const std::string JSON_ICON_TAG; + static const std::string JSON_BG_TAG; +}; + +class SecCompBase { +public: + SecCompBase() = default; + virtual ~SecCompBase() = default; + bool FromJson(const nlohmann::json& jsonSrc); + void ToJson(nlohmann::json& jsonRes) const; + std::string ToJsonStr(void) const; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const; + void SetValid(bool valid) + { + isValid_ = valid; + }; + + bool GetValid() + { + return isValid_; + }; + + // size + DimensionT fontSize_ = DEFAULT_DIMENSION; + DimensionT iconSize_ = DEFAULT_DIMENSION; + PaddingSize padding_; + DimensionT textIconSpace_ = DEFAULT_DIMENSION; + + // color + SecCompColor fontColor_; + SecCompColor iconColor_; + SecCompColor bgColor_; + + // border + DimensionT borderWidth_ = DEFAULT_DIMENSION; + + // parent effect + bool parentEffect_ = false; + + SecCompType type_ = UNKNOWN_SC_TYPE; + SecCompRect rect_; + SecCompRect windowRect_; + bool isValid_ = false; + + int32_t text_ = UNKNOWN_TEXT; + int32_t icon_ = UNKNOWN_ICON; + SecCompBackground bg_ = SecCompBackground::UNKNOWN_BG; + + int32_t nodeId_ = 0; +protected: + virtual bool IsParamValid() = 0; +private: + bool ParseDimension(const nlohmann::json& json, const std::string& tag, DimensionT& res); + bool ParseColor(const nlohmann::json& json, const std::string& tag, SecCompColor& res); + bool ParseBool(const nlohmann::json& json, const std::string& tag, bool& res); + bool ParsePadding(const nlohmann::json& json, const std::string& tag, PaddingSize& res); + bool ParseColors(const nlohmann::json& json, const std::string& tag); + bool ParseBorders(const nlohmann::json& json, const std::string& tag); + bool ParseSize(const nlohmann::json& json, const std::string& tag); + bool ParseParent(const nlohmann::json& json, const std::string& tag); + bool ParseRect(const nlohmann::json& json, const std::string& tag, SecCompRect& rect); + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_BASE_H + diff --git a/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h b/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h new file mode 100644 index 0000000000000000000000000000000000000000..d1564a0b0c74a7fed0af767eedd62f51d7e4b6c0 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h @@ -0,0 +1,43 @@ +/* + * 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 INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H + +#include +#include +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompCallerAuthorization { +public: + static SecCompCallerAuthorization& GetInstance(); + virtual ~SecCompCallerAuthorization() = default; + void RegisterSecCompKitCaller(std::vector& callerList); + bool IsKitCaller(uintptr_t callerAddr); + +private: + SecCompCallerAuthorization() = default; + std::vector kitCallerList_; + bool isInit_ = false; + DISALLOW_COPY_AND_MOVE(SecCompCallerAuthorization); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H + diff --git a/interfaces/inner_api/security_component/include/sec_comp_client.h b/interfaces/inner_api/security_component/include/sec_comp_client.h new file mode 100644 index 0000000000000000000000000000000000000000..954fe115e0f62a55995573171257b0b01d07b702 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_client.h @@ -0,0 +1,68 @@ +/* + * 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_COMPONENT_CLIENT_H +#define SECURITY_COMPONENT_CLIENT_H + +#include +#include +#include +#include "i_sec_comp_service.h" +#include "sec_comp_death_recipient.h" +#include "sec_comp_err.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompClient final { +public: + static SecCompClient& GetInstance(); + + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId); + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo); + int32_t UnregisterSecurityComponent(int32_t scId); + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken); + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + sptr GetEnhanceRemoteObject(bool doLoadSa); + + void FinishStartSASuccess(const sptr& remoteObject); + void FinishStartSAFail(); + void OnRemoteDiedHandle(); + +private: + SecCompClient(); + virtual ~SecCompClient(); + DISALLOW_COPY_AND_MOVE(SecCompClient); + + bool TryToGetSecCompSa(); + bool StartLoadSecCompSa(); + void WaitForSecCompSa(); + void GetSecCompSa(); + void LoadSecCompSa(); + sptr GetProxy(bool doLoadSa); + void GetProxyFromRemoteObject(const sptr& remoteObject); + + std::mutex cvLock_; + bool readyFlag_ = false; + std::condition_variable secComCon_; + std::mutex proxyMutex_; + sptr proxy_ = nullptr; + sptr serviceDeathObserver_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_CLIENT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h b/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..4a18525526e50c4689e0715a0fb81cbecd659e30 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h @@ -0,0 +1,32 @@ +/* + * 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_COMPONENT_DEATH_RECIPIENT_H +#define SECURITY_COMPONENT_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompDeathRecipient : public IRemoteObject::DeathRecipient { +public: + SecCompDeathRecipient() {} + virtual ~SecCompDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_DEATH_RECIPIENT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_info.h b/interfaces/inner_api/security_component/include/sec_comp_info.h new file mode 100644 index 0000000000000000000000000000000000000000..d02ebb2263ac29f8a1b3fda0612ad3966855fa61 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_info.h @@ -0,0 +1,130 @@ +/* + * 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_COMPONENT_INFO_H +#define SECURITY_COMPONENT_INFO_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +static constexpr int32_t INVALID_SC_ID = -1; +using DimensionT = double; // unit is vp +static constexpr DimensionT DEFAULT_DIMENSION = 0.0; +static constexpr DimensionT MIN_FONT_SIZE = 12.0; +static constexpr DimensionT MIN_ICON_SIZE = 12.0; +static constexpr DimensionT MIN_PADDING_SIZE = 0.0; +static constexpr DimensionT MIN_PADDING_WITHOUT_BG = 4.0; +static constexpr uint32_t MAX_EXTRA_SIZE = 0x1000; + +struct PaddingSize { + DimensionT top = DEFAULT_DIMENSION; + DimensionT right = DEFAULT_DIMENSION; + DimensionT bottom = DEFAULT_DIMENSION; + DimensionT left = DEFAULT_DIMENSION; +}; + +enum SecCompType { + UNKNOWN_SC_TYPE = 0, + LOCATION_COMPONENT, + PASTE_COMPONENT, + SAVE_COMPONENT, + MAX_SC_TYPE +}; + +union SecCompColor { + struct { + uint8_t blue; + uint8_t green; + uint8_t red; + uint8_t alpha; + } argb; + uint32_t value; +}; + +inline bool IsComponentTypeValid(int32_t type) +{ + return (type > UNKNOWN_SC_TYPE && type < MAX_SC_TYPE); +} + +inline bool GreatOrEqual(double left, double right) +{ + constexpr double epsilon = -0.001; + return (left - right) > epsilon; +} + +inline bool GreatNotEqual(double left, double right) +{ + constexpr double epsilon = 0.001; + return (left - right) > epsilon; +} + +inline bool IsEqual(double left, double right) +{ + constexpr double epsilon = 0.001; + if (left > right) { + return (left - right) < epsilon; + } else if (right > left) { + return (right - left) < epsilon; + } else { + return true; + } +} + +class SecCompRect { +public: + SecCompRect() = default; + ~SecCompRect() = default; + + bool IsInRect(double x, double y) const + { + return (GreatOrEqual(x, x_) && GreatOrEqual((x_ + width_), x) && + GreatOrEqual(y, y_) && GreatOrEqual((y_ + height_), y)); + }; + + bool operator==(const SecCompRect& other) const + { + return (IsEqual(x_, other.x_)) && (IsEqual(y_, other.y_)) && + (IsEqual(width_, other.width_)) && (IsEqual(height_, other.height_)); + } + + DimensionT x_ = 0.0; + DimensionT y_ = 0.0; + DimensionT width_ = 0.0; + DimensionT height_ = 0.0; +}; + +struct ExtraInfo { + uint32_t dataSize; + uint8_t* data; +}; + +struct SecCompClickEvent { + double touchX; + double touchY; + uint64_t timestamp; + ExtraInfo extraInfo; +}; + +struct SecCompPointEvent { + double touchX; + double touchY; + uint64_t timestamp; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_INFO_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_kit.h b/interfaces/inner_api/security_component/include/sec_comp_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..80c20c253e41cb738da2f701e9e07f932c53f1fb --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_kit.h @@ -0,0 +1,40 @@ +/* + * 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 INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H + +#include +#include "accesstoken_kit.h" +#include "iremote_object.h" +#include "sec_comp_info.h" +#include "sec_comp_ui_register.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompKit { +public: + static int32_t RegisterSecurityComponent(SecCompType type, std::string& componentInfo, int32_t& scId); + static int32_t UpdateSecurityComponent(int32_t scId, std::string& componentInfo); + static int32_t UnregisterSecurityComponent(int32_t scId); + static int32_t ReportSecurityComponentClickEvent(int32_t scId, + std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken = nullptr); + static bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + static sptr GetEnhanceRemoteObject(bool isLoad); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_load_callback.h b/interfaces/inner_api/security_component/include/sec_comp_load_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5513896e17473d10bddf632a0da0849fc98755a3 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_load_callback.h @@ -0,0 +1,33 @@ +/* + * 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_COMPONENT_LOAD_CALLBACK_H +#define SECURITY_COMPONENT_LOAD_CALLBACK_H + +#include "system_ability_load_callback_stub.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompLoadCallback : public SystemAbilityLoadCallbackStub { +public: + explicit SecCompLoadCallback(); + + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr& remoteObject); + void OnLoadSystemAbilityFail(int32_t systemAbilityId); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_LOAD_CALLBACK_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_proxy.h b/interfaces/inner_api/security_component/include/sec_comp_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..729877bcc026aa558e0abea0680a8db1cc431e56 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_proxy.h @@ -0,0 +1,43 @@ +/* + * 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_COMPONENT_PROXY_H +#define SECURITY_COMPONENT_PROXY_H + +#include +#include "i_sec_comp_service.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompProxy : public IRemoteProxy { +public: + explicit SecCompProxy(const sptr& impl); + ~SecCompProxy() override; + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId) override; + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override; + int32_t UnregisterSecurityComponent(int32_t scId) override; + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) override; + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override; + sptr GetEnhanceRemoteObject() override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_PROXY_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_ui_register.h b/interfaces/inner_api/security_component/include/sec_comp_ui_register.h new file mode 100644 index 0000000000000000000000000000000000000000..b415bb164fdbe6c384c6f12c253dd1ac67719d9c --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_ui_register.h @@ -0,0 +1,33 @@ +/* + * 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 INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H + +#include "i_sec_comp_probe.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompUiRegister { +public: + SecCompUiRegister(std::vector& callerList, ISecCompProbe* probe); + virtual ~SecCompUiRegister() = default; + static ISecCompProbe* callbackProbe; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H + diff --git a/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h b/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h new file mode 100644 index 0000000000000000000000000000000000000000..a873e90f74de90df0b0d6f5bd90136dff0e2c17b --- /dev/null +++ b/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h @@ -0,0 +1,43 @@ +/* + * 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_COMPONENT_IPC_INTERFACE_CODE_H +#define SECURITY_COMPONENT_IPC_INTERFACE_CODE_H + +/* SAID: 3506 */ +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum SecurityComponentServiceInterfaceCode { + REGISTER_SECURITY_COMPONENT = 0, + UPDATE_SECURITY_COMPONENT = 1, + UNREGISTER_SECURITY_COMPONENT = 2, + REPORT_SECURITY_COMPONENT_CLICK_EVENT = 3, + GET_SECURITY_COMPONENT_ENHANCE_OBJECT = 4, + VERIFY_TEMP_SAVE_PERMISSION = 5, +}; + +enum EnhanceInterfaceCode { + REGISTER_CHECK_CALLBACK = 0, +}; + +enum EnhanceCallbackCheckCode { + GET_CALLER_SECURITY_COMPONENT_INFO = 0, +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_IPC_INTERFACE_CODE_H + diff --git a/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp b/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b98be285b612ac3528e4601f775143fa5a3c1e7c --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp @@ -0,0 +1,67 @@ +/* + * 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 "sec_comp_caller_authorization.h" + +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr int32_t MAX_FUNC_ASM_SIZE = 0x250; +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompCallerAuthorization"}; +static constexpr size_t MAX_CALLER_SIZE = 10; +} + +void SecCompCallerAuthorization::RegisterSecCompKitCaller(std::vector& callerList) +{ + if (isInit_) { + SC_LOG_ERROR(LABEL, "can not init repeatly"); + return; + } + + isInit_ = true; + if ((callerList.size() == 0) || (callerList.size() > MAX_CALLER_SIZE)) { + SC_LOG_ERROR(LABEL, "caller size is invalid"); + return; + } + + kitCallerList_ = callerList; +} + +bool SecCompCallerAuthorization::IsKitCaller(uintptr_t callerAddr) +{ + if (!isInit_) { + SC_LOG_INFO(LABEL, "caller authorization has not init"); + return true; + } + for (size_t i = 0; i < kitCallerList_.size(); i++) { + if ((callerAddr > kitCallerList_[i]) && (callerAddr < kitCallerList_[i] + MAX_FUNC_ASM_SIZE)) { + return true; + } + } + return false; +} + +SecCompCallerAuthorization& SecCompCallerAuthorization::GetInstance() +{ + static SecCompCallerAuthorization instance; + return instance; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/interfaces/inner_api/security_component/src/sec_comp_client.cpp b/interfaces/inner_api/security_component/src/sec_comp_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e20ceeabdc73b9da67c79848333a199d7dc165b --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_client.cpp @@ -0,0 +1,258 @@ +/* + * 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 "sec_comp_client.h" + +#include "iservice_registry.h" +#include "sec_comp_load_callback.h" +#include "sec_comp_log.h" +#include "sec_comp_proxy.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClient"}; +} // namespace + +SecCompClient& SecCompClient::GetInstance() +{ + static SecCompClient instance; + return instance; +} + +SecCompClient::SecCompClient() +{} + +SecCompClient::~SecCompClient() +{ + if (proxy_ == nullptr) { + return; + } + auto remoteObj = proxy_->AsObject(); + if (remoteObj == nullptr) { + return; + } + if (serviceDeathObserver_ != nullptr) { + remoteObj->RemoveDeathRecipient(serviceDeathObserver_); + } +} + +int32_t SecCompClient::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->RegisterSecurityComponent(type, componentInfo, scId); +} + +int32_t SecCompClient::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->UpdateSecurityComponent(scId, componentInfo); +} + +int32_t SecCompClient::UnregisterSecurityComponent(int32_t scId) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->UnregisterSecurityComponent(scId); +} + +int32_t SecCompClient::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->ReportSecurityComponentClickEvent(scId, componentInfo, touchInfo, callerToken); +} + +bool SecCompClient::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + auto proxy = GetProxy(false); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return false; + } + + return proxy->ReduceAfterVerifySavePermission(tokenId); +} + +sptr SecCompClient::GetEnhanceRemoteObject(bool doLoadSa) +{ + auto proxy = GetProxy(doLoadSa); + if (proxy == nullptr) { + return nullptr; + } + + return proxy->GetEnhanceRemoteObject(); +} + +bool SecCompClient::StartLoadSecCompSa() +{ + { + std::unique_lock lock(cvLock_); + readyFlag_ = false; + } + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + SC_LOG_ERROR(LABEL, "GetSystemAbilityManager return null"); + return false; + } + sptr ptrSecCompLoadCallback = + new (std::nothrow) SecCompLoadCallback(); + if (ptrSecCompLoadCallback == nullptr) { + SC_LOG_ERROR(LABEL, "New ptrSecCompLoadCallback fail."); + return false; + } + + int32_t result = sam->LoadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE, + ptrSecCompLoadCallback); + if (result != SC_OK) { + SC_LOG_ERROR(LABEL, "LoadSystemAbility %{public}d failed", SA_ID_SECURITY_COMPONENT_SERVICE); + return false; + } + SC_LOG_INFO(LABEL, "Notify samgr load sa %{public}d, waiting for service start", SA_ID_SECURITY_COMPONENT_SERVICE); + return true; +} + +bool SecCompClient::TryToGetSecCompSa() +{ + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + SC_LOG_ERROR(LABEL, "GetSystemAbilityManager return null"); + return false; + } + + auto secCompSa = sam->CheckSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (secCompSa == nullptr) { + SC_LOG_INFO(LABEL, "Service is not start."); + return false; + } + GetProxyFromRemoteObject(secCompSa); + return true; +} + +void SecCompClient::WaitForSecCompSa() +{ + // wait_for release lock and block until time out(1s) or match the condition with notice + std::unique_lock lock(cvLock_); + auto waitStatus = secComCon_.wait_for( + lock, std::chrono::milliseconds(SA_ID_SECURITY_COMPONENT_SERVICE), [this]() { return readyFlag_; }); + if (!waitStatus) { + // time out or loadcallback fail + SC_LOG_ERROR(LABEL, "security component load sa timeout"); + return; + } +} + +void SecCompClient::FinishStartSASuccess(const sptr& remoteObject) +{ + GetProxyFromRemoteObject(remoteObject); + // get lock which wait_for release and send a notice so that wait_for can out of block + std::unique_lock lock(cvLock_); + readyFlag_ = true; + secComCon_.notify_one(); +} + +void SecCompClient::FinishStartSAFail() +{ + SC_LOG_ERROR(LABEL, "get security component sa failed."); + // get lock which wait_for release and send a notice + std::unique_lock lock(cvLock_); + readyFlag_ = true; + secComCon_.notify_one(); +} + +void SecCompClient::LoadSecCompSa() +{ + if (!StartLoadSecCompSa()) { + return; + } + WaitForSecCompSa(); +} + +void SecCompClient::OnRemoteDiedHandle() +{ + SC_LOG_ERROR(LABEL, "Remote service died"); + std::unique_lock lock(proxyMutex_); + proxy_ = nullptr; + serviceDeathObserver_ = nullptr; + { + std::unique_lock lock1(cvLock_); + readyFlag_ = false; + } +} + +void SecCompClient::GetProxyFromRemoteObject(const sptr& remoteObject) +{ + if (remoteObject == nullptr) { + return; + } + + sptr serviceDeathObserver = new (std::nothrow) SecCompDeathRecipient(); + if (serviceDeathObserver == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc service death observer fail"); + return; + } + + if (!remoteObject->AddDeathRecipient(serviceDeathObserver)) { + SC_LOG_ERROR(LABEL, "Add service death observer fail"); + return; + } + + auto proxy = iface_cast(remoteObject); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "iface_cast get null"); + return; + } + proxy_ = proxy; + serviceDeathObserver_ = serviceDeathObserver; + SC_LOG_INFO(LABEL, "GetSystemAbility %{public}d success", SA_ID_SECURITY_COMPONENT_SERVICE); + return; +} + +sptr SecCompClient::GetProxy(bool doLoadSa) +{ + std::unique_lock lock(proxyMutex_); + if (proxy_ != nullptr) { + return proxy_; + } + if (TryToGetSecCompSa() || !doLoadSa) { + return proxy_; + } + + LoadSecCompSa(); + return proxy_; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp b/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbdf7fcb9c67e82a5439bb290a4e969ecd00ebd4 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp @@ -0,0 +1,28 @@ +/* + * 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 "sec_comp_death_recipient.h" + +#include "sec_comp_client.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void SecCompDeathRecipient::OnRemoteDied(const wptr& object) +{ + SecCompClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_kit.cpp b/interfaces/inner_api/security_component/src/sec_comp_kit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05b7bd2472c4764086526fbf692a6c35aecada2c --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_kit.cpp @@ -0,0 +1,138 @@ +/* + * 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 "sec_comp_kit.h" + +#include "hisysevent.h" +#include "ipc_skeleton.h" +#include "sec_comp_caller_authorization.h" +#include "sec_comp_client.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompKit"}; +} // namespace + +int32_t SecCompKit::RegisterSecurityComponent(SecCompType type, + std::string& componentInfo, int32_t& scId) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "register security component fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "REGITSTER"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompClient::GetInstance().RegisterSecurityComponent(type, componentInfo, scId); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "register security component fail, error: %{public}d", res); + return res; + } + SecCompEnhanceAdapter::RegisterScIdEnhance(scId); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "REGISTER_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", type); + return res; +} + +int32_t SecCompKit::UpdateSecurityComponent(int32_t scId, std::string& componentInfo) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "update security component fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "UPDATE"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(scId, componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompClient::GetInstance().UpdateSecurityComponent(scId, componentInfo); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "update security component fail, error: %{public}d", res); + } + return res; +} + +int32_t SecCompKit::UnregisterSecurityComponent(int32_t scId) +{ + int32_t res = SecCompClient::GetInstance().UnregisterSecurityComponent(scId); + SecCompEnhanceAdapter::UnregisterScIdEnhance(scId); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "unregister security component fail, error: %{public}d", res); + return res; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "UNREGISTER_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId); + return res; +} + +int32_t SecCompKit::ReportSecurityComponentClickEvent(int32_t scId, + std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "report click event fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "CLICK"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(scId, componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = + SecCompClient::GetInstance().ReportSecurityComponentClickEvent(scId, componentInfo, touchInfo, callerToken); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "report click event fail, error: %{public}d", res); + } + return res; +} + +bool SecCompKit::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + bool res = + SecCompClient::GetInstance().ReduceAfterVerifySavePermission(tokenId); + if (!res) { + SC_LOG_ERROR(LABEL, "verify temp save permission, error: %{public}d", res); + } + return res; +} + +sptr SecCompKit::GetEnhanceRemoteObject(bool isLoad) +{ + return SecCompClient::GetInstance().GetEnhanceRemoteObject(isLoad); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp b/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fd9f263797e6b51c1aea5af9ffc4e7dfd131565 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp @@ -0,0 +1,61 @@ +/* + * 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 "sec_comp_load_callback.h" + +#include "i_sec_comp_service.h" +#include "sec_comp_client.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClient"}; +} // namespace +SecCompLoadCallback::SecCompLoadCallback() {} + +void SecCompLoadCallback::OnLoadSystemAbilitySuccess( + int32_t systemAbilityId, const sptr& remoteObject) +{ + if (systemAbilityId != SA_ID_SECURITY_COMPONENT_SERVICE) { + SC_LOG_ERROR(LABEL, "start systemabilityId is not security_component!"); + return; + } + + if (remoteObject == nullptr) { + SC_LOG_ERROR(LABEL, "remoteObject is null."); + SecCompClient::GetInstance().FinishStartSAFail(); + return; + } + + SC_LOG_INFO(LABEL, "Start systemAbilityId: %{public}d success!", systemAbilityId); + + SecCompClient::GetInstance().FinishStartSASuccess(remoteObject); +} + +void SecCompLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + if (systemAbilityId != SA_ID_SECURITY_COMPONENT_SERVICE) { + SC_LOG_ERROR(LABEL, "start systemabilityId is not security_component!"); + return; + } + + SC_LOG_ERROR(LABEL, "Start systemAbilityId: %{public}d failed.", systemAbilityId); + + SecCompClient::GetInstance().FinishStartSAFail(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp b/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d8e205bee8a604a1e21dd0f1f0ca2b5a330611f --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp @@ -0,0 +1,274 @@ +/* + * 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 "sec_comp_proxy.h" + +#include "sec_comp_click_event_parcel.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompProxy"}; +} + +SecCompProxy::SecCompProxy(const sptr& impl) : IRemoteProxy(impl) +{} + +SecCompProxy::~SecCompProxy() +{} + +int32_t SecCompProxy::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteUint32(type)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read result int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!reply.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read scId int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT), data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read result int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::UnregisterSecurityComponent(int32_t scId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + sptr parcel = new (std::nothrow) SecCompClickEventParcel(); + if (parcel == nullptr) { + SC_LOG_ERROR(LABEL, "New click event parcel failed"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + parcel->touchInfoParams_ = touchInfo; + if (!data.WriteParcelable(parcel)) { + SC_LOG_ERROR(LABEL, "Write touchInfo fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if ((callerToken != nullptr) && !data.WriteRemoteObject(callerToken)) { + SC_LOG_ERROR(LABEL, "Write caller token fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +bool SecCompProxy::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return false; + } + + if (!data.WriteUint32(tokenId)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return false; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return false; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return false; + } + bool res; + if (!reply.ReadBool(res)) { + SC_LOG_ERROR(LABEL, "Read bool fail"); + return false; + } + return res; +} + +sptr SecCompProxy::GetEnhanceRemoteObject() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return nullptr; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return nullptr; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return nullptr; + } + sptr callback = reply.ReadRemoteObject(); + if (callback == nullptr) { + SC_LOG_ERROR(LABEL, "Read remote object fail"); + } + return callback; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp b/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a94215f6da0093abd6ec7b8069e8275e7a2b1234 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp @@ -0,0 +1,39 @@ +/* + * 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 "sec_comp_ui_register.h" + +#include "sec_comp_caller_authorization.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompUiRegister"}; +} // namespace + +ISecCompProbe* SecCompUiRegister::callbackProbe = nullptr; + +SecCompUiRegister::SecCompUiRegister(std::vector& callerList, ISecCompProbe* probe) +{ + SC_LOG_INFO(LABEL, "Init"); + SecCompCallerAuthorization::GetInstance().RegisterSecCompKitCaller(callerList); + callbackProbe = probe; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/interfaces/inner_api/security_component/test/BUILD.gn b/interfaces/inner_api/security_component/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fdba91b8a0e40d27607119904555702266a0bcc3 --- /dev/null +++ b/interfaces/inner_api/security_component/test/BUILD.gn @@ -0,0 +1,93 @@ +# 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. + +import("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_sdk_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_test.cpp", + "unittest/src/paste_button_test.cpp", + "unittest/src/save_button_test.cpp", + "unittest/src/sec_comp_kit_test.cpp", + "unittest/src/test_common.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +ohos_unittest("sec_comp_register_callback_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/sec_comp_register_callback_test.cpp", + "unittest/src/test_common.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ + ":sec_comp_register_callback_test", + ":sec_comp_sdk_test", + ] +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4be6317214e49c6307b0f68b4687e0b1da77ac7 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp @@ -0,0 +1,552 @@ +/* + * 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 "location_button_test.h" + +#include +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "LocationButtonTest"}; +static const std::string WRONG_TYPE = "wrongType"; +} + +void LocationButtonTest::SetUpTestCase() +{} + +void LocationButtonTest::TearDownTestCase() +{} + +void LocationButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void LocationButtonTest::TearDown() +{} + +/** + * @tc.name: FromJson001 + * @tc.desc: Test LocationButton from json success + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton comp; + ASSERT_TRUE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson002 + * @tc.desc: Test empty LocationButton from json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson003 + * @tc.desc: Test location button from wrong type json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton comp; + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = WRONG_TYPE; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = 0; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson004 + * @tc.desc: Test location button from wrong rect json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson004, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + nlohmann::json wrongJson = nlohmann::json::parse("{", nullptr, false); + jsonComponent[JsonTagConstants::JSON_RECT] = wrongJson; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, WRONG_TYPE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson005 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson005, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson006 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson006, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson007 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson007, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, WRONG_TYPE }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson008 + * @tc.desc: Test location button from wrong border and parent json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson008, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + TestCommon::BuildLocationComponentInfo(jsonComponent); + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson009 + * @tc.desc: Test location button from wrong type params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson009, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton button; + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson010 + * @tc.desc: Test location button from wrong type params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton button; + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TestCommon::TEST_COLOR_YELLOW } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TestCommon::TEST_COLOR_YELLOW } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, WRONG_TYPE } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson011 + * @tc.desc: Test location button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson011, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: ToJsonStr001 + * @tc.desc: Test ToJsonStr normal branch + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, ToJsonStr001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + ASSERT_EQ(jsonComponent.dump(), button.ToJsonStr()); +} + +/** + * @tc.name: CompareComponentBasicInfo001 + * @tc.desc: Test CompareComponentBasicInfo other is null + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareComponentBasicInfo001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_FALSE(button.CompareComponentBasicInfo(nullptr, true)); +} + +/** + * @tc.name: CompareLocationButton001 + * @tc.desc: Test LocationButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareLocationButton001, TestSize.Level1) +{ + LocationButton button1; + LocationButton button2; + + nlohmann::json jsonComponent; + TestCommon::BuildLocationComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(LocationDesc::SELECT_LOCATION); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(LocationIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: CompareLocationButton002 + * @tc.desc: Test LocationButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareLocationButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp1; + TestCommon::BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + LocationButton comp2 = comp1; + + comp1.type_ = SAVE_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = LOCATION_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TestCommon::TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TestCommon::TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TestCommon::TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TestCommon::TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TestCommon::TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TestCommon::TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TestCommon::TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TestCommon::TEST_SIZE; + + comp1.fontColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TestCommon::TEST_COLOR_RED; + + comp1.bgColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TestCommon::TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TestCommon::TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7324bd73e3b2b12313a6c7cef783030e4c3fc192 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h @@ -0,0 +1,38 @@ +/* + * 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 SEC_COMP_LOCATION_BUTTON_TEST_H +#define SEC_COMP_LOCATION_BUTTON_TEST_H + +#include +#include "location_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class LocationButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_LOCATION_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e724f359ff740d673d9ad8e7b6800b092306d67b --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp @@ -0,0 +1,198 @@ +/* + * 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 "paste_button_test.h" + +#include +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "PasteButtonTest"}; +} + +void PasteButtonTest::SetUpTestCase() +{} + +void PasteButtonTest::TearDownTestCase() +{} + +void PasteButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void PasteButtonTest::TearDown() +{} + +/** + * @tc.name: IsParamValid001 + * @tc.desc: Test paste button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, FromJson010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildPasteComponentInfo(jsonComponent); + PasteButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE}, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: ComparePasteButton001 + * @tc.desc: Test compare paste button + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, ComparePasteButton001, TestSize.Level1) +{ + PasteButton button1; + PasteButton button2; + + nlohmann::json jsonComponent; + TestCommon::BuildPasteComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(PasteDesc::PASTE); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(PasteIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: ComparePasteButton002 + * @tc.desc: Test PasteButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, ComparePasteButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + PasteButton comp1; + TestCommon::BuildPasteComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + PasteButton comp2 = comp1; + + comp1.type_ = LOCATION_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = PASTE_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TestCommon::TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TestCommon::TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TestCommon::TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TestCommon::TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TestCommon::TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TestCommon::TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TestCommon::TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TestCommon::TEST_SIZE; + + comp1.fontColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TestCommon::TEST_COLOR_RED; + + comp1.bgColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TestCommon::TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TestCommon::TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..6e73d91cb198d05934540909dce27f25e2dc8326 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h @@ -0,0 +1,38 @@ +/* + * 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 SEC_COMP_PASTE_BUTTON_TEST_H +#define SEC_COMP_PASTE_BUTTON_TEST_H + +#include +#include "paste_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class PasteButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_PASTE_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c48e62ee9431213197fe2cdddbebfb573c44598 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp @@ -0,0 +1,198 @@ +/* + * 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 "save_button_test.h" + +#include +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SaveButtonTest"}; +} + +void SaveButtonTest::SetUpTestCase() +{} + +void SaveButtonTest::TearDownTestCase() +{} + +void SaveButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SaveButtonTest::TearDown() +{} + +/** + * @tc.name: IsParamValid001 + * @tc.desc: Test save button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, FromJson010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + TestCommon::BuildSaveComponentInfo(jsonComponent); + SaveButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD}, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: CompareSaveButton001 + * @tc.desc: Test compare save button + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, CompareSaveButton001, TestSize.Level1) +{ + SaveButton button1; + SaveButton button2; + + nlohmann::json jsonComponent; + TestCommon::BuildSaveComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(SaveDesc::DOWNLOAD); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(SaveIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: CompareSaveButton002 + * @tc.desc: Test SaveButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, CompareSaveButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + SaveButton comp1; + TestCommon::BuildSaveComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + SaveButton comp2 = comp1; + + comp1.type_ = PASTE_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = SAVE_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TestCommon::TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TestCommon::TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TestCommon::TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TestCommon::TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TestCommon::TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TestCommon::TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TestCommon::TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TestCommon::TEST_SIZE; + + comp1.fontColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TestCommon::TEST_COLOR_RED; + + comp1.bgColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TestCommon::TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TestCommon::TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TestCommon::TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..34c9f6adc60ba9134ba27d82108af6dfafd779fa --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h @@ -0,0 +1,38 @@ +/* + * 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 SEC_COMP_SAVE_BUTTON_TEST_H +#define SEC_COMP_SAVE_BUTTON_TEST_H + +#include +#include "save_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SaveButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_SAVE_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58dc275ddfb5ee56d62b502c37a2c4bb8254921b --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp @@ -0,0 +1,191 @@ +/* + * 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 "sec_comp_kit_test.h" + +#include "location_button.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "test_common.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompKitTest"}; + +static void TestInCallerNotCheckList() +{ + int32_t scId = -1; + struct SecCompClickEvent touch; + std::string emptyStr = ""; + int registerRes = SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, emptyStr, scId); + int updateRes = SecCompKit::UpdateSecurityComponent(scId, emptyStr); + int reportRes = SecCompKit::ReportSecurityComponentClickEvent(scId, emptyStr, touch, nullptr); + + EXPECT_EQ(registerRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_EQ(updateRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_EQ(reportRes, SC_SERVICE_ERROR_CALLER_INVALID); +} + +static void TestInCallerCheckList() +{ + int32_t scId = -1; + struct SecCompClickEvent touch; + std::string emptyStr = ""; + int registerRes = SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, emptyStr, scId); + int updateRes = SecCompKit::UpdateSecurityComponent(scId, emptyStr); + int reportRes = SecCompKit::ReportSecurityComponentClickEvent(scId, emptyStr, touch, nullptr); + + EXPECT_NE(registerRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_NE(updateRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_NE(reportRes, SC_SERVICE_ERROR_CALLER_INVALID); +} +} // namespace + +void SecCompKitTest::SetUpTestCase() +{ + SC_LOG_INFO(LABEL, "SetUpTestCase."); +} + +void SecCompKitTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "TearDownTestCase."); +} + +void SecCompKitTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompKitTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: ExceptCall001 + * @tc.desc: do kit except call. + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompKitTest, ExceptCall001, TestSize.Level1) +{ + LocationButton comp; + comp.fontSize_ = TestCommon::TEST_SIZE; + comp.iconSize_ = TestCommon::TEST_SIZE; + comp.padding_.top = TestCommon::TEST_DIMENSION; + comp.padding_.right = TestCommon::TEST_DIMENSION; + comp.padding_.bottom = TestCommon::TEST_DIMENSION; + comp.padding_.left = TestCommon::TEST_DIMENSION; + comp.textIconSpace_ = TestCommon::TEST_SIZE; + comp.bgColor_.value = TestCommon::TEST_COLOR; + comp.fontColor_.value = TestCommon::TEST_COLOR; + comp.iconColor_.value = TestCommon::TEST_COLOR; + comp.borderWidth_ = TestCommon::TEST_SIZE; + comp.parentEffect_ = true; + comp.type_ = LOCATION_COMPONENT; + comp.rect_.x_ = TestCommon::TEST_COORDINATE; + comp.rect_.y_ = TestCommon::TEST_COORDINATE; + comp.rect_.width_ = TestCommon::TEST_COORDINATE; + comp.rect_.height_ = TestCommon::TEST_COORDINATE; + + nlohmann::json jsonRes; + comp.ToJson(jsonRes); + int32_t scId = -1; + std::string jsonStr = jsonRes.dump(); + ASSERT_NE(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, jsonStr, scId)); + ASSERT_EQ(-1, scId); + ASSERT_NE(SC_OK, SecCompKit::UpdateSecurityComponent(scId, jsonStr)); + + struct SecCompClickEvent touch = { + .touchX = TestCommon::TEST_COORDINATE, + .touchY = TestCommon::TEST_COORDINATE, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + EXPECT_NE(SC_OK, SecCompKit::ReportSecurityComponentClickEvent(scId, jsonStr, touch, nullptr)); + EXPECT_NE(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: ExceptCall001 + * @tc.desc: test caller check. + * @tc.type: FUNC + * @tc.require: AR000HO9JS + */ +HWTEST_F(SecCompKitTest, TestCallerCheck001, TestSize.Level1) +{ + std::vector callerList = { + reinterpret_cast(TestInCallerCheckList), + }; + SecCompUiRegister registerCallback(callerList, nullptr); + TestInCallerCheckList(); + TestInCallerNotCheckList(); + + // prohibit init caller list repeately + std::vector callerList1 = { + reinterpret_cast(TestInCallerNotCheckList), + }; + SecCompUiRegister registerCallback1(callerList1, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} + +/** + * @tc.name: ExceptCall002 + * @tc.desc: test invalid caller register. + * @tc.type: FUNC + * @tc.require: AR000HO9JS + */ +HWTEST_F(SecCompKitTest, TestCallerCheck002, TestSize.Level1) +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; + + for (size_t i = 0; i < TestCommon::MAX_CALLER_SIZE + 1; i++) { + callerList.emplace_back(reinterpret_cast(TestInCallerNotCheckList)); + } + SecCompUiRegister registerCallback2(callerList, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} + +/** + * @tc.name: RegisterWithoutCallback001 + * @tc.desc: test register without callback. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompKitTest, RegisterWithoutCallback001, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST, + SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..3bd124102c671cb161bfa59bced2f511397809f5 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h @@ -0,0 +1,37 @@ +/* + * 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_COMPONENT_KIT_TEST +#define SECURITY_COMPONENT_KIT_TEST + +#include +#include "sec_comp_kit.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_KIT_TEST \ No newline at end of file diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b38dd25cdb6b200413ff3ed80eb15edaf5029901 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp @@ -0,0 +1,307 @@ +/* + * 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 +#include "i_sec_comp_probe.h" +#include "location_button.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_client.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_kit.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_ui_register.h" +#include "test_common.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompRegisterCallbackTest"}; + +class MockUiSecCompProbe : public ISecCompProbe { +public: + int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) override + { + componentInfo = mockComponentInfo; + return mockRes; + } + std::string mockComponentInfo; + int32_t mockRes; +}; + +static MockUiSecCompProbe g_probe; +static void InitUiRegister() +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, &g_probe); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} +} // namespace + +class SecCompRegisterCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; + +void SecCompRegisterCallbackTest::SetUpTestCase() +{ + InitUiRegister(); + SC_LOG_INFO(LABEL, "SecCompRegisterCallbackTest."); +} + +void SecCompRegisterCallbackTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "SecCompRegisterCallbackTest."); +} + +void SecCompRegisterCallbackTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompRegisterCallbackTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: RegisterWithoutPreprocess001 + * @tc.desc: test register without preprocess + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, RegisterWithoutPreprocess001, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + + SecCompEnhanceAdapter::InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL, + SecCompClient::GetInstance().RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} + +/** + * @tc.name: Register001 + * @tc.desc: test register security component success. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register001, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_NE(-1, scId); + + EXPECT_EQ(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: Register002 + * @tc.desc: test register callback failed. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register002, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = -1; + + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL, + SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} + +/** + * @tc.name: Register003 + * @tc.desc: test register in MaliciousAppList. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register003, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); +} + +/** + * @tc.name: RegisterSecurityComponent001 + * @tc.desc: Test register security component check touch info failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompRegisterCallbackTest, RegisterSecurityComponent001, TestSize.Level1) +{ + system("param set sec.comp.enhance 1"); + nlohmann::json jsonRes; + TestCommon::BuildSaveComponentInfo(jsonRes); + std::string saveInfo = jsonRes.dump(); + int32_t scId; + + EXPECT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + uint8_t data[TestCommon::MAX_HMAC_SIZE] = { 0 }; + struct SecCompClickEvent touchInfo = { + .touchX = TestCommon::TEST_COORDINATE, + .touchY = TestCommon::TEST_COORDINATE, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + touchInfo.extraInfo.dataSize = TestCommon::MAX_HMAC_SIZE; + touchInfo.extraInfo.data = data; + EXPECT_EQ(SC_SERVICE_ERROR_CLICK_EVENT_INVALID, + SecCompKit::ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + EXPECT_EQ(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); + system("param set sec.comp.enhance 0"); +} + +/** + * @tc.name: RegisterSecurityComponent002 + * @tc.desc: Test register security component permission grant failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompRegisterCallbackTest, RegisterSecurityComponent002, TestSize.Level1) +{ + system("param set sec.comp.enhance 1"); + nlohmann::json jsonRes; + TestCommon::BuildSaveComponentInfo(jsonRes); + std::string saveInfo = jsonRes.dump(); + int32_t scId; + + EXPECT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + uint8_t data[TestCommon::MAX_HMAC_SIZE] = { 0 }; + struct SecCompClickEvent touchInfo = { + .touchX = TestCommon::TEST_COORDINATE, + .touchY = TestCommon::TEST_COORDINATE, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TestCommon::TIME_CONVERSION_UNIT + }; + touchInfo.extraInfo.dataSize = TestCommon::MAX_HMAC_SIZE; + touchInfo.extraInfo.data = data; + EXPECT_EQ(SC_OK, SecCompKit::ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + EXPECT_EQ(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); + system("param set sec.comp.enhance 0"); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent003 + * @tc.desc: Test register security component success + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompRegisterCallbackTest, ReportSecurityComponentClickEvent003, TestSize.Level1) +{ + system("param set sec.comp.enhance 1"); + nlohmann::json jsonRes; + TestCommon::BuildSaveComponentInfo(jsonRes); + std::string saveInfo = jsonRes.dump(); + int32_t scId; + + EXPECT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + uint8_t data[TestCommon::MAX_HMAC_SIZE] = { 0 }; + struct SecCompClickEvent touchInfo = { + .touchX = TestCommon::TEST_COORDINATE, + .touchY = TestCommon::TEST_COORDINATE, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TestCommon::TIME_CONVERSION_UNIT + }; + touchInfo.extraInfo.dataSize = TestCommon::MAX_HMAC_SIZE; + touchInfo.extraInfo.data = data; + + ASSERT_EQ(SC_OK, SecCompKit::ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + uint32_t selfTokenId = GetSelfTokenID(); + ASSERT_TRUE(SecCompKit::ReduceAfterVerifySavePermission(selfTokenId)); + system("param set sec.comp.enhance 0"); +} + +/** + * @tc.name: ExceptCall001 + * @tc.desc: Test update security component success + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompRegisterCallbackTest, ExceptCall001, TestSize.Level1) +{ + nlohmann::json jsonRes; + TestCommon::BuildSaveComponentInfo(jsonRes); + std::string saveInfo = jsonRes.dump(); + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, saveInfo, scId)); + ASSERT_NE(-1, scId); + ASSERT_EQ(SC_OK, SecCompKit::UpdateSecurityComponent(scId, saveInfo)); +} + +/** + * @tc.name: ReportClickWithoutHmac001 + * @tc.desc: Test report click event permission denied + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, ReportClickWithoutHmac001, TestSize.Level1) +{ + system("param set sec.comp.enhance 1"); + nlohmann::json jsonRes; + TestCommon::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_NE(-1, scId); + uint8_t data[TestCommon::MAX_HMAC_SIZE] = { 0 }; + struct SecCompClickEvent touch = { + .touchX = TestCommon::TEST_COORDINATE, + .touchY = TestCommon::TEST_COORDINATE, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TestCommon::TIME_CONVERSION_UNIT + }; + touch.extraInfo.dataSize = TestCommon::MAX_HMAC_SIZE; + touch.extraInfo.data = data; + EXPECT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, + SecCompKit::ReportSecurityComponentClickEvent(scId, locationInfo, touch, nullptr)); + system("param set sec.comp.enhance 0"); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/test_common.cpp b/interfaces/inner_api/security_component/test/unittest/src/test_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab8f3adbc58d0ac38fc40c92ccef9a0bfe82d171 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/test_common.cpp @@ -0,0 +1,168 @@ +/* + * 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 "test_common.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void TestCommon::BuildLocationComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} + +void TestCommon::BuildSaveComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = SAVE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} + +void TestCommon::BuildPasteComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = PASTE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/test/unittest/src/test_common.h b/interfaces/inner_api/security_component/test/unittest/src/test_common.h new file mode 100644 index 0000000000000000000000000000000000000000..f3b97b9bb2ff97eb3fe9656e08bcc9a36d968f31 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/test_common.h @@ -0,0 +1,45 @@ +/* + * 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 TEST_COMMON_H +#define TEST_COMMON_H +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class TestCommon { +public: + static constexpr float TEST_SIZE = 100.0; + static constexpr double TEST_COORDINATE = 100.0; + static constexpr double TEST_DIMENSION = 100.0; + static constexpr uint32_t TEST_COLOR = 0xffffffff; + static constexpr uint32_t TEST_COLOR_YELLOW = 0xffffff00; + static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; + static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; + static constexpr uint32_t TEST_DIFF_COLOR = 0; + static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; + static constexpr uint32_t MAX_HMAC_SIZE = 64; + static constexpr size_t MAX_CALLER_SIZE = 10; + + static void BuildLocationComponentInfo(nlohmann::json& jsonComponent); + static void BuildSaveComponentInfo(nlohmann::json& jsonComponent); + static void BuildPasteComponentInfo(nlohmann::json& jsonComponent); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // TEST_COMMON_H diff --git a/security_component.gni b/security_component.gni new file mode 100644 index 0000000000000000000000000000000000000000..f92bdb19a951625547cfe81a7d40c3ce5dff0707 --- /dev/null +++ b/security_component.gni @@ -0,0 +1,14 @@ +# 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. + +sec_comp_dir = "//base/security/security_component" diff --git a/services/security_component_service/sa/BUILD.gn b/services/security_component_service/sa/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4cc4ace089e6cb9d494c9d6ddb1937f547648b86 --- /dev/null +++ b/services/security_component_service/sa/BUILD.gn @@ -0,0 +1,91 @@ +# 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. + +import("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("security_component_service_config") { + include_dirs = [ + "sa_main", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] +} + +ohos_prebuilt_etc("security_component_service.rc") { + source = "security_component_service.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "security_component" +} + +ohos_shared_library("security_component_service") { + subsystem_name = "security" + part_name = "security_component" + + include_dirs = [ + "sa_main", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "sa_main/app_mgr_death_recipient.cpp", + "sa_main/app_state_observer.cpp", + "sa_main/delay_exit_task.cpp", + "sa_main/first_use_dialog.cpp", + "sa_main/sec_comp_entity.cpp", + "sa_main/sec_comp_info_helper.cpp", + "sa_main/sec_comp_manager.cpp", + "sa_main/sec_comp_perm_manager.cpp", + "sa_main/sec_comp_service.cpp", + "sa_main/sec_comp_stub.cpp", + "sa_main/sec_event_handler.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + cflags = [ "-DHILOG_ENABLE" ] + + deps = [ + ":security_component_service.rc", + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":security_component_service_config" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:runtime", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libdm", + ] +} diff --git a/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e37725810df2eee82a11734d6e4c7fc82064484 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp @@ -0,0 +1,28 @@ +/* + * 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_mgr_death_recipient.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void AppMgrDeathRecipient::OnRemoteDied(const wptr& object) +{ + SecCompManager::GetInstance().ExitWhenAppMgrDied(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..d4dc41c1dbe8328c7b1b7292d619ac2f70a04ac0 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h @@ -0,0 +1,33 @@ +/* + * 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 APP_MGR_DEATH_RECIPIENT_H +#define APP_MGR_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { +public: + AppMgrDeathRecipient() {} + virtual ~AppMgrDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // APP_MGR_DEATH_RECIPIENT_H + diff --git a/services/security_component_service/sa/sa_main/app_state_observer.cpp b/services/security_component_service/sa/sa_main/app_state_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be4fa4e23221265154929bd36e369f0c094202e9 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_state_observer.cpp @@ -0,0 +1,129 @@ +/* + * 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_state_observer.h" + +#include "sec_comp_log.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "AppStateObserver"}; +} + +AppStateObserver::AppStateObserver() +{ +} + +AppStateObserver::~AppStateObserver() +{ +} + +bool AppStateObserver::IsProcessForeground(int32_t pid, int32_t uid) +{ + Utils::UniqueReadGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (pid == iter->pid) { + return true; + } + + if ((iter->pid == -1) && (uid == iter->uid)) { + iter->pid = pid; + return true; + } + } + return false; +} + +void AppStateObserver::AddProcessToForegroundSet(int32_t pid, const SecCompProcessData& data) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (pid == -1) { + if (iter->uid == data.uid) { + SC_LOG_INFO(LABEL, "uid %{public}d is already in foreground", data.uid); + return; + } + } else if (pid == iter->pid) { + SC_LOG_INFO(LABEL, "pid %{public}d is already in foreground", pid); + return; + } + } + foregrandProcList_.emplace_back(data); +} + +void AppStateObserver::AddProcessToForegroundSet(const AppExecFwk::AppStateData& stateData) +{ + SecCompProcessData proc = { + .bundleName = stateData.bundleName, + .pid = stateData.pid, + .uid = stateData.uid + }; + AddProcessToForegroundSet(stateData.pid, proc); +} + +void AppStateObserver::AddProcessToForegroundSet(const AppExecFwk::ProcessData &processData) +{ + SecCompProcessData proc = { + .bundleName = processData.bundleName, + .pid = processData.pid, + .uid = processData.uid + }; + AddProcessToForegroundSet(processData.pid, proc); +} + +void AppStateObserver::RemoveProcessFromForegroundSet(const AppExecFwk::ProcessData &processData) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (processData.pid == iter->pid) { + foregrandProcList_.erase(iter); + return; + } + } +} + +void AppStateObserver::OnProcessStateChanged(const AppExecFwk::ProcessData &processData) +{ + if (processData.state == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) { + AddProcessToForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessForeground(processData.pid); + } else if (processData.state == AppExecFwk::AppProcessState::APP_STATE_BACKGROUND) { + RemoveProcessFromForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessBackground(processData.pid); + } +} + +void AppStateObserver::OnProcessDied(const AppExecFwk::ProcessData& processData) +{ + SC_LOG_INFO(LABEL, "OnProcessDied die %{public}s pid %{public}d", + processData.bundleName.c_str(), processData.pid); + RemoveProcessFromForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessDied(processData.pid); +} + +void AppStateObserver::DumpProcess(std::string& dumpStr) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + dumpStr.append("uid:" + std::to_string(iter->uid) + ", pid:" + std::to_string(iter->pid)); + dumpStr.append(", procName:" + iter->bundleName + "\n"); + } +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/app_state_observer.h b/services/security_component_service/sa/sa_main/app_state_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..56998a00217a643c25a230aec946f233f1a0b78f --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_state_observer.h @@ -0,0 +1,57 @@ +/* + * 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_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H +#define SECURITY_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H + +#include +#include +#include "app_mgr_interface.h" +#include "application_state_observer_stub.h" +#include "iremote_object.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompProcessData { + std::string bundleName; + int32_t pid = -1; + int32_t uid = -1; +}; + +class AppStateObserver : public AppExecFwk::ApplicationStateObserverStub { +public: + explicit AppStateObserver(); + virtual ~AppStateObserver(); + + void OnProcessStateChanged(const AppExecFwk::ProcessData& processData) override; + void OnProcessDied(const AppExecFwk::ProcessData& processData) override; + bool IsProcessForeground(int32_t pid, int32_t uid); + void AddProcessToForegroundSet(int32_t pid, const SecCompProcessData& data); + void AddProcessToForegroundSet(const AppExecFwk::ProcessData& processData); + void AddProcessToForegroundSet(const AppExecFwk::AppStateData& stateData); + void DumpProcess(std::string& dumpStr); + +private: + void RemoveProcessFromForegroundSet(const AppExecFwk::ProcessData& processData); + std::vector foregrandProcList_; + OHOS::Utils::RWLock fgProcLock_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + +#endif // SECURITY_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H + diff --git a/services/security_component_service/sa/sa_main/delay_exit_task.cpp b/services/security_component_service/sa/sa_main/delay_exit_task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d78873085860cc1f3c6c1f0d7f348fa65cea462 --- /dev/null +++ b/services/security_component_service/sa/sa_main/delay_exit_task.cpp @@ -0,0 +1,72 @@ +/* + * 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 "delay_exit_task.h" + +#include "sec_comp_log.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "DelayExitTask"}; +static const std::string DELAY_EXIT_TASK = "DelayExitTask"; +static const int32_t DELAY_EXIT_MILLISECONDS = 30 * 1000; // 30s +} + +DelayExitTask::DelayExitTask() +{ +} + +DelayExitTask& DelayExitTask::GetInstance() +{ + static DelayExitTask instance; + return instance; +} + +void DelayExitTask::Init(const std::shared_ptr& secHandler) +{ + secHandler_ = secHandler; +} + +void DelayExitTask::Start() +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + + std::function delayed = ([]() { + SecCompManager::GetInstance().ExitSaProcess(); + }); + + SC_LOG_INFO(LABEL, "Delay exit service after %{public}d ms", DELAY_EXIT_MILLISECONDS); + secHandler_->ProxyPostTask(delayed, DELAY_EXIT_TASK, DELAY_EXIT_MILLISECONDS); +} + +void DelayExitTask::Stop() +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + + SC_LOG_INFO(LABEL, "service delay exit handler stop"); + secHandler_->ProxyRemoveTask(DELAY_EXIT_TASK); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/delay_exit_task.h b/services/security_component_service/sa/sa_main/delay_exit_task.h new file mode 100644 index 0000000000000000000000000000000000000000..d4315df7ca61d32ebefc758239ae514b11e54d90 --- /dev/null +++ b/services/security_component_service/sa/sa_main/delay_exit_task.h @@ -0,0 +1,44 @@ +/* + * 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_COMPONENT_DELAY_EXIT_TASK_H +#define SECURITY_COMPONENT_DELAY_EXIT_TASK_H + +#include +#include +#include "nocopyable.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class DelayExitTask { +public: + static DelayExitTask& GetInstance(); + virtual ~DelayExitTask() = default; + + void Init(const std::shared_ptr& secHandler); + void Start(); + void Stop(); +private: + DelayExitTask(); + std::shared_ptr secHandler_; + + DISALLOW_COPY_AND_MOVE(DelayExitTask); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_DELAY_EXIT_TASK_H + diff --git a/services/security_component_service/sa/sa_main/first_use_dialog.cpp b/services/security_component_service/sa/sa_main/first_use_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6439824a8321fd106e6f216677d4c3c0dbd35529 --- /dev/null +++ b/services/security_component_service/sa/sa_main/first_use_dialog.cpp @@ -0,0 +1,297 @@ +/* + * 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 "first_use_dialog.h" + +#include +#include +#include +#include +#include +#include "ability_manager_client.h" +#include "accesstoken_kit.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "want_params_wrapper.h" +#include "want.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "FirstUseDialog"}; +static const std::string SEC_COMP_SRV_CFG_PATH = "/data/service/el1/public/security_component_service"; +static const std::string FIRST_USE_RECORD_JSON = SEC_COMP_SRV_CFG_PATH + "/first_use_record.json"; +static const std::string FIRST_USE_RECORD_TAG = "FirstUseRecord"; +static const std::string TOKEN_ID_TAG = "TokenId"; +static const std::string COMP_TYPE_TAG = "CompType"; + +const std::string GRANT_ABILITY_BUNDLE_NAME = "com.ohos.permissionmanager"; +const std::string GRANT_ABILITY_ABILITY_NAME = "com.ohos.permissionmanager.SecurityExtAbility"; +const std::string TYPE_KEY = "ohos.user.security.type"; +const std::string TOKEN_KEY = "ohos.ability.params.token"; + +constexpr uint32_t MAX_CFG_FILE_SIZE = 100 * 1024; // 100k +} + +bool FirstUseDialog::IsCfgDirExist(void) +{ + struct stat fstat = {}; + if (stat(SEC_COMP_SRV_CFG_PATH.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", SEC_COMP_SRV_CFG_PATH.c_str(), errno); + return false; + } + + if (!S_ISDIR(fstat.st_mode)) { + SC_LOG_ERROR(LABEL, "path %{public}s is not directory.", SEC_COMP_SRV_CFG_PATH.c_str()); + return false; + } + return true; +} + +bool FirstUseDialog::IsCfgFileExist(void) +{ + struct stat fstat = {}; + if (stat(FIRST_USE_RECORD_JSON.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + return true; +} + +bool FirstUseDialog::IsCfgFileValid(void) +{ + struct stat fstat = {}; + if (stat(FIRST_USE_RECORD_JSON.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + if (fstat.st_size > MAX_CFG_FILE_SIZE) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + return true; +} + +bool FirstUseDialog::ReadCfgContent(std::string& content) +{ + std::stringstream buffer; + std::ifstream i(FIRST_USE_RECORD_JSON); + if (!i.is_open()) { + SC_LOG_ERROR(LABEL, "cannot open file %{public}s, errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + buffer << i.rdbuf(); + content = buffer.str(); + i.close(); + return true; +} + +void FirstUseDialog::WriteCfgContent(const std::string& content) +{ + std::ofstream out(FIRST_USE_RECORD_JSON); + if (!out.is_open()) { + SC_LOG_ERROR(LABEL, "cannot open file %{public}s, errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return; + } + out << content; + out.close(); +} + +bool FirstUseDialog::ParseRecord(nlohmann::json& jsonRes, + AccessToken::AccessTokenID& id, uint64_t& type) +{ + if (jsonRes.find(TOKEN_ID_TAG) == jsonRes.end() || + !jsonRes.at(TOKEN_ID_TAG).is_number()) { + SC_LOG_ERROR(LABEL, "parse TokenId failed."); + return false; + } + id = jsonRes.at(TOKEN_ID_TAG).get(); + if (id == AccessToken::INVALID_TOKENID) { + SC_LOG_ERROR(LABEL, "TokenId is not invalid."); + return false; + } + + if (jsonRes.find(COMP_TYPE_TAG) == jsonRes.end() || + !jsonRes.at(COMP_TYPE_TAG).is_number()) { + SC_LOG_ERROR(LABEL, "parse CompType failed."); + return false; + } + type = jsonRes.at(COMP_TYPE_TAG).get(); + return true; +} + +void FirstUseDialog::ParseRecords(nlohmann::json& jsonRes) +{ + std::unique_lock lock(useMapMutex_); + if (jsonRes.find(FIRST_USE_RECORD_TAG) == jsonRes.end() || + !jsonRes.at(FIRST_USE_RECORD_TAG).is_array()) { + SC_LOG_ERROR(LABEL, "parse tag failed."); + return; + } + + nlohmann::json recordListJson = jsonRes.at(FIRST_USE_RECORD_TAG); + for (auto& recordJson : recordListJson) { + AccessToken::AccessTokenID id; + uint64_t type; + if (!ParseRecord(recordJson, id, type)) { + SC_LOG_ERROR(LABEL, "parse record failed."); + return; + } + firstUseMap_[id] = type; + } +} + +void FirstUseDialog::LoadFirstUseRecord(void) +{ + if (!IsCfgFileValid()) { + SC_LOG_INFO(LABEL, "first use record is invalid."); + return; + } + + std::string content; + if (!ReadCfgContent(content)) { + return; + } + + nlohmann::json jsonRes = nlohmann::json::parse(content, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "cfg info format is invalid"); + return; + } + + ParseRecords(jsonRes); +} + +void FirstUseDialog::SaveFirstUseRecord(void) +{ + SC_LOG_INFO(LABEL, "start save first_use_record json"); + if (!IsCfgDirExist()) { + SC_LOG_ERROR(LABEL, "dir %{public}s is not exist, errno %{public}d", + SEC_COMP_SRV_CFG_PATH.c_str(), errno); + return; + } + + if (!IsCfgFileExist()) { + if (creat(FIRST_USE_RECORD_JSON.c_str(), S_IRUSR | S_IWUSR) == -1) { + SC_LOG_ERROR(LABEL, "create %{public}s failed, errno %{public}d", + FIRST_USE_RECORD_JSON.c_str(), errno); + return; + } + } + + nlohmann::json jsonRes; + { + std::unique_lock lock(useMapMutex_); + nlohmann::json recordsJson; + for (auto iter = firstUseMap_.begin(); iter != firstUseMap_.end(); ++iter) { + AccessToken::AccessTokenID id = iter->first; + AccessToken::HapTokenInfo info; + if (AccessToken::AccessTokenKit::GetHapTokenInfo(id, info) != AccessToken::RET_SUCCESS) { + SC_LOG_INFO(LABEL, "token id %{public}d is not exist, do not update it.", id); + continue; + } + nlohmann::json recordJson; + recordJson[TOKEN_ID_TAG] = id; + recordJson[COMP_TYPE_TAG] = iter->second; + recordsJson.emplace_back(recordJson); + } + + jsonRes[FIRST_USE_RECORD_TAG] = recordsJson; + } + WriteCfgContent(jsonRes.dump()); +} + +void FirstUseDialog::StartDialogAbility(SecCompType type, sptr callerToken) +{ + int32_t typeNum; + if (type == LOCATION_COMPONENT) { + typeNum = 0; + } else if (type == SAVE_COMPONENT) { + typeNum = 1; + } else { + SC_LOG_ERROR(LABEL, "unknown type."); + return; + } + + AAFwk::Want want; + want.SetElementName(GRANT_ABILITY_BUNDLE_NAME, GRANT_ABILITY_ABILITY_NAME); + want.SetParam(TYPE_KEY, typeNum); + want.SetParam(TOKEN_KEY, callerToken); + int startRes = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, callerToken); + SC_LOG_INFO(LABEL, "start ability res %{public}d", startRes); +} + +void FirstUseDialog::SendSaveEventHandler(void) +{ + std::function delayed = ([this]() { + this->SaveFirstUseRecord(); + }); + + SC_LOG_INFO(LABEL, "Delay first_use_record json"); + secHandler_->ProxyPostTask(delayed); +} + +void FirstUseDialog::NotifyFirstUseDialog(AccessToken::AccessTokenID tokenId, SecCompType type, + sptr callerToken) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "event handler invalid."); + return; + } + if (callerToken == nullptr) { + SC_LOG_INFO(LABEL, "callerToken is null, no need to notify dialog"); + return; + } + + uint64_t typeMask; + if (type == LOCATION_COMPONENT) { + typeMask = LOCATION_BUTTON_FIRST_USE; + } else if (type == SAVE_COMPONENT) { + typeMask = SAVE_BUTTON_FIRST_USE; + } else { + SC_LOG_INFO(LABEL, "this type need not notify dialog to user"); + return; + } + + std::unique_lock lock(useMapMutex_); + auto iter = firstUseMap_.find(tokenId); + if (iter == firstUseMap_.end()) { + SC_LOG_INFO(LABEL, "has not use record, start dialog"); + StartDialogAbility(type, callerToken); + firstUseMap_[tokenId] = typeMask; + SendSaveEventHandler(); + return; + } + + uint64_t compTypes = firstUseMap_[tokenId]; + if ((compTypes & typeMask) == typeMask) { + SC_LOG_INFO(LABEL, "no need notify again."); + return; + } + StartDialogAbility(type, callerToken); + firstUseMap_[tokenId] |= typeMask; + SendSaveEventHandler(); +} + +void FirstUseDialog::Init(std::shared_ptr secHandler) +{ + SC_LOG_DEBUG(LABEL, "Init!!"); + secHandler_ = secHandler; + LoadFirstUseRecord(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/first_use_dialog.h b/services/security_component_service/sa/sa_main/first_use_dialog.h new file mode 100644 index 0000000000000000000000000000000000000000..fd04777b01dec61998d058e840c6f04b5305fe52 --- /dev/null +++ b/services/security_component_service/sa/sa_main/first_use_dialog.h @@ -0,0 +1,64 @@ +/* + * 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 FIRST_USE_DIALOG_H +#define FIRST_USE_DIALOG_H + +#include +#include +#include +#include +#include "access_token.h" +#include "iremote_object.h" +#include "nlohmann/json.hpp" +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr uint64_t LOCATION_BUTTON_FIRST_USE = 1 << 0; +constexpr uint64_t SAVE_BUTTON_FIRST_USE = 1 << 1; + +class FirstUseDialog final { +public: + FirstUseDialog() = default; + ~FirstUseDialog() = default; + void NotifyFirstUseDialog(AccessToken::AccessTokenID tokenId, SecCompType type, sptr callerToken); + void Init(std::shared_ptr secHandler); + +private: + bool IsCfgDirExist(void); + bool IsCfgFileExist(void); + bool IsCfgFileValid(void); + bool ReadCfgContent(std::string& content); + void WriteCfgContent(const std::string& content); + bool ParseRecord(nlohmann::json& jsonRes, + AccessToken::AccessTokenID& id, uint64_t& type); + void ParseRecords(nlohmann::json& jsonRes); + void LoadFirstUseRecord(void); + void SaveFirstUseRecord(void); + void StartDialogAbility(SecCompType type, sptr callerToken); + void SendSaveEventHandler(void); + + std::mutex useMapMutex_; + std::unordered_map firstUseMap_; + std::shared_ptr secHandler_; +}; +} // namespace SecurityComponentEnhance +} // namespace Security +} // namespace OHOS +#endif // FIRST_USE_DIALOG_H + diff --git a/services/security_component_service/sa/sa_main/sec_comp_entity.cpp b/services/security_component_service/sa/sa_main/sec_comp_entity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1bc9e4715a9c359519d661ca135bc3533a735e0 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_entity.cpp @@ -0,0 +1,85 @@ +/* + * 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 "sec_comp_entity.h" + +#include +#include "hisysevent.h" +#include "ipc_skeleton.h" +#include "sec_comp_err.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_info_helper.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEntity"}; +static constexpr uint64_t MAX_TOUCH_INTERVAL = 1000000L; // 1000ms +static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; +} + +int32_t SecCompEntity::RevokeTempPermission() +{ + if (!isGrant_) { + SC_LOG_ERROR(LABEL, "security component is not granted"); + return SC_OK; + } + isGrant_ = false; + return SecCompInfoHelper::RevokeTempPermission(tokenId_, componentInfo_); +} + +int32_t SecCompEntity::GrantTempPermission() +{ + isGrant_ = true; + return SecCompInfoHelper::GrantTempPermission(tokenId_, componentInfo_); +} + +bool SecCompEntity::CompareComponentBasicInfo(SecCompBase* other, bool isRectCheck) const +{ + return componentInfo_->CompareComponentBasicInfo(other, isRectCheck); +} + +bool SecCompEntity::CheckTouchInfo(const SecCompClickEvent& touchInfo) const +{ + auto current = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + if (touchInfo.timestamp < current - MAX_TOUCH_INTERVAL || touchInfo.timestamp > current) { + SC_LOG_ERROR(LABEL, "touch timestamp invalid touchInfo. timestamp: %{public}llu, current: %{public}llu", + static_cast(touchInfo.timestamp), static_cast(current)); + return false; + } + + if (!componentInfo_->rect_.IsInRect(touchInfo.touchX, touchInfo.touchY)) { + SC_LOG_ERROR(LABEL, "touch point is not in component rect"); + return false; + } + + int32_t res = SecCompEnhanceAdapter::CheckExtraInfo(touchInfo); + if ((res != SC_OK) && (res != SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE)) { + SC_LOG_ERROR(LABEL, "HMAC checkout failed," + "touchX:%{public}f, touchY:%{public}f, timestamp:%{public}llu, dataSize:%{public}d", + touchInfo.touchX, touchInfo.touchY, static_cast(touchInfo.timestamp), + touchInfo.extraInfo.dataSize); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CLICK_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId_, "SC_TYPE", componentInfo_->type_); + return false; + } + return true; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_entity.h b/services/security_component_service/sa/sa_main/sec_comp_entity.h new file mode 100644 index 0000000000000000000000000000000000000000..d95f6f6d64a20ed4d6a1bf7bb540d8865df4a022 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_entity.h @@ -0,0 +1,80 @@ +/* + * 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_COMPONENT_ENTITY_H +#define SECURITY_COMPONENT_ENTITY_H + +#include +#include "accesstoken_kit.h" +#include "sec_comp_base.h" +#include "sec_comp_info.h" +#include "sec_comp_perm_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEntity { +public: + SecCompEntity(std::shared_ptr component, + AccessToken::AccessTokenID token, int32_t scId) : componentInfo_(component), + tokenId_(token), scId_(scId){}; + ~SecCompEntity() = default; + int32_t RevokeTempPermission(); + int32_t GrantTempPermission(); + int32_t GetScId() const + { + return scId_; + }; + + SecCompType GetType() const + { + if (componentInfo_ == nullptr) { + return UNKNOWN_SC_TYPE; + } + return componentInfo_->type_; + }; + + bool IsGrant() const + { + return isGrant_; + } + + std::shared_ptr GetComponentInfo() const + { + return componentInfo_; + }; + + void SetComponentInfo(const std::shared_ptr& com) + { + componentInfo_ = com; + }; + + std::shared_ptr GetComponentInfo() + { + return componentInfo_; + }; + + bool CompareComponentBasicInfo(SecCompBase* other, bool isRectCheck) const; + bool CheckTouchInfo(const SecCompClickEvent& touchInfo) const; + +private: + std::shared_ptr componentInfo_; + bool isGrant_ = false; + AccessToken::AccessTokenID tokenId_; + int32_t scId_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENTITY_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp b/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7058200bbaae92dfbea3c4e77d045f86a357372e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp @@ -0,0 +1,272 @@ +/* + * 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 "sec_comp_info_helper.h" + +#include "display.h" +#include "display_info.h" +#include "display_manager.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_service.h" +#include "sec_comp_tool.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompInfoHelper"}; +static constexpr double MAX_RECT_PERCENT = 0.1F; // 10% +static constexpr double ZERO_OFFSET = 0.0F; +static std::mutex g_renderLock; +} + +SecCompBase* SecCompInfoHelper::ParseComponent(SecCompType type, const nlohmann::json& jsonComponent) +{ + SecCompBase* comp = nullptr; + switch (type) { + case LOCATION_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + case PASTE_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + case SAVE_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + default: + SC_LOG_ERROR(LABEL, "Parse component type unknown"); + break; + } + if (comp == nullptr) { + SC_LOG_ERROR(LABEL, "Parse component failed"); + return comp; + } + + comp->SetValid(CheckComponentValid(comp)); + return comp; +} + +static bool GetScreenSize(double& width, double& height) +{ + sptr display = + OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplaySync(); + if (display == nullptr) { + SC_LOG_ERROR(LABEL, "Get display manager failed"); + return false; + } + + auto info = display->GetDisplayInfo(); + if (info == nullptr) { + SC_LOG_ERROR(LABEL, "Get display info failed"); + return false; + } + + width = static_cast(info->GetWidth()); + height = static_cast(info->GetHeight()); + SC_LOG_DEBUG(LABEL, "display manager Screen width %{public}f height %{public}f", + width, height); + return true; +} + +bool SecCompInfoHelper::CheckRectValid(const SecCompRect& rect, const SecCompRect& windowRect) +{ + double curScreenWidth = 0.0F; + double curScreenHeight = 0.0F; + if (!GetScreenSize(curScreenWidth, curScreenHeight)) { + SC_LOG_ERROR(LABEL, "Get screen size is invalid"); + return false; + } + + if (GreatOrEqual(0.0, rect.width_) || GreatOrEqual(0.0, rect.height_)) { + SC_LOG_ERROR(LABEL, "width or height is <= 0"); + return false; + } + + if (GreatNotEqual(ZERO_OFFSET, rect.x_) || GreatNotEqual(ZERO_OFFSET, rect.y_) || + GreatNotEqual(rect.x_, curScreenWidth) || GreatNotEqual(rect.y_, curScreenHeight)) { + SC_LOG_ERROR(LABEL, "start point is out of screen"); + return false; + } + + if (GreatOrEqual((rect.x_ + rect.width_), curScreenWidth) || + GreatOrEqual((rect.y_ + rect.height_), curScreenHeight)) { + SC_LOG_ERROR(LABEL, "rect is out of screen"); + return false; + } + + if (GreatNotEqual(windowRect.x_, rect.x_) || GreatNotEqual(windowRect.y_, rect.y_) || + GreatNotEqual(rect.width_, windowRect.width_) || GreatNotEqual(rect.height_, windowRect.height_)) { + SC_LOG_ERROR(LABEL, "rect is out of window"); + return false; + } + + // check rect > 10% + if (GreatOrEqual((rect.width_ * rect.height_), (curScreenWidth * curScreenHeight * MAX_RECT_PERCENT))) { + SC_LOG_ERROR(LABEL, "rect area is too large"); + return false; + } + SC_LOG_DEBUG(LABEL, "check component rect success."); + return true; +} + +static bool CheckSecCompBaseButton(const SecCompBase* comp) +{ + if ((comp->text_ < 0) && (comp->icon_ < 0)) { + SC_LOG_INFO(LABEL, "both text and icon do not exist."); + return false; + } + if ((comp->text_ >= 0) && comp->fontSize_ < MIN_FONT_SIZE) { + SC_LOG_INFO(LABEL, "font size invalid."); + return false; + } + if ((comp->icon_ >= 0) && comp->iconSize_ < MIN_ICON_SIZE) { + SC_LOG_INFO(LABEL, "icon size invalid."); + return false; + } + + if ((comp->bg_ != SecCompBackground::NO_BG_TYPE) && + (((comp->text_ != NO_TEXT) && (IsColorSimilar(comp->fontColor_, comp->bgColor_))) || + ((comp->icon_ != NO_ICON) && (IsColorSimilar(comp->iconColor_, comp->bgColor_))))) { + SC_LOG_INFO(LABEL, "fontColor or iconColor is similar whith backgroundColor."); + return false; + } + + if (comp->bg_ == SecCompBackground::NO_BG_TYPE && + ((comp->padding_.top != MIN_PADDING_WITHOUT_BG) || (comp->padding_.right != MIN_PADDING_WITHOUT_BG) || + (comp->padding_.bottom != MIN_PADDING_WITHOUT_BG) || (comp->padding_.left != MIN_PADDING_WITHOUT_BG))) { + SC_LOG_INFO(LABEL, "padding can not change without background."); + return false; + } + + return true; +} + +static bool CheckSecCompBase(const SecCompBase* comp) +{ + if (comp->parentEffect_) { + SC_LOG_ERROR(LABEL, "parentEffect is active, security component invalid."); + return false; + } + + if ((comp->padding_.top < MIN_PADDING_SIZE) || (comp->padding_.right < MIN_PADDING_SIZE) || + (comp->padding_.bottom < MIN_PADDING_SIZE) || (comp->padding_.left < MIN_PADDING_SIZE) || + (comp->textIconSpace_ < MIN_PADDING_SIZE)) { + SC_LOG_ERROR(LABEL, "size is invalid."); + return false; + } + + if (((comp->bg_ != SecCompBackground::NO_BG_TYPE) && (IsColorTransparent(comp->bgColor_))) || + ((comp->text_ != NO_TEXT) && (IsColorTransparent(comp->fontColor_))) || + ((comp->icon_ != NO_ICON) && (IsColorTransparent(comp->iconColor_)))) { + SC_LOG_ERROR(LABEL, "bgColor or fontColor or iconColor is too transparent."); + return false; + } + if (!CheckSecCompBaseButton(comp)) { + return false; + } + return true; +} + +bool SecCompInfoHelper::CheckComponentValid(const SecCompBase* comp) +{ + if ((comp == nullptr) || !IsComponentTypeValid(comp->type_)) { + SC_LOG_INFO(LABEL, "comp is null or type is invalid."); + return false; + } + + if (!CheckSecCompBase(comp)) { + SC_LOG_INFO(LABEL, "SecComp base is invalid."); + return false; + } + + return true; +} + +int32_t SecCompInfoHelper::GrantTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo) +{ + if ((tokenId <= 0) || (componentInfo == nullptr)) { + SC_LOG_ERROR(LABEL, "revoke component is null"); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + + SecCompType type = componentInfo->type_; + switch (type) { + case LOCATION_COMPONENT: + { + int32_t res = SecCompPermManager::GetInstance().GrantLocationPermission(tokenId, + "ohos.permission.APPROXIMATELY_LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if (res != SC_OK) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + res = SecCompPermManager::GetInstance().GrantLocationPermission(tokenId, "ohos.permission.LOCATION", + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if (res != SC_OK) { + SecCompPermManager::GetInstance().RevokeLocationPermission( + tokenId, "ohos.permission.APPROXIMATELY_LOCATION", + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + return SC_OK; + } + case PASTE_COMPONENT: + SC_LOG_DEBUG(LABEL, "grant paste permission"); + return SC_OK; + case SAVE_COMPONENT: + SC_LOG_DEBUG(LABEL, "grant save permission"); + return SecCompPermManager::GetInstance().GrantTempSavePermission(tokenId); + default: + SC_LOG_ERROR(LABEL, "Parse component type unknown"); + break; + } + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; +} + +int32_t SecCompInfoHelper::RevokeTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo) +{ + if (componentInfo == nullptr) { + SC_LOG_ERROR(LABEL, "revoke component is null"); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + + SecCompType type = componentInfo->type_; + switch (type) { + case LOCATION_COMPONENT: + { + int32_t locationRes = SecCompPermManager::GetInstance().RevokeLocationPermission(tokenId, + "ohos.permission.LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + int32_t approxLocationRes = SecCompPermManager::GetInstance().RevokeLocationPermission(tokenId, + "ohos.permission.APPROXIMATELY_LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if ((locationRes != SC_OK) || (approxLocationRes != SC_OK)) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + return SC_OK; + } + case PASTE_COMPONENT: + SC_LOG_DEBUG(LABEL, "revoke paste permission"); + return SC_OK; + default: + SC_LOG_ERROR(LABEL, "revoke component type unknown"); + break; + } + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_info_helper.h b/services/security_component_service/sa/sa_main/sec_comp_info_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..463c9fc14c8a0c1dc25f9aea012bed6f0305abd0 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_info_helper.h @@ -0,0 +1,51 @@ +/* + * 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 I_SECURITY_COMPONENT_INFO_HELPER_H +#define I_SECURITY_COMPONENT_INFO_HELPER_H + +#include "accesstoken_kit.h" +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" +#include "sec_comp_perm_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +template +T* ConstructComponent(const nlohmann::json& jsonComponent) +{ + T *componentPtr = new (std::nothrow)T(); + if ((componentPtr != nullptr) && !componentPtr->FromJson(jsonComponent)) { + delete componentPtr; + return nullptr; + } + return componentPtr; +} + +class SecCompInfoHelper { +public: + static SecCompBase* ParseComponent(SecCompType type, const nlohmann::json& jsonComponent); + static int32_t RevokeTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo); + static int32_t GrantTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo); + static bool CheckComponentValid(const SecCompBase* comp); + static bool CheckRectValid(const SecCompRect& rect, const SecCompRect& windowRect); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_INFO_HELPER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_manager.cpp b/services/security_component_service/sa/sa_main/sec_comp_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49d0785e67b2978dac0b65b9e4b6f0fb90af913f --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_manager.cpp @@ -0,0 +1,524 @@ +/* + * 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 "sec_comp_manager.h" + +#include "delay_exit_task.h" +#include "hisysevent.h" +#include "i_sec_comp_service.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_info_helper.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompManager"}; +static constexpr int32_t SC_ID_START = 1000; +static constexpr int32_t MAX_INT_NUM = 0x7fffffff; +static constexpr int32_t ROOT_UID = 0; +} + +SecCompManager::SecCompManager() +{ + scIdStart_ = SC_ID_START; +} + +SecCompManager& SecCompManager::GetInstance() +{ + static SecCompManager instance; + return instance; +} + +int32_t SecCompManager::CreateScId() +{ + std::lock_guard lock(scIdMtx_); + if (scIdStart_ == MAX_INT_NUM) { + scIdStart_ = SC_ID_START; + } else { + scIdStart_++; + } + return scIdStart_; +} + +int32_t SecCompManager::AddSecurityComponentToList(int32_t pid, const SecCompEntity& newEntity) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + if (isSaExit_) { + SC_LOG_ERROR(LABEL, "SA is exiting, retry..."); + return SC_SERVICE_ERROR_SERVICE_NOT_EXIST; + } + + auto iter = componentMap_.find(pid); + if (iter != componentMap_.end()) { + iter->second.isForeground = true; + iter->second.compList.emplace_back(newEntity); + SecCompEnhanceAdapter::EnableInputEnhance(); + return SC_OK; + } + + ProcessCompInfos newProcess; + newProcess.isForeground = true; + newProcess.compList.emplace_back(newEntity); + componentMap_[pid] = newProcess; + SecCompEnhanceAdapter::EnableInputEnhance(); + return SC_OK; +} + +int32_t SecCompManager::DeleteSecurityComponentFromList(int32_t pid, int32_t scId) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + SC_LOG_ERROR(LABEL, "Can not find registered process"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + if (it->GetScId() == scId) { + it->RevokeTempPermission(); + list.erase(it); + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + return SC_OK; + } + } + SC_LOG_ERROR(LABEL, "Can not find component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; +} + +bool SecCompManager::IsInMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + if (IPCSkeleton::GetCallingUid() == ROOT_UID) { + return false; + } + return (maliciousAppList_.find(pid) != maliciousAppList_.end()); +} + +void SecCompManager::AddAppToMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + maliciousAppList_.insert(pid); +} + +void SecCompManager::RemoveAppFromMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + maliciousAppList_.erase(pid); +} + +bool SecCompManager::IsMaliciousAppListEmpty() +{ + std::lock_guard lock(maliciousMtx_); + return (maliciousAppList_.size() == 0); +} + +static std::string TransformCallBackResult(enum SCErrCode error) +{ + std::string errMsg = ""; + switch (error) { + case SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE: + errMsg = "enhance do not exist"; + break; + case SC_ENHANCE_ERROR_VALUE_INVALID: + errMsg = "value is invalid"; + break; + case SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST: + errMsg = "callback do not exist"; + break; + case SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL: + errMsg = "callback operate fail"; + break; + case SC_SERVICE_ERROR_COMPONENT_INFO_INVALID: + errMsg = "component info invalid"; + break; + case SC_ENHANCE_ERROR_CALLBACK_CHECK_FAIL: + errMsg = "callback check fail"; + break; + default: + errMsg = "unknown error"; + break; + } + return errMsg; +} + +SecCompEntity* SecCompManager::GetSecurityComponentFromList(int32_t pid, int32_t scId) +{ + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return nullptr; + } + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + if (it->GetScId() == scId) { + return std::addressof(*it); + } + } + return nullptr; +} + +bool SecCompManager::IsForegroundCompExist() +{ + return std::any_of(componentMap_.begin(), componentMap_.end(), [](const auto & iter) { + return (iter.second.isForeground) && (iter.second.compList.size() > 0); + }); +} + +void SecCompManager::NotifyProcessForeground(int32_t pid) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + iter->second.isForeground = true; + if (IsForegroundCompExist()) { + SecCompEnhanceAdapter::EnableInputEnhance(); + } + + SC_LOG_INFO(LABEL, "App pid %{public}d to foreground", pid); +} + +void SecCompManager::NotifyProcessBackground(int32_t pid) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + it->RevokeTempPermission(); + } + + iter->second.isForeground = false; + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + SC_LOG_INFO(LABEL, "App pid %{public}d to background", pid); +} + +void SecCompManager::NotifyProcessDied(int32_t pid) +{ + // notify enhance process died. + SecCompEnhanceAdapter::NotifyProcessDied(pid); + + RemoveAppFromMaliciousAppList(pid); + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + SC_LOG_INFO(LABEL, "App pid %{public}d died", pid); + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + it->RevokeTempPermission(); + } + list.clear(); + componentMap_.erase(pid); + + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + + DelayExitTask::GetInstance().Start(); +} + +void SecCompManager::ExitSaProcess() +{ + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + if (!componentMap_.empty() || !IsMaliciousAppListEmpty()) { + SC_LOG_INFO(LABEL, "Apps using security component still exist, no exit sa"); + return; + } + isSaExit_ = true; + SecCompEnhanceAdapter::DisableInputEnhance(); + SecCompEnhanceAdapter::ExistEnhanceService(); + + SC_LOG_INFO(LABEL, "All processes using security component died, start sa exit"); + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get SystemAbilityManager."); + return; + } + int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (ret != SC_OK) { + SC_LOG_ERROR(LABEL, "Failed to UnloadSystemAbility service! errcode=%{public}d", ret); + return; + } + SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!"); +} + +void SecCompManager::ExitWhenAppMgrDied() +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) { + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + it->RevokeTempPermission(); + } + list.clear(); + } + componentMap_.clear(); + + // no need exit enhance service, only disable input enhance. + SecCompEnhanceAdapter::DisableInputEnhance(); + isSaExit_ = true; + + SC_LOG_INFO(LABEL, "app mgr died, start sa exit"); + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + SC_LOG_ERROR(LABEL, "failed to get SystemAbilityManager."); + return; + } + int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (ret != SC_OK) { + SC_LOG_ERROR(LABEL, "failed to UnloadSystemAbility service! errcode=%{public}d", ret); + return; + } + SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!"); +} + +void SecCompManager::SendCheckInfoEnhanceSysEvent(int32_t scId, + SecCompType type, const std::string& scene, int32_t res) +{ + if (res == SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CHALLENGE_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", type, "CALL_SCENE", + scene); + } else { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLBACK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_TYPE", type, + "CALL_SCENE", scene, "REASON", TransformCallBackResult(static_cast(res))); + } +} + +int32_t SecCompManager::RegisterSecurityComponent(SecCompType type, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller, int32_t& scId) +{ + DelayExitTask::GetInstance().Stop(); + SC_LOG_DEBUG(LABEL, "PID: %{public}d, register security component", caller.pid); + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + SecCompBase* componentPtr = SecCompInfoHelper::ParseComponent(type, jsonComponent); + std::shared_ptr component(componentPtr); + if (component == nullptr) { + SC_LOG_ERROR(LABEL, "Parse component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "REGITSTER", "SC_TYPE", type); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, component, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(INVALID_SC_ID, type, "REGISTER", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + int32_t registerId = CreateScId(); + SecCompEntity entity(component, caller.tokenId, registerId); + int32_t ret = AddSecurityComponentToList(caller.pid, entity); + if (ret == SC_OK) { + scId = registerId; + } else { + SC_LOG_ERROR(LABEL, "Register security component failed"); + scId = INVALID_SC_ID; + } + return ret; +} + +int32_t SecCompManager::UpdateSecurityComponent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, update security component", caller.pid); + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + SecCompEntity* sc = GetSecurityComponentFromList(caller.pid, scId); + if (sc == nullptr) { + SC_LOG_ERROR(LABEL, "Can not find target component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent); + std::shared_ptr reportComponentInfo(report); + if (reportComponentInfo == nullptr) { + SC_LOG_ERROR(LABEL, "Update component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "UPDATE", + "SC_TYPE", sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, reportComponentInfo, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "UPDATE", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + sc->SetComponentInfo(reportComponentInfo); + return SC_OK; +} + +int32_t SecCompManager::UnregisterSecurityComponent(int32_t scId, const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, unregister security component", caller.pid); + if (scId < 0) { + SC_LOG_ERROR(LABEL, "ScId is invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + return DeleteSecurityComponentFromList(caller.pid, scId); +} + +int32_t SecCompManager::CheckClickSecurityComponentInfo(SecCompEntity* sc, int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, Check security component", caller.pid); + SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent); + std::shared_ptr reportComponentInfo(report); + if ((reportComponentInfo == nullptr) || (!reportComponentInfo->GetValid())) { + SC_LOG_ERROR(LABEL, "report component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE", + sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + if ((!SecCompInfoHelper::CheckRectValid(reportComponentInfo->rect_, reportComponentInfo->windowRect_))) { + SC_LOG_ERROR(LABEL, "compare component info failed."); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE", + sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, reportComponentInfo, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "CLICK", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + sc->SetComponentInfo(reportComponentInfo); + return SC_OK; +} + +int32_t SecCompManager::ReportSecurityComponentClickEvent(int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller, + const SecCompClickEvent& touchInfo, sptr callerToken) +{ + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + SecCompEntity* sc = GetSecurityComponentFromList(caller.pid, scId); + if (sc == nullptr) { + SC_LOG_ERROR(LABEL, "Can not find target component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + + int32_t res = CheckClickSecurityComponentInfo(sc, scId, jsonComponent, caller); + if (res != SC_OK) { + return res; + } + + if (!sc->CheckTouchInfo(touchInfo)) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CLICK_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + AddAppToMaliciousAppList(caller.pid); + return SC_SERVICE_ERROR_CLICK_EVENT_INVALID; + } + res = sc->GrantTempPermission(); + if (res != SC_OK) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "TEMP_GRANT_FAILED", + HiviewDFX::HiSysEvent::EventType::FAULT, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + return res; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "TEMP_GRANT_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + firstUseDialog_.NotifyFirstUseDialog(caller.tokenId, sc->GetType(), callerToken); + return res; +} + +bool SecCompManager::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + if (SecCompPermManager::GetInstance().RevokeTempSavePermission(tokenId) == SC_OK) { + return true; + } + return false; +} + +void SecCompManager::DumpSecComp(std::string& dumpStr) +{ + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) { + dumpStr.append("pid:" + std::to_string(iter->first) + "\n"); + for (auto compIter = iter->second.compList.begin(); compIter != iter->second.compList.end(); compIter ++) { + nlohmann::json json; + compIter->GetComponentInfo()->ToJson(json); + dumpStr.append(" scId:" + std::to_string(compIter->GetScId()) + + ", isGrant:" + std::to_string(compIter->IsGrant()) + ", " + json.dump() + "\n"); + } + } +} + +bool SecCompManager::Initialize() +{ + SC_LOG_DEBUG(LABEL, "Initialize!!"); + SecCompEnhanceAdapter::StartEnhanceService(); + + secRunner_ = AppExecFwk::EventRunner::Create(true); + if (!secRunner_) { + SC_LOG_ERROR(LABEL, "failed to create a recvRunner."); + return false; + } + + secHandler_ = std::make_shared(secRunner_); + DelayExitTask::GetInstance().Init(secHandler_); + firstUseDialog_.Init(secHandler_); + + return SecCompPermManager::GetInstance().InitEventHandler(secHandler_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_manager.h b/services/security_component_service/sa/sa_main/sec_comp_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..3c0848c8b21a8ab54a46654ccf0b53983d2aa4f7 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_manager.h @@ -0,0 +1,101 @@ +/* + * 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_COMPONENT_MANAGER_H +#define SECURITY_COMPONENT_MANAGER_H + +#include +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "app_state_observer.h" +#include "first_use_dialog.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "sec_comp_base.h" +#include "sec_comp_entity.h" +#include "sec_comp_info.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompCallerInfo { + AccessToken::AccessTokenID tokenId; + int32_t uid; + int32_t pid; +}; + +struct ProcessCompInfos { + std::vector compList; + bool isForeground = false; +}; + +class SecCompManager { +public: + static SecCompManager& GetInstance(); + virtual ~SecCompManager() = default; + + int32_t RegisterSecurityComponent(SecCompType type, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller, int32_t& scId); + int32_t UpdateSecurityComponent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller); + int32_t UnregisterSecurityComponent(int32_t scId, const SecCompCallerInfo& caller); + int32_t ReportSecurityComponentClickEvent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller, const SecCompClickEvent& touchInfo, sptr callerToken); + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + void NotifyProcessForeground(int32_t pid); + void NotifyProcessBackground(int32_t pid); + void NotifyProcessDied(int32_t pid); + void DumpSecComp(std::string& dumpStr); + bool Initialize(); + void ExitSaProcess(); + void ExitWhenAppMgrDied(); + +private: + SecCompManager(); + bool IsForegroundCompExist(); + int32_t AddSecurityComponentToList(int32_t pid, const SecCompEntity& newEntity); + int32_t DeleteSecurityComponentFromList(int32_t pid, int32_t scId); + SecCompEntity* GetSecurityComponentFromList(int32_t pid, int32_t scId); + int32_t CheckClickSecurityComponentInfo(SecCompEntity* sc, int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller); + bool IsInMaliciousAppList(int32_t pid); + void AddAppToMaliciousAppList(int32_t pid); + void RemoveAppFromMaliciousAppList(int32_t pid); + bool IsMaliciousAppListEmpty(); + void SendCheckInfoEnhanceSysEvent(int32_t scId, + SecCompType type, const std::string& scene, int32_t res); + int32_t CreateScId(); + + OHOS::Utils::RWLock componentInfoLock_; + std::mutex scIdMtx_; + std::unordered_map componentMap_; + int32_t scIdStart_; + bool isSaExit_ = false; + + std::shared_ptr secRunner_; + std::shared_ptr secHandler_; + std::set maliciousAppList_; // pid set + std::mutex maliciousMtx_; + FirstUseDialog firstUseDialog_; + + DISALLOW_COPY_AND_MOVE(SecCompManager); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_MANAGER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c10b7adb4f1cc408c581f1d715f674a9aaaf547 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp @@ -0,0 +1,132 @@ +/* + * 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 "sec_comp_perm_manager.h" + +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_service.h" +#include "sec_comp_tool.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompPermManager"}; +static const int32_t WAIT_MILLISECONDS = 5 * 1000; +} + +SecCompPermManager& SecCompPermManager::GetInstance() +{ + static SecCompPermManager instance; + return instance; +} + +bool SecCompPermManager::DelayRevokePermission(AccessToken::AccessTokenID tokenId, const std::string& taskName) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return false; + } + + std::function delayed = ([tokenId]() { + SC_LOG_DEBUG(LABEL, "delay revoke save permission"); + SecCompPermManager::GetInstance().RevokeTempSavePermission(tokenId); + }); + + SC_LOG_DEBUG(LABEL, "revoke save permission after %{public}d ms", WAIT_MILLISECONDS); + secHandler_->ProxyPostTask(delayed, taskName, WAIT_MILLISECONDS); + return true; +} + +bool SecCompPermManager::RevokeSavePermissionTask(const std::string& taskName) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return false; + } + + SC_LOG_DEBUG(LABEL, "revoke save permission task name:%{public}s", taskName.c_str()); + secHandler_->ProxyRemoveTask(taskName); + return true; +} + +int32_t SecCompPermManager::GrantLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag) +{ + int32_t res = AccessToken::AccessTokenKit::GrantPermission(tokenId, permissionName, + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + SC_LOG_INFO(LABEL, "grant permission res: %{public}d, permission: %{public}s, tokenId:%{public}d", + res, permissionName.c_str(), tokenId); + return res; +} + +int32_t SecCompPermManager::RevokeLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag) +{ + int32_t res = AccessToken::AccessTokenKit::RevokePermission(tokenId, permissionName, + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + SC_LOG_INFO(LABEL, "revoke permission res: %{public}d, permission: %{public}s, tokenId:%{public}d", + res, permissionName.c_str(), tokenId); + return res; +} + +int32_t SecCompPermManager::GrantTempSavePermission(AccessToken::AccessTokenID tokenId) +{ + auto current = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()); + std::string taskName = std::to_string(tokenId) + std::to_string(current); + if (!DelayRevokePermission(tokenId, taskName)) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + std::lock_guard lock(mutex_); + taskQue_.push_back(taskName); + applySaveCountMap_[tokenId]++; + SC_LOG_DEBUG(LABEL, "tokenId: %{public}d current permission apply counts is: %{public}d.", + tokenId, applySaveCountMap_[tokenId]); + return SC_OK; +} + +int32_t SecCompPermManager::RevokeTempSavePermission(AccessToken::AccessTokenID tokenId) +{ + std::lock_guard lock(mutex_); + auto iter = applySaveCountMap_.find(tokenId); + if (iter == applySaveCountMap_.end() || applySaveCountMap_[tokenId] == 0) { + SC_LOG_ERROR(LABEL, "This hap has no permissions to save files."); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + std::string taskName = taskQue_.front(); + if (!RevokeSavePermissionTask(taskName)) { + return false; + } + taskQue_.pop_front(); + SC_LOG_DEBUG(LABEL, "tokenId: %{public}d current permission apply counts is: %{public}d.", + tokenId, applySaveCountMap_[tokenId]); + if ((--applySaveCountMap_[tokenId]) == 0) { + applySaveCountMap_.erase(tokenId); + } + return SC_OK; +} + +bool SecCompPermManager::InitEventHandler(const std::shared_ptr& secHandler) +{ + secHandler_ = secHandler; + return true; +} + +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..0cd7f76808ca4a3777a2638a5287da914ba723c4 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h @@ -0,0 +1,57 @@ +/* + * 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_COMPONENT_PERMISSION_MANAGER_H +#define SECURITY_COMPONENT_PERMISSION_MANAGER_H + +#include +#include +#include "accesstoken_kit.h" +#include "rwlock.h" +#include "sec_comp_base.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompPermManager { +public: + SecCompPermManager() = default; + virtual ~SecCompPermManager() = default; + static SecCompPermManager& GetInstance(); + + int32_t GrantLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag); + int32_t RevokeLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag); + + int32_t GrantTempSavePermission(AccessToken::AccessTokenID tokenId); + int32_t RevokeTempSavePermission(AccessToken::AccessTokenID tokenId); + + bool InitEventHandler(const std::shared_ptr& secHandler); + std::shared_ptr GetSecEventHandler() const; + +private: + bool DelayRevokePermission(AccessToken::AccessTokenID tokenId, const std::string& taskName); + bool RevokeSavePermissionTask(const std::string& taskName); + + std::unordered_map applySaveCountMap_; + std::deque taskQue_; + std::mutex mutex_; + std::shared_ptr secHandler_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_PERMISSION_MANAGER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_service.cpp b/services/security_component_service/sa/sa_main/sec_comp_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40aad2dae403765f53eb9eb108b83f929d133f5a --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_service.cpp @@ -0,0 +1,284 @@ +/* + * 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 "sec_comp_service.h" + +#include + +#include "app_mgr_death_recipient.h" +#include "hisysevent.h" +#include "hitrace_meter.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_manager.h" +#include "sec_comp_log.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompService"}; +static const int32_t ROOT_UID = 0; +} + +REGISTER_SYSTEM_ABILITY_BY_ID(SecCompService, SA_ID_SECURITY_COMPONENT_SERVICE, true); + +SecCompService::SecCompService(int32_t saId, bool runOnCreate) + : SystemAbility(saId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START) +{ +} + +SecCompService::~SecCompService() +{ +} + +void SecCompService::OnStart() +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentOnStart"); + if (state_ == ServiceRunningState::STATE_RUNNING) { + SC_LOG_INFO(LABEL, "SecCompService has already started!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + SC_LOG_INFO(LABEL, "SecCompService is starting"); + if (!RegisterAppStateObserver()) { + SC_LOG_ERROR(LABEL, "Failed to register app state observer!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + if (!Initialize()) { + SC_LOG_ERROR(LABEL, "Failed to initialize"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(this); + if (!ret) { + SC_LOG_ERROR(LABEL, "Failed to publish service!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "SERVICE_INIT_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", getpid()); + SC_LOG_INFO(LABEL, "Congratulations, SecCompService start successfully!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); +} + +void SecCompService::OnStop() +{ + SC_LOG_INFO(LABEL, "Stop service"); + state_ = ServiceRunningState::STATE_NOT_START; + UnregisterAppStateObserver(); + iAppMgr_ = nullptr; + appStateObserver_ = nullptr; +} + +bool SecCompService::RegisterAppStateObserver() +{ + if (appStateObserver_ != nullptr) { + SC_LOG_INFO(LABEL, "AppStateObserver instance already create"); + return true; + } + appStateObserver_ = new (std::nothrow) AppStateObserver(); + if (appStateObserver_ == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to create AppStateObserver instance"); + return false; + } + sptr samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrClient == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get system ability manager"); + appStateObserver_ = nullptr; + return false; + } + auto remoteObject = samgrClient->GetSystemAbility(APP_MGR_SERVICE_ID); + iAppMgr_ = iface_cast(remoteObject); + if (iAppMgr_ == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get ability manager service"); + appStateObserver_ = nullptr; + return false; + } + + if (iAppMgr_->RegisterApplicationStateObserver(appStateObserver_) != ERR_OK) { + SC_LOG_ERROR(LABEL, "Failed to Register app state observer"); + iAppMgr_ = nullptr; + appStateObserver_ = nullptr; + return false; + } + + sptr appMgrDeathRecipient = new (std::nothrow) AppMgrDeathRecipient(); + if (appMgrDeathRecipient == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc appMgr death observer fail"); + return false; + } + + if (!remoteObject->AddDeathRecipient(appMgrDeathRecipient)) { + SC_LOG_ERROR(LABEL, "Add service death observer fail"); + return false; + } + + std::vector list; + if (iAppMgr_->GetForegroundApplications(list) == ERR_OK) { + for (auto it = list.begin(); it != list.end(); ++it) { + appStateObserver_->AddProcessToForegroundSet(*it); + } + } + SC_LOG_ERROR(LABEL, "Register app state observer success"); + return true; +} + +void SecCompService::UnregisterAppStateObserver() +{ + if (iAppMgr_ != nullptr && appStateObserver_ != nullptr) { + iAppMgr_->UnregisterApplicationStateObserver(appStateObserver_); + } +} + +bool SecCompService::GetCallerInfo(SecCompCallerInfo& caller) +{ + AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); + int32_t pid = IPCSkeleton::GetCallingPid(); + int32_t uid = IPCSkeleton::GetCallingUid(); + if ((uid != ROOT_UID) && (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) != AccessToken::TOKEN_HAP)) { + SC_LOG_ERROR(LABEL, "Get caller tokenId invalid"); + return false; + } + if ((uid != ROOT_UID) && (!appStateObserver_->IsProcessForeground(pid, uid))) { + SC_LOG_ERROR(LABEL, "caller pid is not in foreground"); + return false; + } + caller.tokenId = tokenId; + caller.pid = pid; + caller.uid = uid; + return true; +} + +int32_t SecCompService::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentRegister"); + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompManager::GetInstance().RegisterSecurityComponent(type, jsonRes, caller, scId); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return res; +} + +int32_t SecCompService::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + return SecCompManager::GetInstance().UpdateSecurityComponent(scId, jsonRes, caller); +} + +int32_t SecCompService::UnregisterSecurityComponent(int32_t scId) +{ + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return SecCompManager::GetInstance().UnregisterSecurityComponent(scId, caller); +} + +int32_t SecCompService::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentClick"); + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + int32_t res = + SecCompManager::GetInstance().ReportSecurityComponentClickEvent(scId, jsonRes, caller, touchInfo, callerToken); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return res; +} + +bool SecCompService::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + return SecCompManager::GetInstance().ReduceAfterVerifySavePermission(tokenId); +} + +sptr SecCompService::GetEnhanceRemoteObject() +{ + return SecCompEnhanceAdapter::GetEnhanceRemoteObject(); +} + +int SecCompService::Dump(int fd, const std::vector& args) +{ + if (fd < 0) { + return ERR_INVALID_VALUE; + } + + dprintf(fd, "SecCompService Dump:\n"); + std::string arg0 = ((args.size() == 0)? "" : Str16ToStr8(args.at(0))); + if (arg0.compare("-h") == 0) { + dprintf(fd, "Usage:\n"); + dprintf(fd, " -h: command help\n"); + dprintf(fd, " -a: dump all sec component\n"); + dprintf(fd, " -p: dump foreground processes\n"); + } else if (arg0.compare("-p") == 0) { + std::string dumpStr; + appStateObserver_->DumpProcess(dumpStr); + dprintf(fd, "%s\n", dumpStr.c_str()); + } else if (arg0.compare("-a") == 0 || arg0 == "") { + std::string dumpStr; + SecCompManager::GetInstance().DumpSecComp(dumpStr); + dprintf(fd, "%s\n", dumpStr.c_str()); + } + return ERR_OK; +} + +bool SecCompService::Initialize() const +{ + return SecCompManager::GetInstance().Initialize(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_service.h b/services/security_component_service/sa/sa_main/sec_comp_service.h new file mode 100644 index 0000000000000000000000000000000000000000..99d21f2ba6d0369929f964dc88d7bbf84933266e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_service.h @@ -0,0 +1,65 @@ +/* + * 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_COMPONENT_SERVICE_H +#define SECURITY_COMPONENT_SERVICE_H + +#include +#include +#include "app_state_observer.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "sec_comp_manager.h" +#include "sec_comp_stub.h" +#include "singleton.h" +#include "system_ability.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class SecCompService final : public SystemAbility, public SecCompStub { + DECLARE_DELAYED_SINGLETON(SecCompService); + DECLEAR_SYSTEM_ABILITY(SecCompService); + +public: + SecCompService(int32_t saId, bool runOnCreate); + + void OnStart() override; + void OnStop() override; + + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId) override; + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override; + int32_t UnregisterSecurityComponent(int32_t scId) override; + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) override; + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override; + sptr GetEnhanceRemoteObject() override; + + int Dump(int fd, const std::vector& args) override; + +private: + bool Initialize() const; + bool RegisterAppStateObserver(); + void UnregisterAppStateObserver(); + bool GetCallerInfo(SecCompCallerInfo& caller); + + ServiceRunningState state_; + sptr iAppMgr_; + sptr appStateObserver_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_SERVICE_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_stub.cpp b/services/security_component_service/sa/sa_main/sec_comp_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b91d428b42a613842dc11977352e62d600f7e7ce --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_stub.cpp @@ -0,0 +1,245 @@ +/* + * 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 "sec_comp_stub.h" + +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "sec_comp_click_event_parcel.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompStub"}; +static constexpr int32_t ROOT_UID = 0; +static constexpr int32_t BASE_USER_RANGE = 200000; +} // namespace + +int32_t SecCompStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + std::u16string descripter = SecCompStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (descripter != remoteDescripter) { + SC_LOG_ERROR(LABEL, "Deal remote request fail, descriptor is not matched"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t SecCompStub::RegisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t type; + if (!data.ReadUint32(type)) { + SC_LOG_ERROR(LABEL, "Read component type fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (type <= UNKNOWN_SC_TYPE || type >= MAX_SC_TYPE) { + SC_LOG_ERROR(LABEL, "Security component type invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + int32_t scId = INVALID_SC_ID; + int32_t res = this->RegisterSecurityComponent(static_cast(type), componentInfo, scId); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!reply.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + return SC_OK; +} + +int32_t SecCompStub::UpdateSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + int32_t res = this->UpdateSecurityComponent(scId, componentInfo); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Update security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + return res; +} + +int32_t SecCompStub::UnregisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + int32_t res = this->UnregisterSecurityComponent(scId); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Unregister security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::ReportSecurityComponentClickEventInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + sptr touchInfoParcel = data.ReadParcelable(); + if (touchInfoParcel == nullptr) { + SC_LOG_ERROR(LABEL, "Read touchInfo info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + sptr callerToken = data.ReadRemoteObject(); + int32_t res = + this->ReportSecurityComponentClickEvent(scId, componentInfo, touchInfoParcel->touchInfoParams_, callerToken); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::ReduceAfterVerifySavePermissionInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsMediaLibraryCalling()) { + SC_LOG_ERROR(LABEL, "Not medialibrary called"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + uint32_t tokenId; + if (!data.ReadUint32(tokenId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (tokenId == 0) { + SC_LOG_ERROR(LABEL, "AccessTokenId invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + bool res = this->ReduceAfterVerifySavePermission(tokenId); + if (!reply.WriteBool(res)) { + SC_LOG_ERROR(LABEL, "verify temp save permission result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::GetEnhanceRemoteObjectInner(MessageParcel& data, MessageParcel& reply) +{ + auto res = this->GetEnhanceRemoteObject(); + if (!reply.WriteRemoteObject(res)) { + SC_LOG_ERROR(LABEL, "Register security component enhance remote object fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +bool SecCompStub::IsMediaLibraryCalling() +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + if (uid == ROOT_UID) { + return true; + } + int32_t userId = uid / BASE_USER_RANGE; + uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (mediaLibraryTokenId_ == 0) { + mediaLibraryTokenId_ = AccessToken::AccessTokenKit::GetHapTokenID( + userId, "com.ohos.medialibrary.medialibrarydata", 0); + } + return tokenCaller == mediaLibraryTokenId_; +} + +SecCompStub::SecCompStub() +{ + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT)] = + &SecCompStub::RegisterSecurityComponentInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT)] = + &SecCompStub::UpdateSecurityComponentInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT)] = + &SecCompStub::UnregisterSecurityComponentInner; + requestFuncMap_[static_cast( + SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT)] = + &SecCompStub::ReportSecurityComponentClickEventInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION)] = + &SecCompStub::ReduceAfterVerifySavePermissionInner; + requestFuncMap_[static_cast( + SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT)] = + &SecCompStub::GetEnhanceRemoteObjectInner; +} + +SecCompStub::~SecCompStub() +{ + SC_LOG_ERROR(LABEL, "~SecCompStub"); + requestFuncMap_.clear(); + SC_LOG_ERROR(LABEL, "~SecCompStub end"); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_stub.h b/services/security_component_service/sa/sa_main/sec_comp_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..8c5addaa7cab8fce8d9447806dd131197beb928e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_stub.h @@ -0,0 +1,49 @@ +/* + * 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_COMPONENT_STUB_H +#define SECURITY_COMPONENT_STUB_H + +#include +#include "i_sec_comp_service.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompStub : public IRemoteStub { +public: + SecCompStub(); + virtual ~SecCompStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + +private: + int32_t RegisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t UpdateSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t UnregisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t ReportSecurityComponentClickEventInner(MessageParcel& data, MessageParcel& reply); + int32_t ReduceAfterVerifySavePermissionInner(MessageParcel& data, MessageParcel& reply); + int32_t GetEnhanceRemoteObjectInner(MessageParcel& data, MessageParcel& reply); + bool IsMediaLibraryCalling(); + + using RequestFuncType = int32_t (SecCompStub::*)(MessageParcel& data, MessageParcel& reply); + std::map requestFuncMap_; + AccessToken::AccessTokenID mediaLibraryTokenId_ = 0; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_STUB_H diff --git a/services/security_component_service/sa/sa_main/sec_event_handler.cpp b/services/security_component_service/sa/sa_main/sec_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32e3d8bc6ba1df57ba02ef3101fc9a52cdbbb169 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_event_handler.cpp @@ -0,0 +1,40 @@ +/* + * 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 "sec_event_handler.h" + +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +SecEventHandler::SecEventHandler( + const std::shared_ptr& runner) + : AppExecFwk::EventHandler(runner) {} + +SecEventHandler::~SecEventHandler() = default; + +bool SecEventHandler::ProxyPostTask( + const Callback &callback, const std::string &name, int64_t delayTime) +{ + return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); +} + +void SecEventHandler::ProxyRemoveTask(const std::string &name) +{ + AppExecFwk::EventHandler::RemoveTask(name); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/security_component_service/sa/sa_main/sec_event_handler.h b/services/security_component_service/sa/sa_main/sec_event_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..86b07342a3a82cd06d8c026df6f0904ee0054a01 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_event_handler.h @@ -0,0 +1,37 @@ +/* + * 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 SEC_EVENT_HANDLER_H +#define SEC_EVENT_HANDLER_H + +#include +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecEventHandler : public AppExecFwk::EventHandler { +public: + explicit SecEventHandler(const std::shared_ptr& runner); + ~SecEventHandler() override; + + bool ProxyPostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + + void ProxyRemoveTask(const std::string &name); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_EVENT_HANDLER_H diff --git a/services/security_component_service/sa/sa_profile/3506.json b/services/security_component_service/sa/sa_profile/3506.json new file mode 100644 index 0000000000000000000000000000000000000000..83650d44babc580266f8422199d2c9e64be7be46 --- /dev/null +++ b/services/security_component_service/sa/sa_profile/3506.json @@ -0,0 +1,12 @@ +{ + "process": "security_component_service", + "systemability": [ + { + "name": 3506, + "libpath": "libsecurity_component_service.z.so", + "run-on-create": false, + "distributed": false, + "dump_level": 1 + } + ] +} \ No newline at end of file diff --git a/services/security_component_service/sa/sa_profile/BUILD.gn b/services/security_component_service/sa/sa_profile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dc0c6d9bdd6554c72a3d5af28e337a35bfb45677 --- /dev/null +++ b/services/security_component_service/sa/sa_profile/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("security_component_sa_profile_standard") { + sources = [ "3506.json" ] + part_name = "security_component" +} diff --git a/services/security_component_service/sa/security_component_service.cfg b/services/security_component_service/sa/security_component_service.cfg new file mode 100644 index 0000000000000000000000000000000000000000..009ac034141ee3973516318ec955cec7c5d6b0b7 --- /dev/null +++ b/services/security_component_service/sa/security_component_service.cfg @@ -0,0 +1,24 @@ +{ + "jobs" : [{ + "name" : "post-fs-data", + "cmds" : [ + "mkdir /data/service/el1/public/security_component_service 0750 security_component security_component" + ] + } + ], + "services" : [{ + "name" : "security_component_service", + "path" : ["/system/bin/sa_main", "/system/profile/security_component_service.json"], + "ondemand" : true, + "start-mode" : "condition", + "uid" : "security_component", + "gid" : ["security_component"], + "apl" : "system_basic", + "permission" : [ + "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", + "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS" + ], + "secon" : "u:r:security_component_service:s0" + } + ] +} diff --git a/services/security_component_service/sa/security_component_service.rc b/services/security_component_service/sa/security_component_service.rc new file mode 100644 index 0000000000000000000000000000000000000000..68b6fbc01a098231e8f7bd4c342d90dd98e964a0 --- /dev/null +++ b/services/security_component_service/sa/security_component_service.rc @@ -0,0 +1,19 @@ +# 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. + +service security_component_service /system/bin/sa_main /system/profile/security_component.json + class security_component_service + priority -20 + user security_component + group security_component + seclabel u:r:security_component_service:s0 diff --git a/services/security_component_service/sa/test/BUILD.gn b/services/security_component_service/sa/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..84cd54b72a554b9e23184a8fb35bbc40ce848709 --- /dev/null +++ b/services/security_component_service/sa/test/BUILD.gn @@ -0,0 +1,147 @@ +# 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. + +import("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_service_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/include", + "//third_party/json/include", + ] + + sources = [ + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_state_observer.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/delay_exit_task.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/first_use_dialog.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_entity.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_service.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_stub.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_event_handler.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp", + "unittest/src/app_state_observer_test.cpp", + "unittest/src/sec_comp_entity_test.cpp", + "unittest/src/sec_comp_info_helper_test.cpp", + "unittest/src/sec_comp_manager_test.cpp", + "unittest/src/sec_comp_service_test.cpp", + "unittest/src/sec_comp_stub_test.cpp", + "unittest/src/service_test_common.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "//third_party/googletest:gmock_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "access_token:libtoken_setproc", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "window_manager:libdm", + ] +} + +ohos_unittest("sec_comp_service_mock_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/include", + "//third_party/json/include", + ] + + sources = [ + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_state_observer.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/delay_exit_task.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/first_use_dialog.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_entity.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_service.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_stub.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_event_handler.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp", + "unittest/src/sec_comp_service_mock_test.cpp", + "unittest/src/service_test_common.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "//third_party/googletest:gmock_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "access_token:libtoken_setproc", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "window_manager:libdm", + ] +} + +group("unittest") { + testonly = true + deps = [ + ":sec_comp_service_mock_test", + ":sec_comp_service_test", + ] +} diff --git a/services/security_component_service/sa/test/mock/include/access_token.h b/services/security_component_service/sa/test/mock/include/access_token.h new file mode 100644 index 0000000000000000000000000000000000000000..654bb5bcf506d359484a7cbcd762b048bff72878 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/access_token.h @@ -0,0 +1,57 @@ +/* + * 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_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H +#define SECURITY_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef unsigned int AccessTokenID; +static const AccessTokenID INVALID_TOKENID = 0; + +enum AccessTokenKitRet { + RET_FAILED = -1, + RET_SUCCESS = 0, +}; + +typedef enum TypeATokenTypeEnum { + TOKEN_INVALID = -1, + TOKEN_HAP = 0, + TOKEN_NATIVE, + TOKEN_SHELL, + TOKEN_TYPE_BUTT, +} ATokenTypeEnum; + +typedef enum TypePermissionFlag { + PERMISSION_DEFAULT_FLAG = 0, + PERMISSION_USER_SET = 1 << 0, + PERMISSION_USER_FIXED = 1 << 1, + PERMISSION_SYSTEM_FIXED = 1 << 2, + PERMISSION_GRANTED_BY_POLICY = 1 << 3, + PERMISSION_COMPONENT_SET = 1 << 4, + PERMISSION_POLICY_FIXED = 1 << 5, +} PermissionFlag; + +typedef struct { + unsigned int tokenUniqueID : 20; + unsigned int res : 6; + unsigned int dlpFlag : 1; + unsigned int type : 2; + unsigned int version : 3; +} AccessTokenIDInner; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H diff --git a/services/security_component_service/sa/test/mock/include/accesstoken_kit.h b/services/security_component_service/sa/test/mock/include/accesstoken_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..0a746c250c2b5fb77119ab5dea9b9bdbe43492dd --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/accesstoken_kit.h @@ -0,0 +1,58 @@ +/* + * 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_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +#define SECURITY_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H + +#include +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfo { +}; + +class AccessTokenKit { +public: + static int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) + { + return 0; + }; + + static int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) + { + return 0; + }; + + static int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) + { + return 0; + }; + + static AccessTokenID GetHapTokenID(int32_t userID, const std::string& bundleName, int32_t instIndex) + { + return 0; + }; + + static ATokenTypeEnum GetTokenTypeFlag(AccessTokenID tokenID) + { + AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); + return static_cast(idInner->type); + }; +}; +} // namespace SECURITY_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +} // namespace Security +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/app_mgr_interface.h b/services/security_component_service/sa/test/mock/include/app_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..b0a36ec60602865e1e850bc854dbaf2d3a2b85fd --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/app_mgr_interface.h @@ -0,0 +1,38 @@ +/* + * 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_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H +#define SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "application_state_observer_stub.h" + +namespace OHOS { +namespace AppExecFwk { + +class IAppMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.mock.AppMgr"); + + virtual int32_t RegisterApplicationStateObserver(const sptr &observer, + const std::vector &bundleNameList = {}) = 0; + + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) = 0; + + virtual int32_t GetForegroundApplications(std::vector &list) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H diff --git a/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h b/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..9271160512de5d5ad6d8bd52177b88b095a2623d --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h @@ -0,0 +1,73 @@ +/* + * 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_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H +#define SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H + +#include +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +enum class AppProcessState { + APP_STATE_BEGIN = 0, + APP_STATE_CREATE = APP_STATE_BEGIN, + APP_STATE_READY, + APP_STATE_FOREGROUND, + APP_STATE_FOCUS, + APP_STATE_BACKGROUND, + APP_STATE_TERMINATED, + APP_STATE_END, +}; + +struct ProcessData { + std::string bundleName; + int32_t pid = 0; + int32_t uid = 0; + AppProcessState state; + bool isContinuousTask = false; + bool isKeepAlive = false; + bool isFocused = false; + int32_t requestProcCode = 0; +}; + +struct AppStateData { + std::string bundleName; + int32_t pid = -1; + int32_t uid = 0; + int32_t state = 0; + int32_t accessTokenId = 0; + bool isFocused = false; +}; + +class IApplicationStateObserver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IApplicationStateObserver"); + virtual void OnProcessStateChanged(const ProcessData &processData) {} + virtual void OnProcessDied(const ProcessData &processData) = 0; +}; + +class ApplicationStateObserverStub : public IRemoteStub { +public: + ApplicationStateObserverStub() = default; + virtual ~ApplicationStateObserverStub() = default; + DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H diff --git a/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h b/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..eee66c0b67d0e67a3eadd84f958ab404be7770cc --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h @@ -0,0 +1,51 @@ +/* +* 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 SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H +#define SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "mock_app_mgr_proxy.h" + +namespace OHOS { +class MockIRemoteObject : public virtual RefBase { +public: + bool AddDeathRecipient(const sptr& recipient) + { + (void)recipient; + return addResult; + } + bool addResult = true; +}; + +template inline sptr iface_cast(const sptr &object) +{ + if (object == nullptr) { + return nullptr; + } + const std::u16string descriptor = INTERFACE::GetDescriptor(); + if (descriptor == u"ohos.appexecfwk.mock.AppMgr") { + return static_cast(MockAppMgrProxy::g_MockAppMgrProxy); + } + return nullptr; +} + +class ISystemAbilityManager : public IRemoteBroker { +public: + virtual sptr GetSystemAbility(int32_t systemAbilityId) = 0; + virtual int32_t UnloadSystemAbility(int32_t systemAbilityId) = 0; +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H diff --git a/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h b/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h new file mode 100644 index 0000000000000000000000000000000000000000..f1ca97c0f156ca84c72a8cc45be81fe370772f06 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h @@ -0,0 +1,38 @@ +/* +* 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 SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H +#define SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H +#include + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + static uint32_t GetCallingTokenID() + { + return tokenID; + }; + + static pid_t GetCallingPid() + { + return pid; + }; + + static uint32_t tokenID; + static pid_t pid; +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H diff --git a/services/security_component_service/sa/test/mock/include/iservice_registry.h b/services/security_component_service/sa/test/mock/include/iservice_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..8a4aa3d665598fbd0ba1cd1dc2d96be819fffdd7 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/iservice_registry.h @@ -0,0 +1,33 @@ +/* +* 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 SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H +#define SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H +#include +#include "if_system_ability_manager.h" + +namespace OHOS { +class SystemAbilityManagerClient { +public: + static SystemAbilityManagerClient& GetInstance(); + SystemAbilityManagerClient() = default; + ~SystemAbilityManagerClient() = default; + + static SystemAbilityManagerClient* clientInstance; + static SystemAbilityManagerClient defaultInstance; + static std::mutex instanceMtx; + MOCK_METHOD0(GetSystemAbilityManager, sptr()); +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H \ No newline at end of file diff --git a/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h b/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..eab8644c5eb1cb32b7ea63e29969d3cd295eec1f --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h @@ -0,0 +1,37 @@ +/* + * 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_COMPONET_MOCK_APP_MGR_PROXY_H +#define SECURITY_COMPONET_MOCK_APP_MGR_PROXY_H +#include +#include +#include "app_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +class MockAppMgrProxy : public IRemoteProxy { +public: + explicit MockAppMgrProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~MockAppMgrProxy() = default; + + static MockAppMgrProxy* g_MockAppMgrProxy; + + MOCK_METHOD2(RegisterApplicationStateObserver, + int32_t(const sptr&, const std::vector&)); + MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr &)); + MOCK_METHOD1(GetForegroundApplications, int32_t(std::vector&)); +}; +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h b/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..ee833e69215ad68403c3722089f1ec0c1cacee2f --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h @@ -0,0 +1,32 @@ +/* + * 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_COMPONENT_MOCK_SYSTEM_ABILITY_MANAGER_PROXY +#define SECURITY_COMPONENT_MOCK_SYSTEM_ABILITY_MANAGER_PROXY +#include +#include +#include "if_system_ability_manager.h" + +namespace OHOS { +class SystemAbilityManagerProxy : public IRemoteProxy { +public: + explicit SystemAbilityManagerProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~SystemAbilityManagerProxy() = default; + + MOCK_METHOD1(GetSystemAbility, sptr(int32_t)); + MOCK_METHOD1(UnloadSystemAbility, int32_t(int32_t)); +}; +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/system_ability.h b/services/security_component_service/sa/test/mock/include/system_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..9127f3a1d434f0085660bced523e1c471d88ed08 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/system_ability.h @@ -0,0 +1,47 @@ +/* + * 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 MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H +#define MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H + +#include +#include "if_system_ability_manager.h" +#include "iremote_object.h" + +namespace OHOS { +#define DECLEAR_SYSTEM_ABILITY(className) +#define SA_ID_SECURITY_COMPONENT_SERVICE 1000 +#define REGISTER_SYSTEM_ABILITY_BY_ID(a, b, c) + +class SystemAbility { +public: + static bool MakeAndRegisterAbility(SystemAbility*) + { + return true; + } + + virtual void OnStart() {}; + + virtual void OnStop() {}; + + MOCK_METHOD1(Publish, bool(sptr)); + + SystemAbility(bool runOnCreate = false) {}; + + SystemAbility(const int32_t serviceId, bool runOnCreate = false) {}; + + virtual ~SystemAbility() = default; +}; +} // namespace OHOS +#endif // MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H diff --git a/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp b/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d83e9f01b665b7f20f49db9d9cb4463e35b095f8 --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp @@ -0,0 +1,20 @@ +/* +* 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 "mock_app_mgr_proxy.h" + +namespace OHOS { +MockAppMgrProxy* MockAppMgrProxy::g_MockAppMgrProxy = nullptr; +} diff --git a/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp b/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62174e8997770d3412923f75a6bb868a1efe5a02 --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp @@ -0,0 +1,20 @@ +/* +* 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 "ipc_skeleton.h" + +namespace OHOS { +uint32_t IPCSkeleton::tokenID = 0; +pid_t IPCSkeleton::pid = -1; +} // namespace OHOS diff --git a/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp b/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7abc1fa0b728dcc88d95b324286181ca7d2a84bf --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp @@ -0,0 +1,34 @@ + /* + * 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 "iservice_registry.h" + +namespace OHOS { +SystemAbilityManagerClient* SystemAbilityManagerClient::clientInstance = nullptr; +SystemAbilityManagerClient SystemAbilityManagerClient::defaultInstance; +std::mutex SystemAbilityManagerClient::instanceMtx; + +SystemAbilityManagerClient& SystemAbilityManagerClient::GetInstance() +{ + std::lock_guard lock(instanceMtx); + if (clientInstance == nullptr) { + clientInstance = new (std::nothrow)SystemAbilityManagerClient(); + if (clientInstance == nullptr) { + return defaultInstance; + } + } + return *clientInstance; +} +} // namespace OHOS diff --git a/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp b/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..812f046124c763bdd5fa3ce8e5ca5067188a639d --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp @@ -0,0 +1,110 @@ +/* + * 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 "sec_comp_enhance_adapter.h" + +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "MockSecCompEnhanceAdapter"}; +} + +int32_t SecCompEnhanceAdapter::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + SC_LOG_DEBUG(LABEL, "SetEnhanceCfg success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + SC_LOG_DEBUG(LABEL, "GetPointerEventEnhanceData success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::CheckExtraInfo(const SecCompClickEvent& touchInfo) +{ + SC_LOG_DEBUG(LABEL, "CheckExtraInfo success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::EnableInputEnhance() +{ + SC_LOG_DEBUG(LABEL, "EnableInputEnhance success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::DisableInputEnhance() +{ + SC_LOG_DEBUG(LABEL, "DisableInputEnhance success"); + return SC_OK; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(std::string& componentInfo) +{ + SC_LOG_DEBUG(LABEL, "EnhanceDataPreprocess success"); + return true; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(int32_t scId, std::string& componentInfo) +{ + SC_LOG_DEBUG(LABEL, "EnhanceDataPreprocess success"); + return true; +} + +void SecCompEnhanceAdapter::RegisterScIdEnhance(int32_t scId) +{ + SC_LOG_DEBUG(LABEL, "RegisterScIdEnhance success"); +} + +void SecCompEnhanceAdapter::UnregisterScIdEnhance(int32_t scId) +{ + SC_LOG_DEBUG(LABEL, "UnregisterScIdEnhance success"); +} + +void SecCompEnhanceAdapter::StartEnhanceService() +{ + SC_LOG_DEBUG(LABEL, "StartEnhanceService success"); +} + +void SecCompEnhanceAdapter::ExistEnhanceService() +{ + SC_LOG_DEBUG(LABEL, "ExistEnhanceService success"); +} + +void SecCompEnhanceAdapter::NotifyProcessDied(int32_t pid) +{ + SC_LOG_DEBUG(LABEL, "NotifyProcessDied success"); +} + +int32_t SecCompEnhanceAdapter::CheckComponentInfoEnhnace(int32_t pid, + std::shared_ptr& compInfo, const nlohmann::json& jsonComponent) +{ + SC_LOG_DEBUG(LABEL, "CheckComponentInfoEnhnace success"); + return SC_OK; +} + +sptr SecCompEnhanceAdapter::GetEnhanceRemoteObject() +{ + SC_LOG_DEBUG(LABEL, "GetEnhanceRemoteObject success"); + return nullptr; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b132c4f687de7f637c133f985a375b4697797dee --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp @@ -0,0 +1,179 @@ +/* + * 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_state_observer_test.h" + +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "service_test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "AppStateObserverTest"}; +} + +void AppStateObserverTest::SetUpTestCase() +{} + +void AppStateObserverTest::TearDownTestCase() +{} + +void AppStateObserverTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (observer_ != nullptr) { + return; + } + + observer_ = std::make_shared(); + ASSERT_NE(nullptr, observer_); +} + +void AppStateObserverTest::TearDown() +{ + observer_ = nullptr; +} + +/** + * @tc.name: IsProcessForeground001 + * @tc.desc: Test is process foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, IsProcessForeground001, TestSize.Level1) +{ + ASSERT_FALSE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + AppExecFwk::AppStateData stateData = { + .pid = ServiceTestCommon::TEST_PID_1, + .uid = ServiceTestCommon::TEST_UID_1, + }; + observer_->AddProcessToForegroundSet(stateData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); +} + +/** + * @tc.name: AddProcessToForegroundSet001 + * @tc.desc: Test add process to foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, AddProcessToForegroundSet001, TestSize.Level1) +{ + AppExecFwk::AppStateData stateData = { + .pid = ServiceTestCommon::TEST_PID_1, + .uid = ServiceTestCommon::TEST_UID_1, + }; + observer_->AddProcessToForegroundSet(stateData); + observer_->AddProcessToForegroundSet(stateData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + + AppExecFwk::ProcessData procData = { + .pid = ServiceTestCommon::TEST_PID_2, + .uid = ServiceTestCommon::TEST_UID_2, + }; + observer_->AddProcessToForegroundSet(procData); + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_2, ServiceTestCommon::TEST_UID_2)); +} + +/** + * @tc.name: RemoveProcessFromForegroundSet001 + * @tc.desc: Test remove process from foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, RemoveProcessFromForegroundSet001, TestSize.Level1) +{ + AppExecFwk::ProcessData procData = { + .pid = ServiceTestCommon::TEST_PID_1, + .uid = ServiceTestCommon::TEST_UID_1, + }; + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + observer_->RemoveProcessFromForegroundSet(procData); + observer_->RemoveProcessFromForegroundSet(procData); + ASSERT_FALSE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); +} + +/** + * @tc.name: RemoveProcessFromForegroundSet002 + * @tc.desc: Test remove process with different uid + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, RemoveProcessFromForegroundSet002, TestSize.Level1) +{ + AppExecFwk::ProcessData procData = { + .pid = ServiceTestCommon::TEST_PID_1, + .uid = ServiceTestCommon::TEST_UID_1, + }; + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + procData.pid = ServiceTestCommon::TEST_PID_2; + observer_->RemoveProcessFromForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); +} + +/** + * @tc.name: OnProcessStateChanged001 + * @tc.desc: Test recieve process state changed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, OnProcessStateChanged001, TestSize.Level1) +{ + AppExecFwk::ProcessData processData; + processData.state = AppExecFwk::AppProcessState::APP_STATE_CREATE; + observer_->OnProcessStateChanged(processData); + ASSERT_EQ(observer_->foregrandProcList_.size(), static_cast(0)); + + processData.state = AppExecFwk::AppProcessState::APP_STATE_FOREGROUND; + processData.pid = ServiceTestCommon::TEST_PID_1; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + + processData.state = AppExecFwk::AppProcessState::APP_STATE_BACKGROUND; + processData.pid = ServiceTestCommon::TEST_PID_1; + observer_->OnProcessStateChanged(processData); + ASSERT_FALSE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); +} + +/** + * @tc.name: OnProcessDied001 + * @tc.desc: Test recieve process state died + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, OnProcessDied001, TestSize.Level1) +{ + AppExecFwk::ProcessData processData; + processData.state = AppExecFwk::AppProcessState::APP_STATE_FOREGROUND; + processData.pid = ServiceTestCommon::TEST_PID_1; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); + + // if last process died, the sec_comp service will exit. + processData.pid = ServiceTestCommon::TEST_PID_2; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_2, ServiceTestCommon::TEST_UID_2)); + + // notify process 1 died + processData.pid = ServiceTestCommon::TEST_PID_1; + observer_->OnProcessDied(processData); + ASSERT_FALSE(observer_->IsProcessForeground(ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_UID_1)); +} diff --git a/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7195cf2b88d3f55ff06aa59a8a1494689a580446 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h @@ -0,0 +1,41 @@ +/* + * 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 APP_STATE_OBSERVER_TEST_H +#define APP_STATE_OBSERVER_TEST_H + +#include +#define private public +#include "app_state_observer.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class AppStateObserverTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + std::shared_ptr observer_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // APP_STATE_OBSERVER_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a9b861c3e8a4ee23f9ac65733106d7f2d8d6fdd --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp @@ -0,0 +1,156 @@ +/* + * 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 "sec_comp_entity_test.h" + +#include "sec_comp_log.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_tool.h" +#include "service_test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEntityTest"}; +} + +void SecCompEntityTest::SetUpTestCase() +{} + +void SecCompEntityTest::TearDownTestCase() +{} + +void SecCompEntityTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (entity_ != nullptr) { + return; + } + + std::shared_ptr component = std::make_shared(); + ASSERT_NE(nullptr, component); + + entity_ = std::make_shared(component, 1, 1); + ASSERT_NE(nullptr, entity_); +} + +void SecCompEntityTest::TearDown() +{ + entity_ = nullptr; +} + +/** + * @tc.name: RevokeTempPermission001 + * @tc.desc: Test revoke temp permission + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, RevokeTempPermission001, TestSize.Level1) +{ + entity_->isGrant_ = false; + ASSERT_EQ(SC_OK, entity_->RevokeTempPermission()); + + entity_->isGrant_ = true; + entity_->componentInfo_->type_ = UNKNOWN_SC_TYPE; + ASSERT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, entity_->RevokeTempPermission()); + ASSERT_FALSE(entity_->isGrant_); + + entity_->isGrant_ = true; + entity_->componentInfo_->type_ = LOCATION_COMPONENT; + ASSERT_EQ(SC_OK, entity_->RevokeTempPermission()); + ASSERT_FALSE(entity_->isGrant_); +} + +/** + * @tc.name: GrantTempPermission001 + * @tc.desc: Test grant location permission + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, GrantTempPermission001, TestSize.Level1) +{ + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = UNKNOWN_SC_TYPE; + ASSERT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, entity_->GrantTempPermission()); + ASSERT_TRUE(entity_->isGrant_); + + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = LOCATION_COMPONENT; + ASSERT_EQ(SC_OK, entity_->GrantTempPermission()); + ASSERT_TRUE(entity_->isGrant_); + + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = PASTE_COMPONENT; + ASSERT_EQ(SC_OK, entity_->GrantTempPermission()); + ASSERT_TRUE(entity_->isGrant_); +} + +/** + * @tc.name: GrantTempPermission002 + * @tc.desc: Test grant paste permission with invalid tokenId. + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, GrantTempPermission002, TestSize.Level1) +{ + std::shared_ptr pasteComponent = std::make_shared(); + ASSERT_NE(nullptr, pasteComponent); + + entity_ = std::make_shared(pasteComponent, 0, 1); + ASSERT_NE(nullptr, entity_); + + ASSERT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, entity_->GrantTempPermission()); + ASSERT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, entity_->RevokeTempPermission()); +} + +/** + * @tc.name: CheckTouchInfo001 + * @tc.desc: Test touch info + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, CheckTouchInfo001, TestSize.Level1) +{ + SecCompClickEvent touch = { + .touchX = ServiceTestCommon::TEST_COORDINATE, + .touchY = ServiceTestCommon::TEST_COORDINATE, + .timestamp = 0, + }; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + uint64_t current = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()); + touch.timestamp = current + 10000L; // 10s + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + entity_->componentInfo_->rect_.x_ = ServiceTestCommon::TEST_DIFF_COORDINATE; // click event will not hit this rect + entity_->componentInfo_->rect_.y_ = ServiceTestCommon::TEST_DIFF_COORDINATE; + entity_->componentInfo_->rect_.width_ = ServiceTestCommon::TEST_DIFF_COORDINATE; + entity_->componentInfo_->rect_.height_ = ServiceTestCommon::TEST_DIFF_COORDINATE; + touch.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + entity_->componentInfo_->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + entity_->componentInfo_->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + touch.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c65cf377d77180ea4843c551596866f4d12cf09f --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h @@ -0,0 +1,42 @@ +/* + * 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 SEC_COMP_ENTITY_TEST_H +#define SEC_COMP_ENTITY_TEST_H + +#include +#define private public +#include "sec_comp_entity.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEntityTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + std::shared_ptr entity_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_ENTITY_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddcef69c0d59319501f97f3c7492ed7c407f66ae --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp @@ -0,0 +1,654 @@ +/* + * 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 "sec_comp_info_helper_test.h" + +#include "display.h" +#include "display_info.h" +#include "display_manager.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "service_test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompInfoHelperTest"}; +static double g_curScreenWidth = 0.0F; +static double g_curScreenHeight = 0.0F; +static double g_testWidth = 0.0F; +static double g_testHeight = 0.0F; + +static bool GetScreenSize() +{ + sptr display = + OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplaySync(); + if (display == nullptr) { + return false; + } + + auto info = display->GetDisplayInfo(); + if (info == nullptr) { + return false; + } + + g_curScreenWidth = static_cast(info->GetWidth()); + g_curScreenHeight = static_cast(info->GetHeight()); + return true; +} +} + +void SecCompInfoHelperTest::SetUpTestCase() +{ + ASSERT_TRUE(GetScreenSize()); + g_testWidth = (ServiceTestCommon::ZERO_OFFSET + g_curScreenWidth) / ServiceTestCommon::QUARTER; + g_testHeight = (ServiceTestCommon::ZERO_OFFSET + g_curScreenHeight) / ServiceTestCommon::QUARTER; +} + +void SecCompInfoHelperTest::TearDownTestCase() +{} + +void SecCompInfoHelperTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SecCompInfoHelperTest::TearDown() +{} + +/** + * @tc.name: ParseComponent001 + * @tc.desc: Test parse component info success + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_NE(nullptr, comp); + ASSERT_TRUE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent002 + * @tc.desc: Test parse component info with empty json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ASSERT_EQ(nullptr, SecCompInfoHelper::ParseComponent(UNKNOWN_SC_TYPE, jsonComponent)); + + ASSERT_EQ(nullptr, SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent)); + ASSERT_EQ(nullptr, SecCompInfoHelper::ParseComponent(PASTE_COMPONENT, jsonComponent)); + ASSERT_EQ(nullptr, SecCompInfoHelper::ParseComponent(SAVE_COMPONENT, jsonComponent)); +} + +/** + * @tc.name: ParseComponent003 + * @tc.desc: Test parse component info with invalid type + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = UNKNOWN_SC_TYPE; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_EQ(nullptr, comp); +} + +/** + * @tc.name: ParseComponent004 + * @tc.desc: Test parse component info with invalid rect + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent004, TestSize.Level1) +{ + SecCompRect rect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + SecCompRect windowRect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + ASSERT_TRUE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + + rect.x_ = ServiceTestCommon::TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = ServiceTestCommon::TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.x_ = g_curScreenWidth + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = g_curScreenHeight + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.width_ = g_curScreenWidth; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.height_ = g_curScreenHeight; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.x_ = g_curScreenWidth - g_testWidth; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = g_curScreenHeight - g_testHeight; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); +} + +/** + * @tc.name: ParseComponent005 + * @tc.desc: Test parse component info with windowRect invalid + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent005, TestSize.Level1) +{ + SecCompRect rect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + SecCompRect windowRect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + ASSERT_TRUE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + + windowRect.x_ = g_testWidth + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.y_ = g_testHeight + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.width_ = g_testWidth - 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.height_ = g_testHeight - 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.width_ = ServiceTestCommon::TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.height_ = ServiceTestCommon::TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); +} + +/** + * @tc.name: ParseComponent006 + * @tc.desc: Test parse component info with parentEffect active + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent006, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, true }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent007 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent007, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent008 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent008, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent009 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent009, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_INVALID_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent010 + * @tc.desc: Test parse component info with invalid color + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_INVALID }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_INVALID }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_INVALID } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent011 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent011, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, NO_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, NO_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent012 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent012, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent013 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent013, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent014 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent014, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + + +/** + * @tc.name: CheckComponentValid001 + * @tc.desc: Test CheckComponentValid with invalid color + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLACK }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_WHITE } + }; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); +} + +/** + * @tc.name: CheckComponentValid002 + * @tc.desc: Test CheckComponentValid with invalid text or icon + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + comp->text_ = UNKNOWN_TEXT; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->text_ = static_cast(LocationDesc::SELECT_LOCATION); + comp->icon_ = UNKNOWN_ICON; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->text_ = UNKNOWN_TEXT; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); +} + +/** + * @tc.name: CheckComponentValid003 + * @tc.desc: Test CheckComponentValid with invalid type + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ServiceTestCommon::BuildLocationComponentJson(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + comp->type_ = SecCompType::UNKNOWN_SC_TYPE; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->type_ = SecCompType::MAX_SC_TYPE; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h new file mode 100644 index 0000000000000000000000000000000000000000..a9d845964b1791d69009082178f2339c7c47b3de --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h @@ -0,0 +1,37 @@ +/* + * 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 SEC_COMP_INFO_HELPER_TEST_H +#define SEC_COMP_INFO_HELPER_TEST_H + +#include +#include "sec_comp_info_helper.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompInfoHelperTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_ENTITY_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ad5d90f6760f8f4f48ca396c3c96050f5450a90 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp @@ -0,0 +1,350 @@ +/* + * 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 "sec_comp_manager_test.h" + +#include "sec_comp_log.h" +#include "location_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "service_test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompManagerTest"}; + +static LocationButton BuildInvalidLocationComponent() +{ + LocationButton button; + button.fontSize_ = ServiceTestCommon::TEST_INVALID_SIZE; + button.iconSize_ = ServiceTestCommon::TEST_INVALID_SIZE; + button.padding_.top = ServiceTestCommon::TEST_INVALID_SIZE; + button.padding_.right = ServiceTestCommon::TEST_INVALID_SIZE; + button.padding_.bottom = ServiceTestCommon::TEST_INVALID_SIZE; + button.padding_.left = ServiceTestCommon::TEST_INVALID_SIZE; + button.textIconSpace_ = ServiceTestCommon::TEST_INVALID_SIZE; + button.fontColor_.value = ServiceTestCommon::TEST_COLOR_WHITE; + button.iconColor_.value = ServiceTestCommon::TEST_COLOR_WHITE; + button.bgColor_.value = ServiceTestCommon::TEST_COLOR_WHITE; + button.borderWidth_ = ServiceTestCommon::TEST_INVALID_SIZE; + button.type_ = LOCATION_COMPONENT; + button.rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.x_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.y_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.width_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.height_ = ServiceTestCommon::TEST_COORDINATE; + button.text_ = UNKNOWN_TEXT; + button.icon_ = UNKNOWN_ICON; + button.bg_ = SecCompBackground::UNKNOWN_BG; + return button; +} + +static LocationButton BuildValidLocationComponent() +{ + LocationButton button; + button.fontSize_ = ServiceTestCommon::TEST_SIZE; + button.iconSize_ = ServiceTestCommon::TEST_SIZE; + button.padding_.top = ServiceTestCommon::TEST_SIZE; + button.padding_.right = ServiceTestCommon::TEST_SIZE; + button.padding_.bottom = ServiceTestCommon::TEST_SIZE; + button.padding_.left = ServiceTestCommon::TEST_SIZE; + button.textIconSpace_ = ServiceTestCommon::TEST_SIZE; + button.fontColor_.value = ServiceTestCommon::TEST_COLOR_YELLOW; + button.iconColor_.value = ServiceTestCommon::TEST_COLOR_RED; + button.bgColor_.value = ServiceTestCommon::TEST_COLOR_BLUE; + button.borderWidth_ = ServiceTestCommon::TEST_SIZE; + button.type_ = LOCATION_COMPONENT; + button.rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + button.rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.x_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.y_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.width_ = ServiceTestCommon::TEST_COORDINATE; + button.windowRect_.height_ = ServiceTestCommon::TEST_COORDINATE; + button.text_ = static_cast(LocationDesc::SELECT_LOCATION); + button.icon_ = static_cast(LocationIcon::LINE_ICON); + button.bg_ = SecCompBackground::CIRCLE; + return button; +} +} + +void SecCompManagerTest::SetUpTestCase() +{} + +void SecCompManagerTest::TearDownTestCase() +{} + +void SecCompManagerTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SecCompManagerTest::TearDown() +{ + SecCompManager::GetInstance().componentMap_.clear(); +} + + +/** + * @tc.name: CreateScId001 + * @tc.desc: Test create sc id + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, CreateScId001, TestSize.Level1) +{ + SecCompManager::GetInstance().scIdStart_ = ServiceTestCommon::MAX_INT_NUM; + ASSERT_EQ(ServiceTestCommon::SC_ID_START, SecCompManager::GetInstance().CreateScId()); + + SecCompManager::GetInstance().scIdStart_ = ServiceTestCommon::SC_ID_START; + ASSERT_EQ(ServiceTestCommon::SC_ID_START + 1, SecCompManager::GetInstance().CreateScId()); +} + +/** + * @tc.name: AddSecurityComponentToList001 + * @tc.desc: Test add security component to list + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, AddSecurityComponentToList001, TestSize.Level1) +{ + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(nullptr, compPtr); + compPtr->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity(compPtr, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_1); + + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(1, entity)); + + std::shared_ptr compPtrNew = std::make_shared(); + ASSERT_NE(nullptr, compPtrNew); + compPtrNew->rect_.x_ = ServiceTestCommon::TEST_COORDINATE * 2; // not overlap + compPtrNew->rect_.y_ = ServiceTestCommon::TEST_COORDINATE * 2; // not overlap + compPtrNew->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtrNew->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entityNew(compPtrNew, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_2); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(1, entityNew)); +} + +/** + * @tc.name: DeleteSecurityComponentFromList001 + * @tc.desc: Test delete security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, DeleteSecurityComponentFromList001, TestSize.Level1) +{ + ASSERT_EQ(SC_SERVICE_ERROR_COMPONENT_NOT_EXIST, SecCompManager::GetInstance().DeleteSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(nullptr, compPtr); + compPtr->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity(compPtr, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_1); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(ServiceTestCommon::TEST_PID_1, entity)); + + ASSERT_EQ(SC_SERVICE_ERROR_COMPONENT_NOT_EXIST, SecCompManager::GetInstance().DeleteSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_2)); + + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().DeleteSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); +} + +/** + * @tc.name: GetSecurityComponentFromList001 + * @tc.desc: Test get security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, GetSecurityComponentFromList001, TestSize.Level1) +{ + ASSERT_EQ(nullptr, SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(nullptr, compPtr); + compPtr->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity(compPtr, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_1); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(ServiceTestCommon::TEST_PID_1, entity)); + ASSERT_EQ(nullptr, SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_2)); + ASSERT_NE(nullptr, SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); +} + +/** + * @tc.name: NotifyProcessBackground001 + * @tc.desc: Test notify process background + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, NotifyProcessBackground001, TestSize.Level1) +{ + SecCompManager::GetInstance().NotifyProcessBackground(ServiceTestCommon::TEST_PID_1); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(nullptr, compPtr); + compPtr->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity(compPtr, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_1); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(ServiceTestCommon::TEST_PID_1, entity)); + auto component = SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1); + ASSERT_NE(nullptr, component); + SecCompManager::GetInstance().NotifyProcessForeground(ServiceTestCommon::TEST_PID_1); + ASSERT_TRUE(SecCompManager::GetInstance().IsForegroundCompExist()); + + SecCompManager::GetInstance().NotifyProcessBackground(ServiceTestCommon::TEST_PID_1); + ASSERT_FALSE(SecCompManager::GetInstance().IsForegroundCompExist()); +} + +/** + * @tc.name: NotifyProcessDied001 + * @tc.desc: Test notify process died + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, NotifyProcessDied001, TestSize.Level1) +{ + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(nullptr, compPtr); + compPtr->rect_.x_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.y_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity(compPtr, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_1); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(ServiceTestCommon::TEST_PID_1, entity)); + + std::shared_ptr compPtr2 = std::make_shared(); + ASSERT_NE(nullptr, compPtr2); + compPtr2->rect_.x_ = ServiceTestCommon::TEST_COORDINATE * 2; // not overlap + compPtr2->rect_.y_ = ServiceTestCommon::TEST_COORDINATE * 2; // not overlap + compPtr2->rect_.width_ = ServiceTestCommon::TEST_COORDINATE; + compPtr2->rect_.height_ = ServiceTestCommon::TEST_COORDINATE; + SecCompEntity entity2(compPtr2, ServiceTestCommon::TEST_TOKEN_ID, ServiceTestCommon::TEST_SC_ID_2); + ASSERT_EQ(SC_OK, SecCompManager::GetInstance().AddSecurityComponentToList(ServiceTestCommon::TEST_PID_2, entity2)); + + SecCompManager::GetInstance().NotifyProcessDied(ServiceTestCommon::TEST_PID_3); + ASSERT_NE(nullptr, SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); + + SecCompManager::GetInstance().NotifyProcessDied(ServiceTestCommon::TEST_PID_1); + ASSERT_EQ(nullptr, SecCompManager::GetInstance().GetSecurityComponentFromList( + ServiceTestCommon::TEST_PID_1, ServiceTestCommon::TEST_SC_ID_1)); +} + +/** + * @tc.name: RegisterSecurityComponent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, RegisterSecurityComponent001, TestSize.Level1) +{ + nlohmann::json jsonInvalid; + LocationButton buttonInvalid = BuildInvalidLocationComponent(); + buttonInvalid.ToJson(jsonInvalid); + int32_t scId; + SecCompCallerInfo caller = { + .tokenId = ServiceTestCommon::TEST_TOKEN_ID, + .pid = ServiceTestCommon::TEST_PID_1 + }; + ASSERT_EQ(SC_SERVICE_ERROR_COMPONENT_INFO_INVALID, + SecCompManager::GetInstance().RegisterSecurityComponent(LOCATION_COMPONENT, jsonInvalid, caller, scId)); + + nlohmann::json jsonValid; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonValid); + + // callback check failed + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST, + SecCompManager::GetInstance().RegisterSecurityComponent(LOCATION_COMPONENT, jsonValid, caller, scId)); + SecCompManager::GetInstance().maliciousAppList_.clear(); +} + +/** + * @tc.name: UpdateSecurityComponent001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, UpdateSecurityComponent001, TestSize.Level1) +{ + nlohmann::json jsonValid; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonValid); + SecCompCallerInfo caller = { + .tokenId = ServiceTestCommon::TEST_TOKEN_ID, + .pid = ServiceTestCommon::TEST_PID_1 + }; + ASSERT_NE(SC_OK, SecCompManager::GetInstance().UpdateSecurityComponent( + ServiceTestCommon::TEST_SC_ID_1, jsonValid, caller)); +} + +/** + * @tc.name: UnregisterSecurityComponent001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, UnregisterSecurityComponent001, TestSize.Level1) +{ + SecCompCallerInfo caller = { + .tokenId = ServiceTestCommon::TEST_TOKEN_ID, + .pid = ServiceTestCommon::TEST_PID_1 + }; + + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, + SecCompManager::GetInstance().UnregisterSecurityComponent(ServiceTestCommon::TEST_INVALID_SC_ID, caller)); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test report security component click + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + SecCompCallerInfo caller = { + .tokenId = ServiceTestCommon::TEST_TOKEN_ID, + .pid = ServiceTestCommon::TEST_PID_1 + }; + SecCompClickEvent touchInfo; + nlohmann::json jsonVaild; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonVaild); + ASSERT_NE(SC_OK, + SecCompManager::GetInstance().ReportSecurityComponentClickEvent(1, jsonVaild, caller, touchInfo, nullptr)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..eaf0968fec369055981fa5a373026fd7d06e4a43 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h @@ -0,0 +1,39 @@ +/* + * 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 SEC_COMP_MANAGER_TEST_H +#define SEC_COMP_MANAGER_TEST_H + +#include +#define private public +#include "sec_comp_manager.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_MANAGER_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..533adeccd476ca76ad290b468b9088d91e98c618 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp @@ -0,0 +1,323 @@ +/* + * 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 "sec_comp_service_mock_test.h" + +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "location_button.h" +#include "mock_system_ability_proxy.h" +#include "mock_app_mgr_proxy.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_enhance_adapter.h" +#include "service_test_common.h" +#include "system_ability.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompServiceMockTest"}; +static AccessTokenID g_selfTokenId = 0; +} + +void SecCompServiceMockTest::SetUpTestCase() +{} + +void SecCompServiceMockTest::TearDownTestCase() +{} + +void SecCompServiceMockTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (secCompService_ != nullptr) { + return; + } + SecCompService* ptr = new (std::nothrow) SecCompService(ServiceTestCommon::SA_ID, true); + secCompService_ = sptr(ptr); + ASSERT_NE(nullptr, secCompService_); + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + ASSERT_NE(nullptr, secCompService_->appStateObserver_); + g_selfTokenId = GetSelfTokenID(); +} + +void SecCompServiceMockTest::TearDown() +{ + if (secCompService_ != nullptr) { + secCompService_->appStateObserver_ = nullptr; + } + secCompService_ = nullptr; + EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); +} + +/** + * @tc.name: RegisterSecurityComponent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceMockTest, RegisterSecurityComponent001, TestSize.Level1) +{ + // get caller fail + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + EXPECT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, "", scId)); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + // parse component json fail + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // wrong json + EXPECT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, "{a=", scId)); + + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + EXPECT_EQ(SC_OK, secCompService_->UpdateSecurityComponent(scId, saveInfo)); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT + }; + + EXPECT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touch, nullptr)); + sleep(5); + EXPECT_EQ(SC_OK, secCompService_->UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: RegisterSecurityComponent002 + * @tc.desc: Test register security component check touch info failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceMockTest, RegisterSecurityComponent002, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + EXPECT_EQ(SC_SERVICE_ERROR_CLICK_EVENT_INVALID, + secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touch, nullptr)); + EXPECT_EQ(SC_OK, secCompService_->UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: RegisterSecurityComponent003 + * @tc.desc: Test register security component permission grant failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceMockTest, RegisterSecurityComponent003, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + ASSERT_EQ(0, SetSelfTokenID(0)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT + }; + EXPECT_EQ(SC_SERVICE_ERROR_PERMISSION_OPER_FAIL, + secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touch, nullptr)); + EXPECT_EQ(SC_OK, secCompService_->UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceMockTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(6); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + EXPECT_EQ(SC_OK, secCompService_->UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent002 + * @tc.desc: Test report security component click with save button + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompServiceMockTest, ReportSecurityComponentClickEvent002, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent003 + * @tc.desc: Test report security component click twice with save button + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceMockTest, ReportSecurityComponentClickEvent003, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + nlohmann::json jsonRes; + ServiceTestCommon::BuildSaveComponentJson(jsonRes); + std::string saveInfo = jsonRes.dump(); + + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(SC_OK, secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, saveInfo, scId)); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(6); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / ServiceTestCommon::TIME_CONVERSION_UNIT; + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_EQ(SC_OK, secCompService_->ReportSecurityComponentClickEvent(scId, saveInfo, touchInfo, nullptr)); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(ServiceTestCommon::HAP_TOKEN_ID)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f2f7ae7f9050b43fa653262e838805d5e818966b --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.h @@ -0,0 +1,42 @@ +/* + * 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 SEC_COMP_SERVICE_TEST_H +#define SEC_COMP_SERVICE_TEST_H + +#include +#define private public +#include "sec_comp_service.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompServiceMockTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + sptr secCompService_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_SERVICE_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ca3a7fd7dab56d46bd8de7daa7b71b177d22afa --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp @@ -0,0 +1,276 @@ +/* + * 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 "sec_comp_service_test.h" + +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "location_button.h" +#include "mock_system_ability_proxy.h" +#include "mock_app_mgr_proxy.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "service_test_common.h" +#include "system_ability.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompServiceTest"}; +static AccessTokenID g_selfTokenId = 0; +} + +void SecCompServiceTest::SetUpTestCase() +{ + system("kill -9 `pidof security_compon`"); +} + +void SecCompServiceTest::TearDownTestCase() +{} + +void SecCompServiceTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (secCompService_ != nullptr) { + return; + } + SecCompService* ptr = new (std::nothrow) SecCompService(ServiceTestCommon::SA_ID, true); + secCompService_ = sptr(ptr); + ASSERT_NE(nullptr, secCompService_); + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + ASSERT_NE(nullptr, secCompService_->appStateObserver_); + g_selfTokenId = GetSelfTokenID(); +} + +void SecCompServiceTest::TearDown() +{ + if (secCompService_ != nullptr) { + secCompService_->appStateObserver_ = nullptr; + } + secCompService_ = nullptr; + EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); +} + +/** + * @tc.name: Onstart001 + * @tc.desc: Test OnStart + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, OnStart001, TestSize.Level1) +{ + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->appStateObserver_ = nullptr; + secCompService_->OnStart(); + ASSERT_EQ(nullptr, secCompService_->appStateObserver_); + EXPECT_CALL(*secCompService_, Publish(testing::_)).WillOnce(testing::Return(false)); + + secCompService_->state_ = ServiceRunningState::STATE_NOT_START; + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + secCompService_->OnStart(); + ASSERT_EQ(ServiceRunningState::STATE_RUNNING, secCompService_->state_); + + secCompService_->OnStop(); + ASSERT_EQ(nullptr, secCompService_->appStateObserver_); +} + +/** + * @tc.name: RegisterAppStateObserver001 + * @tc.desc: Test RegisterAppStateObserver + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, RegisterAppStateObserver001, TestSize.Level1) +{ + // GetSystemAbilityManager get failed + secCompService_->appStateObserver_ = nullptr; + std::shared_ptr saClient = std::make_shared(); + ASSERT_NE(nullptr, saClient); + SystemAbilityManagerClient::clientInstance = saClient.get(); + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(nullptr)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // GetSystemAbility get app mgr failed + secCompService_->appStateObserver_ = nullptr; + SystemAbilityManagerProxy proxy(nullptr); + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // RegisterApplicationStateObserver failed + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + MockIRemoteObject object; + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + sptr appProxy = new (std::nothrow) MockAppMgrProxy(nullptr); + MockAppMgrProxy::g_MockAppMgrProxy = appProxy; + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(-1)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // GetForegroundApplications failed + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(0)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + GetForegroundApplications(testing::_)).WillOnce(testing::Return(-1)); + EXPECT_TRUE(secCompService_->RegisterAppStateObserver()); + EXPECT_EQ(static_cast(0), secCompService_->appStateObserver_->foregrandProcList_.size()); + + // get one foreground app + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(0)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, GetForegroundApplications(testing::_)) + .WillOnce([](std::vector& list) { + AppExecFwk::AppStateData data; + data.uid = 1000; + list.emplace_back(data); + return 0; + }); + EXPECT_TRUE(secCompService_->RegisterAppStateObserver()); + EXPECT_EQ(static_cast(1), secCompService_->appStateObserver_->foregrandProcList_.size()); + secCompService_->UnregisterAppStateObserver(); + SystemAbilityManagerClient::clientInstance = nullptr; +} + +/** + * @tc.name: UnregisterAppStateObserver001 + * @tc.desc: Test RegisterAppStateObserver + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UnregisterAppStateObserver001, TestSize.Level1) +{ + // GetSystemAbilityManager get failed + secCompService_->appStateObserver_ = nullptr; + sptr appProxy = new (std::nothrow) MockAppMgrProxy(nullptr); + secCompService_->iAppMgr_ = appProxy; + + EXPECT_CALL(*appProxy, UnregisterApplicationStateObserver(testing::_)).Times(testing::Exactly(0)); + secCompService_->UnregisterAppStateObserver(); +} + +/** + * @tc.name: GetCallerInfo001 + * @tc.desc: Test get caller info + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, GetCallerInfo001, TestSize.Level1) +{ + // not root uid + setuid(1); + SecCompCallerInfo caller; + EXPECT_FALSE(secCompService_->GetCallerInfo(caller)); + + // set token id to hap token, but uid is not in foreground + EXPECT_FALSE(secCompService_->GetCallerInfo(caller)); + setuid(0); + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + // add local uid to foreground. + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + EXPECT_TRUE(secCompService_->GetCallerInfo(caller)); +} + +/** + * @tc.name: UnregisterSecurityComponent001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UnregisterSecurityComponent001, TestSize.Level1) +{ + // get caller fail + EXPECT_EQ(SC_SERVICE_ERROR_COMPONENT_NOT_EXIST, + secCompService_->UnregisterSecurityComponent(ServiceTestCommon::TEST_SC_ID_1)); +} + +/** + * @tc.name: UpdateSecurityComponent001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UpdateSecurityComponent001, TestSize.Level1) +{ + // get caller fail + EXPECT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, + secCompService_->UpdateSecurityComponent(ServiceTestCommon::TEST_SC_ID_1, "")); + + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + EXPECT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, + secCompService_->UpdateSecurityComponent(ServiceTestCommon::TEST_SC_ID_1, "{a")); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test report security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + auto uid = getuid(); + // get caller fail + int32_t scId; + EXPECT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, + secCompService_->RegisterSecurityComponent(LOCATION_COMPONENT, "", scId)); + + nlohmann::json jsonRes; + ServiceTestCommon::BuildLocationComponentJson(jsonRes); + std::string locationInfo = jsonRes.dump(); + + // parse component json fail + ASSERT_EQ(0, SetSelfTokenID(ServiceTestCommon::HAP_TOKEN_ID)); + setuid(100); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + + EXPECT_EQ(SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST, + secCompService_->RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + uint8_t data[16] = { 0 }; + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) / + ServiceTestCommon::TIME_CONVERSION_UNIT, + .extraInfo.data = data, + .extraInfo.dataSize = 16, + }; + EXPECT_EQ(SC_ENHANCE_ERROR_IN_MALICIOUS_LIST, + secCompService_->ReportSecurityComponentClickEvent(scId, locationInfo, touch, nullptr)); + EXPECT_EQ(SC_SERVICE_ERROR_COMPONENT_NOT_EXIST, secCompService_->UnregisterSecurityComponent(scId)); + setuid(uid); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h new file mode 100644 index 0000000000000000000000000000000000000000..4786c06e8dd8ea9234225c5db7ef96332b04f9e7 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h @@ -0,0 +1,42 @@ +/* + * 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 SEC_COMP_SERVICE_TEST_H +#define SEC_COMP_SERVICE_TEST_H + +#include +#define private public +#include "sec_comp_service.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + sptr secCompService_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_SERVICE_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3693fb9a8fbceb4909c4747c6b10b9f3ed588765 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp @@ -0,0 +1,177 @@ +/* + * 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 "sec_comp_stub_test.h" + +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "sec_comp_click_event_parcel.h" +#include "service_test_common.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompStubTest"}; +} + +void SecCompStubTest::SetUpTestCase() +{} + +void SecCompStubTest::TearDownTestCase() +{} + +void SecCompStubTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (stub_ != nullptr) { + return; + } + + stub_ = new (std::nothrow) SecCompStubMock(); + ASSERT_NE(nullptr, stub_); +} + +void SecCompStubTest::TearDown() +{ + stub_ = nullptr; +} + +/** + * @tc.name: OnRemoteRequest001 + * @tc.desc: Test on remote request + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, OnRemoteRequest001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(u"wrong"); + ASSERT_EQ(SC_SERVICE_ERROR_IPC_REQUEST_FAIL, stub_->OnRemoteRequest(static_cast( + SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), data, reply, option)); + + data.WriteInterfaceToken(u"ohos.security.ISecCompService"); + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->OnRemoteRequest(static_cast( + SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), data, reply, option)); + + data.WriteInterfaceToken(u"ohos.security.ISecCompService"); + ASSERT_EQ(305, stub_->OnRemoteRequest(1000, data, reply, option)); +} + +/** + * @tc.name: RegisterSecurityComponentInner001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, RegisterSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->RegisterSecurityComponentInner(data, reply)); + + data.WriteUint32(UNKNOWN_SC_TYPE); + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, stub_->RegisterSecurityComponentInner(data, reply)); + + data.WriteUint32(MAX_SC_TYPE); + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, stub_->RegisterSecurityComponentInner(data, reply)); + + data.WriteUint32(LOCATION_COMPONENT); + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->RegisterSecurityComponentInner(data, reply)); + + data.WriteUint32(LOCATION_COMPONENT); + data.WriteString(""); + ASSERT_EQ(SC_OK, stub_->RegisterSecurityComponentInner(data, reply)); +} + +/** + * @tc.name: UpdateSecurityComponentInner001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, UpdateSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->UpdateSecurityComponentInner(data, reply)); + + data.WriteInt32(-1); + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, stub_->UpdateSecurityComponentInner(data, reply)); + + data.WriteInt32(1); + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->UpdateSecurityComponentInner(data, reply)); + + data.WriteInt32(1); + data.WriteString(""); + ASSERT_EQ(SC_OK, stub_->UpdateSecurityComponentInner(data, reply)); +} + +/** + * @tc.name: UnregisterSecurityComponentInner001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, UnregisterSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->UnregisterSecurityComponentInner(data, reply)); + + data.WriteInt32(-1); + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, stub_->UnregisterSecurityComponentInner(data, reply)); + + data.WriteInt32(1); + ASSERT_EQ(SC_OK, stub_->UnregisterSecurityComponentInner(data, reply)); +} + +/** + * @tc.name: ReportSecurityComponentClickEventInner001 + * @tc.desc: Test report click event + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, ReportSecurityComponentClickEventInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->ReportSecurityComponentClickEventInner(data, reply)); + + data.WriteInt32(-1); + ASSERT_EQ(SC_SERVICE_ERROR_VALUE_INVALID, stub_->ReportSecurityComponentClickEventInner(data, reply)); + + data.WriteInt32(1); + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->ReportSecurityComponentClickEventInner(data, reply)); + + data.WriteInt32(1); + data.WriteString(""); + ASSERT_EQ(SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL, stub_->ReportSecurityComponentClickEventInner(data, reply)); + + data.WriteInt32(1); + data.WriteString(""); + SecCompClickEvent touchInfo; + sptr parcel = new (std::nothrow) SecCompClickEventParcel(); + parcel->touchInfoParams_ = touchInfo; + data.WriteParcelable(parcel); + ASSERT_EQ(SC_OK, stub_->ReportSecurityComponentClickEventInner(data, reply)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h new file mode 100644 index 0000000000000000000000000000000000000000..e56866c8b0a4aff13d0935bb7cb250d51b4f3400 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h @@ -0,0 +1,79 @@ +/* + * 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 SEC_COMP_STUB_TEST_H +#define SEC_COMP_STUB_TEST_H + +#include +#define private public +#include "sec_comp_stub.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { + +// stub is abstract class +struct SecCompStubMock : public SecCompStub { +public: + int32_t RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) override + { + return 0; + }; + + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override + { + return 0; + }; + + int32_t UnregisterSecurityComponent(int32_t scId) override + { + return 0; + }; + + int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, + const SecCompClickEvent& touchInfo, sptr callerToken) override + { + return 0; + }; + + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override + { + return true; + } + + sptr GetEnhanceRemoteObject() override + { + return nullptr; + } +}; + +class SecCompStubTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + sptr stub_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_STUB_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/service_test_common.cpp b/services/security_component_service/sa/test/unittest/src/service_test_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62a15456ef89fd957f0c33a07b747b203f890a6f --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/service_test_common.cpp @@ -0,0 +1,168 @@ +/* + * 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 "service_test_common.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void ServiceTestCommon::BuildLocationComponentJson(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + { JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + { JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + { JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + { JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, ServiceTestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} + +void ServiceTestCommon::BuildSaveComponentJson(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = SAVE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, ServiceTestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} + +void ServiceTestCommon::BuildPasteComponentJson(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = PASTE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, ServiceTestCommon::TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, ServiceTestCommon::TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, ServiceTestCommon::TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, ServiceTestCommon::TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, ServiceTestCommon::TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, ServiceTestCommon::TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, ServiceTestCommon::TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, ServiceTestCommon::TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, ServiceTestCommon::TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/test/unittest/src/service_test_common.h b/services/security_component_service/sa/test/unittest/src/service_test_common.h new file mode 100644 index 0000000000000000000000000000000000000000..078189f9b7d314e3569566e5d3765f796d4cd6eb --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/service_test_common.h @@ -0,0 +1,65 @@ +/* + * 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 SERVICE_TEST_COMMON_H +#define SERVICE_TEST_COMMON_H +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class ServiceTestCommon { +public: + static constexpr int32_t TEST_UID_1 = 1; + static constexpr int32_t TEST_UID_2 = 2; + static constexpr int32_t TEST_PID_1 = 1; + static constexpr int32_t TEST_PID_2 = 2; + static constexpr int32_t TEST_PID_3 = 3; + static constexpr int32_t TEST_SC_ID_1 = 1; + static constexpr int32_t TEST_SC_ID_2 = 2; + static constexpr int32_t TEST_INVALID_SC_ID = -1; + static constexpr int32_t SC_ID_START = 1000; + static constexpr int32_t SA_ID = 3506; + + static constexpr float TEST_SIZE = 100.0; + static constexpr double TEST_COORDINATE = 100.0; + static constexpr double TEST_DIFF_COORDINATE = 200.0; + static constexpr double TEST_DIMENSION = 100.0; + static constexpr double TEST_INVALID_DIMENSION = -100.0; + static constexpr double ZERO_OFFSET = 0.0F; + static constexpr uint32_t TEST_INVALID_SIZE = 0; + static constexpr uint32_t QUARTER = 4; + + static constexpr uint32_t TEST_COLOR_INVALID = 0x66000000; + static constexpr uint32_t TEST_COLOR_BLACK = 0x00000000; + static constexpr uint32_t TEST_COLOR_WHITE = 0xffffffff; + static constexpr uint32_t TEST_COLOR_YELLOW = 0xff7fff00; + static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; + static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; + + static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; + static constexpr uint32_t MAX_INT_NUM = 0x7fffffff; + static constexpr uint32_t HAP_TOKEN_ID = 537715419; + static constexpr uint32_t TEST_TOKEN_ID = 1; + + static void BuildLocationComponentJson(nlohmann::json& jsonComponent); + static void BuildSaveComponentJson(nlohmann::json& jsonComponent); + static void BuildPasteComponentJson(nlohmann::json& jsonComponent); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SERVICE_TEST_COMMON_H diff --git a/test/fuzztest/security_component/BUILD.gn b/test/fuzztest/security_component/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8d2c4335c3f86f0029883e67a5a31fcc1b1c5754 --- /dev/null +++ b/test/fuzztest/security_component/BUILD.gn @@ -0,0 +1,34 @@ +# 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. + +group("fuzztest") { + testonly = true + deps = [] + + deps += [ + "getenhanceremoteobjectInner_fuzzer:GetEnhanceRemoteObjectInnerFuzzTest", + "getenhanceremoteobject_fuzzer:GetEnhanceRemoteObjectFuzzTest", + "getpointereventenhancedata_fuzzer:GetPointerEventEnhanceDataFuzzTest", + "reduceafterverifysavepermissionInner_fuzzer:ReduceAfterVerifySavePermissionInnerFuzzTest", + "reduceafterverifysavepermission_fuzzer:ReduceAfterVerifySavePermissionFuzzTest", + "registersecuritycomponentInner_fuzzer:RegisterSecurityComponentInnerFuzzTest", + "registersecuritycomponent_fuzzer:RegisterSecurityComponentFuzzTest", + "reportsecuritycomponentclickeventInner_fuzzer:ReportSecurityComponentClickEventInnerFuzzTest", + "reportsecuritycomponentclickevent_fuzzer:ReportSecurityComponentClickEventFuzzTest", + "setenhancecfg_fuzzer:SetEnhanceCfgFuzzTest", + "unregistersecuritycomponentInner_fuzzer:UnregisterSecurityComponentInnerFuzzTest", + "unregistersecuritycomponent_fuzzer:UnregisterSecurityComponentFuzzTest", + "updatesecuritycomponentInner_fuzzer:UpdateSecurityComponentInnerFuzzTest", + "updatesecuritycomponent_fuzzer:UpdateSecurityComponentFuzzTest", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..68d43fe44ff6503698e930fac87b974e12a9659f --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetEnhanceRemoteObjectInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getenhanceremoteobjectInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48d375e56a93311aa4d5061e5e4e6664b72bae80 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getenhanceremoteobjectInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetEnhanceRemoteObjectInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetEnhanceRemoteObjectInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a3ec5aaea653d36d5318f656ee77a9177c06579a --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h @@ -0,0 +1,24 @@ +/* + * 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 GET_ENHANCE_REMOTE_OBJECT_INNER_FUZZER_H +#define GET_ENHANCE_REMOTE_OBJECT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_stub.h" +#include "sec_comp_service.h" + +#endif diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d0a5c65c17a5a6b2cfd862a49170a52f41831d70 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetEnhanceRemoteObjectFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getenhanceremoteobject_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getenhanceremoteobject_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47d929378e2b804496c1c30332ac5c6ea2267219 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getenhanceremoteobject_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetEnhanceRemoteObjectFuzzTest(const uint8_t *data, size_t size) +{ + bool isLoad = true; + SecCompKit::GetEnhanceRemoteObject(isLoad); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetEnhanceRemoteObjectFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a907797afc598a88856dcd1444e49c1510034694 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h @@ -0,0 +1,23 @@ +/* + * 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 GET_ENHANCE_REMOTE_OBJECT_FUZZER_H +#define GET_ENHANCE_REMOTE_OBJECT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bca0c526a208a37a3c441bb55c9459fed0aab913 --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetPointerEventEnhanceDataFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getpointereventenhancedata_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/enhance_kits/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getpointereventenhancedata_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c894798b9c190deff1969bac1f979caed4b9112b --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp @@ -0,0 +1,43 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getpointereventenhancedata_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetPointerEventEnhanceDataFuzzTest(const uint8_t *data, size_t size) +{ + uint8_t *data1 = const_cast(data); + uint8_t enhanceData[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + uint32_t enhancedataLen = 10; + SecCompEnhanceKit::GetPointerEventEnhanceData(data1, size, enhanceData, enhancedataLen); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetPointerEventEnhanceDataFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5d8ac757c41e1ad06bacad2317b869cdc9a810cd --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h @@ -0,0 +1,23 @@ +/* + * 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 GET_POINTER_EVENT_ENHANCE_DATA_FUZZER_H +#define GET_POINTER_EVENT_ENHANCE_DATA_FUZZER_H + +#define FUZZ_PROJECT_NAME "getpointereventenhancedata_fuzzer" + +#include "sec_comp_enhance_kit.h" + +#endif diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ff5172ec390ea64fbe429c57ceafd0d5be29cb8f --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReduceAfterVerifySavePermissionInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reduceafterverifysavepermissionInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5afd4e1204b82cf950d315e66bc2b8e62ec95fd2 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reduceafterverifysavepermissionInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReduceAfterVerifySavePermissionInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReduceAfterVerifySavePermissionInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d17798de5c79ea13f3b8ed7ec30ab65d06037cb7 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h @@ -0,0 +1,24 @@ +/* + * 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 REDUCE_AFTER_VERIFY_SAVEPERMISSION_INNER_FUZZER_H +#define REDUCE_AFTER_VERIFY_SAVEPERMISSION_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_stub.h" +#include "sec_comp_service.h" + +#endif diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aec22dc6f63f11dfd9e2df2414fc8cf9eb3f4b8a --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReduceAfterVerifySavePermissionFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reduceafterverifysavepermission_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62a7c88eb90597e405e9be22c103d57e4332ee91 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp @@ -0,0 +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. + */ + +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reduceafterverifysavepermission_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReduceAfterVerifySavePermissionFuzzTest(const uint8_t *data, size_t size) +{ + SecCompKit::ReduceAfterVerifySavePermission(size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReduceAfterVerifySavePermissionFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6d024ef8d358f57f1e81d13a7ad4ba841ce6c568 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h @@ -0,0 +1,23 @@ +/* + * 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 REDUCE_AFTER_VERIFY_SAVEPERMISSION_FUZZER_H +#define REDUCE_AFTER_VERIFY_SAVEPERMISSION_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif // TEST_FUZZTEST_SECURITY_COMPONENT_FUZZER_H diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3e81ae7618698e22339845259142ba0f7f6692f9 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("RegisterSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "registersecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24385f9d8e981b516ebf272e5804984f3d0b3328 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,51 @@ +/* + * 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 +#include +#include +#include +#include "registersecuritycomponentInner_fuzzer.h" +#include "accesstoken_kit.h" +#include "sec_comp_service.h" +#include "securec.h" +#include "token_setproc.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void RegisterSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = + SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = + std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::RegisterSecurityComponentInnerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a8ada33ca5202605ee006fbb1bc54ef0a24fb4d6 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 REGISTER_SECURITY_COMPONENT_INNER_FUZZER_H +#define REGISTER_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..68f586d0d1a65f841fe6abda64e6b8e1d942de6a --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,50 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("RegisterSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/registersecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + "//third_party/json/test/thirdparty/fifo_map", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "registersecuritycomponent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea9d2753d2e0d1ca0e8ea7d7ce587c9ad92cf729 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp @@ -0,0 +1,43 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "registersecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void RegisterSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + std::string componentInfo(reinterpret_cast(data), size); + int32_t scId = size; + enum SecCompType type = UNKNOWN_SC_TYPE; + SecCompKit::RegisterSecurityComponent(type, componentInfo, scId); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::RegisterSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..667b5925c6e6dbf87ca0eca15a4c3aba34c69d27 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 REGISTER_SECURITY_COMPONENT_FUZZER_H +#define REGISTER_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fa374fa989a1783a1c43d3119d553e8f73133243 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReportSecurityComponentClickEventInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reportsecuritycomponentclickeventInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cea50866d887a0f3368a56c6b7f6b4ae21c1635 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "reportsecuritycomponentclickeventInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReportSecurityComponentClickEventInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReportSecurityComponentClickEventInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..8af2a89541d9a6834b758fc0bdc21a9b00e26622 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 REPORT_SECURITY_COMPONENT_CLICK_EVENT_INNER_FUZZER_H +#define REPORT_SECURITY_COMPONENT_CLICK_EVENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1ac949d7c2233da9e7fae24fa9c0ed1d6a868d1c --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn @@ -0,0 +1,50 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReportSecurityComponentClickEventFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + "//third_party/json/test/thirdparty/fifo_map", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reportsecuritycomponentclickevent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89477c3af681f53de2606f72f43c5ee367d72cd9 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp @@ -0,0 +1,51 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reportsecuritycomponentclickevent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReportSecurityComponentClickEventFuzzTest(const uint8_t *data, size_t size) +{ + std::string componentInfo(reinterpret_cast(data), size); + uint8_t *data1 = const_cast(data); + const double touchX = size; + const double touchY = size; + const uint64_t timesStamp = size; + struct SecCompClickEvent touchInfo; + touchInfo.touchX = touchX; + touchInfo.touchY = touchY; + touchInfo.timestamp = timesStamp; + touchInfo.extraInfo.data = data1; + touchInfo.extraInfo.dataSize = size; + SecCompKit::ReportSecurityComponentClickEvent(size, componentInfo, touchInfo); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReportSecurityComponentClickEventFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..989ec28ef896a09708630e0d6b05fe4f10a25eff --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h @@ -0,0 +1,23 @@ +/* + * 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 REPORT_SECURITY_COMPONENT_CLICK_EVENT_FUZZER_H +#define REPORT_SECURITY_COMPONENT_CLICK_EVENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn b/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c7a950f93943331689e8b12c5c50e8af7d828d2f --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("SetEnhanceCfgFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${sec_comp_dir}/test/fuzztest/security_component/setenhancecfg_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/enhance_kits/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "setenhancecfg_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init b/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml b/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be86e485bd5290118d0ff3919b6a2d025e374f9d --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "setenhancecfg_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void SetEnhanceCfgFuzzTest(const uint8_t *data, size_t size) +{ + uint8_t *cfg = const_cast(data); + SecCompEnhanceKit::SetEnhanceCfg(cfg, size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::SetEnhanceCfgFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..47d46f126e9fb2ff55ca30e75745c5004954f54d --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 SETENHANCE_CFG_FUZZER_H +#define SETENHANCE_CFG_FUZZER_H + +#define FUZZ_PROJECT_NAME "setenhancecfg_fuzzer" +#include "sec_comp_enhance_kit.h" +#endif diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..02f554eccc6ba019266d7689d61e851b49e1c8b2 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UnregisterSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "unregistersecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8eddb37a6946477d65e6cbf79a94e489a37e8b2f --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "unregistersecuritycomponentInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UnregisterSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UnregisterSecurityComponentInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..02a5307ec877556820a75c99eac14d98ff30cf0f --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 UNREGISTER_SECURITY_COMPONENT_INNER_FUZZER_H +#define UNREGISTER_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2afbc272f29e40ce4434fd8d5d1745f9ad7e9902 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UnregisterSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "unregistersecuritycomponent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3219fb3fc111003a563fcf849132c5db2d00bf9c --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp @@ -0,0 +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. + */ + +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "unregistersecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UnregisterSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + SecCompKit::UnregisterSecurityComponent(size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UnregisterSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..794af54033ff861e656ec5cb3d2953ded5e0213a --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 UNREGISTER_SECURITY_COMPONENT_FUZZER_H +#define UNREGISTER_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..061dcc7612c13dfca5cc3586863a2b90e7254f14 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UpdateSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "updatesecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f1ab9fc6ad74a5604b27d450fab21d9c2bf24ca --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "updatesecuritycomponentInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UpdateSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UpdateSecurityComponentInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..2d2559048b020f2691e644aa264d2dc56fb064c6 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 UPDATE_SECURITY_COMPONENT_INNER_FUZZER_H +#define UPDATE_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0e675b23ac98bc6c6e092cf4a4d77ed0869bf676 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,52 @@ +# 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("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UpdateSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/updatesecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "updatesecuritycomponent_fuzzer.cpp" ] + + deps = [ + "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + "${sec_comp_dir}/services/security_component_service/sa:security_component_service", + ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a15493c09fcc72fc7410e5628983f87b33d9f41 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "updatesecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UpdateSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + std::string str(reinterpret_cast(data), size); + SecCompKit::UpdateSecurityComponent(size, str); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UpdateSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..85f7f166a82a7daabc347bcfa3b1a4af785aae4e --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 UPDATE_SECURITY_COMPONENT_FUZZER_H +#define UPDATE_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif