diff --git a/bundle.json b/bundle.json index 7ef8ef689403719bf583ef97510fb8efa500c0b9..d8a427cf1ba62615347a962db1e96ecba3b3aa50 100644 --- a/bundle.json +++ b/bundle.json @@ -60,6 +60,7 @@ "c_utils", "data_share", "dupdate_engine", + "netmanager_base", "netmanager_ext", "hisysevent_native", "hiviewdfx_hilog_native", diff --git a/common/native/BUILD.gn b/common/native/BUILD.gn index 4e380b4fc5462acb5095bc77d8b47ab6aa5753cc..47798b534bb3f1bf3fdaa9b633a329cffa64d1d1 100644 --- a/common/native/BUILD.gn +++ b/common/native/BUILD.gn @@ -14,7 +14,10 @@ import("//build/ohos.gni") config("edm_commom_all_dependent_configs") { - include_dirs = [ "include" ] + include_dirs = [ + "include", + "include/plugin_utils", + ] } ohos_shared_library("edm_commom") { @@ -22,7 +25,8 @@ ohos_shared_library("edm_commom") { "./src/edm_data_ability_utils.cpp", "./src/edm_permission.cpp", "./src/edm_sys_manager.cpp", - "./src/message_parcel_utils.cpp", + "./src/plugin_utils/iptables_utils.cpp", + "./src/plugin_utils/message_parcel_utils.cpp", ] configs = [ diff --git a/common/native/include/plugin_utils/iptables_utils.h b/common/native/include/plugin_utils/iptables_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ac4f4bfbaaf3e21bcea1c0865560283e974f0dc1 --- /dev/null +++ b/common/native/include/plugin_utils/iptables_utils.h @@ -0,0 +1,81 @@ +/* + * 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_NETWORK_MANAGER_INCLUDE_IPTABLES_UTILS_H +#define INTERFACES_INNER_API_NETWORK_MANAGER_INCLUDE_IPTABLES_UTILS_H + +#include + +#include "message_parcel.h" + +namespace OHOS { +namespace EDM { +namespace IPTABLES { +enum class AddMethod { INVALID = -1, APPEND, INSERT }; + +enum class Direction { INVALID = -1, INPUT, OUTPUT }; + +enum class Action { INVALID = -1, ALLOW, DENY }; + +enum class Protocol { INVALID = -1, ALL, TCP, UDP, ICMP }; + +struct Firewall { + std::string srcAddr; + std::string destAddr; + std::string srcPort; + std::string destPort; + std::string uid; + Direction direction; + Action action; + Protocol protocol; +}; + +struct AddFilter : Firewall { + uint32_t ruleNo = 0; + AddMethod method; + AddFilter() + { + protocol = Protocol::INVALID; + action = Action::INVALID; + direction = Direction::INVALID; + method = AddMethod::INVALID; + } +}; + +struct RemoveFilter : Firewall { + RemoveFilter() + { + protocol = Protocol::INVALID; + action = Action::INVALID; + direction = Direction::INVALID; + } +}; + +class IptablesUtils { +public: + static void WriteAddFilterConfig(const AddFilter &fiter, MessageParcel &data); + static void WriteRemoveFilterConfig(const RemoveFilter &fiter, MessageParcel &data); + static void ReadAddFilterConfig(AddFilter &fiter, MessageParcel &data); + static void ReadRemoveFilterConfig(RemoveFilter &fiter, MessageParcel &data); + static bool ProcessFirewallAction(int32_t type, Action &action); + static bool ProcessFirewallMethod(int32_t type, AddMethod &method); + static bool ProcessFirewallDirection(int32_t type, Direction &direction); + static void ProcessFirewallProtocol(int32_t type, Protocol &protocol); +}; +} // namespace IPTABLES +} // namespace EDM +} // namespace OHOS + +#endif // INTERFACES_INNER_API_NETWORK_MANAGER_INCLUDE_IPTABLES_UTILS_H diff --git a/common/native/include/message_parcel_utils.h b/common/native/include/plugin_utils/message_parcel_utils.h similarity index 50% rename from common/native/include/message_parcel_utils.h rename to common/native/include/plugin_utils/message_parcel_utils.h index 5f11bd093a201ab44b929f68bf42d64dac82759b..c4adee09e95d0b643c03dce565dce437b75a3fb6 100644 --- a/common/native/include/message_parcel_utils.h +++ b/common/native/include/plugin_utils/message_parcel_utils.h @@ -1,39 +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 COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H -#define COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H - -#include -#include "edm_errors.h" -#include "message_parcel.h" -#include "wifi_msg.h" - -namespace OHOS { -namespace EDM { -class MessageParcelUtils { -public: - static void WriteWifiDeviceConfig(const Wifi::WifiDeviceConfig &config, MessageParcel &data); - static void WriteIpAddress(MessageParcel &data, const Wifi::WifiIpAddress &address); - static void ReadWifiDeviceConfig(MessageParcel &data, Wifi::WifiDeviceConfig &config); - static void ProcessAssignIpMethod(int32_t ipMethod, Wifi::WifiIpConfig &ipConfig); - static void ProcessPhase2Method(int32_t phase2, Wifi::WifiEapConfig &eapConfig); - static void ProcessConfigureProxyMethod(int32_t proxyMethod, Wifi::WifiProxyConfig &proxyConfig); - static void ProcessPrivacyConfig(int32_t privacyConfig, Wifi::WifiDeviceConfig &config); - static void ReadIpAddress(MessageParcel &data, Wifi::WifiIpAddress &address); -}; -} // namespace EDM -} // namespace OHOS -#endif // COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H \ No newline at end of file +/* + * 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 COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H +#define COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H + +#include + +#include "edm_errors.h" +#include "message_parcel.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace EDM { +class MessageParcelUtils { +public: + static void WriteWifiDeviceConfig(const Wifi::WifiDeviceConfig &config, MessageParcel &data); + static void WriteIpAddress(MessageParcel &data, const Wifi::WifiIpAddress &address); + static void ReadWifiDeviceConfig(MessageParcel &data, Wifi::WifiDeviceConfig &config); + static void ProcessAssignIpMethod(int32_t ipMethod, Wifi::WifiIpConfig &ipConfig); + static void ProcessPhase2Method(int32_t phase2, Wifi::WifiEapConfig &eapConfig); + static void ProcessConfigureProxyMethod(int32_t proxyMethod, Wifi::WifiProxyConfig &proxyConfig); + static void ProcessPrivacyConfig(int32_t privacyConfig, Wifi::WifiDeviceConfig &config); + static void ReadIpAddress(MessageParcel &data, Wifi::WifiIpAddress &address); +}; +} // namespace EDM +} // namespace OHOS +#endif // COMMON_NATIVE_INCLUDE_MESSAGE_PARCEL_UTILS_H \ No newline at end of file diff --git a/common/native/src/plugin_utils/iptables_utils.cpp b/common/native/src/plugin_utils/iptables_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87408382dc5ca4fe0e023dbead3faa3f828df027 --- /dev/null +++ b/common/native/src/plugin_utils/iptables_utils.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 "iptables_utils.h" + +#include "edm_log.h" + +namespace OHOS { +namespace EDM { +namespace IPTABLES { +void IptablesUtils::WriteAddFilterConfig(const AddFilter &filter, MessageParcel &data) +{ + data.WriteUint32(filter.ruleNo); + data.WriteString(filter.srcAddr); + data.WriteString(filter.destAddr); + data.WriteString(filter.srcPort); + data.WriteString(filter.destPort); + data.WriteString(filter.uid); + data.WriteInt32(static_cast(filter.method)); + data.WriteInt32(static_cast(filter.direction)); + data.WriteInt32(static_cast(filter.action)); + data.WriteInt32(static_cast(filter.protocol)); +} + +void IptablesUtils::ReadAddFilterConfig(AddFilter &filter, MessageParcel &data) +{ + filter.ruleNo = data.ReadUint32(); + filter.srcAddr = data.ReadString(); + filter.destAddr = data.ReadString(); + filter.srcPort = data.ReadString(); + filter.destPort = data.ReadString(); + filter.uid = data.ReadString(); + IptablesUtils::ProcessFirewallMethod(data.ReadInt32(), filter.method); + IptablesUtils::ProcessFirewallDirection(data.ReadInt32(), filter.direction); + IptablesUtils::ProcessFirewallAction(data.ReadInt32(), filter.action); + IptablesUtils::ProcessFirewallProtocol(data.ReadInt32(), filter.protocol); +} + +void IptablesUtils::WriteRemoveFilterConfig(const RemoveFilter &filter, MessageParcel &data) +{ + data.WriteString(filter.srcAddr); + data.WriteString(filter.destAddr); + data.WriteString(filter.srcPort); + data.WriteString(filter.destPort); + data.WriteString(filter.uid); + data.WriteInt32(static_cast(filter.direction)); + data.WriteInt32(static_cast(filter.action)); + data.WriteInt32(static_cast(filter.protocol)); +} + +void IptablesUtils::ReadRemoveFilterConfig(RemoveFilter &filter, MessageParcel &data) +{ + filter.srcAddr = data.ReadString(); + filter.destAddr = data.ReadString(); + filter.srcPort = data.ReadString(); + filter.destPort = data.ReadString(); + filter.uid = data.ReadString(); + IptablesUtils::ProcessFirewallDirection(data.ReadInt32(), filter.direction); + IptablesUtils::ProcessFirewallAction(data.ReadInt32(), filter.action); + IptablesUtils::ProcessFirewallProtocol(data.ReadInt32(), filter.protocol); +} + +bool IptablesUtils::ProcessFirewallAction(int32_t type, Action &action) +{ + if (type >= static_cast(Action::ALLOW) && type <= static_cast(Action::DENY)) { + action = Action(type); + return true; + } + return false; +} + +bool IptablesUtils::ProcessFirewallMethod(int32_t type, AddMethod &method) +{ + if (type >= static_cast(AddMethod::APPEND) && type <= static_cast(AddMethod::INSERT)) { + method = AddMethod(type); + return true; + } + return false; +} + +bool IptablesUtils::ProcessFirewallDirection(int32_t type, Direction &direction) +{ + if (type >= static_cast(Direction::INPUT) && type <= static_cast(Direction::OUTPUT)) { + direction = Direction(type); + return true; + } + return false; +} + +void IptablesUtils::ProcessFirewallProtocol(int32_t type, Protocol &protocol) +{ + if (type >= static_cast(Protocol::ALL) && type <= static_cast(Protocol::ICMP)) { + protocol = Protocol(type); + } +} +} // namespace IPTABLES +} // namespace EDM +} // namespace OHOS \ No newline at end of file diff --git a/common/native/src/message_parcel_utils.cpp b/common/native/src/plugin_utils/message_parcel_utils.cpp similarity index 96% rename from common/native/src/message_parcel_utils.cpp rename to common/native/src/plugin_utils/message_parcel_utils.cpp index 212b19cf28f102faeb2e5543446a01d8f2a2924f..a20e345dbba87a7f865290fb241809f60a2bfb35 100644 --- a/common/native/src/message_parcel_utils.cpp +++ b/common/native/src/plugin_utils/message_parcel_utils.cpp @@ -1,208 +1,209 @@ -/* - * 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 "message_parcel_utils.h" -#include "edm_log.h" -#include "securec.h" - -namespace OHOS { -namespace EDM { -void MessageParcelUtils::WriteWifiDeviceConfig(const Wifi::WifiDeviceConfig &config, MessageParcel &data) -{ - data.WriteInt32(config.networkId); - data.WriteInt32(config.status); - data.WriteString(config.bssid); - data.WriteString(config.ssid); - data.WriteInt32(config.band); - data.WriteInt32(config.channel); - data.WriteInt32(config.frequency); - data.WriteInt32(config.level); - data.WriteBool(config.isPasspoint); - data.WriteBool(config.isEphemeral); - data.WriteString(config.preSharedKey); - data.WriteString(config.keyMgmt); - for (int i = 0; i < WEPKEYS_SIZE; i++) { - data.WriteString(config.wepKeys[i]); - } - data.WriteInt32(config.wepTxKeyIndex); - data.WriteInt32(config.priority); - data.WriteBool(config.hiddenSSID); - data.WriteInt32(static_cast(config.wifiIpConfig.assignMethod)); - WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.ipAddress.address); - data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); - data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.flags); - data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.scope); - WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.gateway); - WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer1); - WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer2); - data.WriteString(config.wifiIpConfig.staticIpAddress.domains); - data.WriteString(config.wifiEapConfig.eap); - data.WriteString(config.wifiEapConfig.identity); - data.WriteString(config.wifiEapConfig.password); - data.WriteString(config.wifiEapConfig.clientCert); - data.WriteString(config.wifiEapConfig.privateKey); - data.WriteUInt8Vector(config.wifiEapConfig.certEntry); - data.WriteString(std::string(config.wifiEapConfig.certPassword)); - data.WriteInt32(static_cast(config.wifiEapConfig.phase2Method)); - data.WriteInt32(static_cast(config.wifiProxyconfig.configureMethod)); - data.WriteString(config.wifiProxyconfig.autoProxyConfig.pacWebAddress); - data.WriteString(config.wifiProxyconfig.manualProxyConfig.serverHostName); - data.WriteInt32(config.wifiProxyconfig.manualProxyConfig.serverPort); - data.WriteString(config.wifiProxyconfig.manualProxyConfig.exclusionObjectList); - data.WriteInt32(static_cast(config.wifiPrivacySetting)); -} - -void MessageParcelUtils::WriteIpAddress(MessageParcel &data, const Wifi::WifiIpAddress &address) -{ - data.WriteInt32(address.family); - data.WriteUint32(address.addressIpv4); - size_t size = address.addressIpv6.size(); - data.WriteInt32(size); - for (size_t i = 0; i < size; i++) { - data.WriteUint8(address.addressIpv6[i]); - } -} - -void MessageParcelUtils::ReadWifiDeviceConfig(MessageParcel &data, Wifi::WifiDeviceConfig &config) -{ - config.networkId = data.ReadInt32(); - config.status = data.ReadInt32(); - config.bssid = data.ReadString(); - config.ssid = data.ReadString(); - config.band = data.ReadInt32(); - config.channel = data.ReadInt32(); - config.frequency = data.ReadInt32(); - config.level = data.ReadInt32(); - config.isPasspoint = data.ReadBool(); - config.isEphemeral = data.ReadBool(); - config.preSharedKey = data.ReadString(); - config.keyMgmt = data.ReadString(); - for (int i = 0; i < WEPKEYS_SIZE; i++) { - config.wepKeys[i] = data.ReadString(); - } - config.wepTxKeyIndex = data.ReadInt32(); - config.priority = data.ReadInt32(); - config.hiddenSSID = data.ReadBool(); - ProcessAssignIpMethod(data.ReadInt32(), config.wifiIpConfig); - ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.ipAddress.address); - config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength = data.ReadInt32(); - config.wifiIpConfig.staticIpAddress.ipAddress.flags = data.ReadInt32(); - config.wifiIpConfig.staticIpAddress.ipAddress.scope = data.ReadInt32(); - ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.gateway); - ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer1); - ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer2); - config.wifiIpConfig.staticIpAddress.domains = data.ReadString(); - config.wifiEapConfig.eap = data.ReadString(); - config.wifiEapConfig.identity = data.ReadString(); - config.wifiEapConfig.password = data.ReadString(); - config.wifiEapConfig.clientCert = data.ReadString(); - config.wifiEapConfig.privateKey = data.ReadString(); - data.ReadUInt8Vector(&config.wifiEapConfig.certEntry); - strncpy_s(config.wifiEapConfig.certPassword, sizeof(config.wifiEapConfig.certPassword), - data.ReadString().c_str(), sizeof(config.wifiEapConfig.certPassword) - 1); - ProcessPhase2Method(data.ReadInt32(), config.wifiEapConfig); - ProcessConfigureProxyMethod(data.ReadInt32(), config.wifiProxyconfig); - config.wifiProxyconfig.autoProxyConfig.pacWebAddress = data.ReadString(); - config.wifiProxyconfig.manualProxyConfig.serverHostName = data.ReadString(); - config.wifiProxyconfig.manualProxyConfig.serverPort = data.ReadInt32(); - config.wifiProxyconfig.manualProxyConfig.exclusionObjectList = data.ReadString(); - ProcessPrivacyConfig(data.ReadInt32(), config); -} - -void MessageParcelUtils::ProcessAssignIpMethod(int32_t ipMethod, Wifi::WifiIpConfig &ipConfig) -{ - switch (ipMethod) { - case static_cast(Wifi::AssignIpMethod::DHCP): - ipConfig.assignMethod = Wifi::AssignIpMethod::DHCP; - break; - case static_cast(Wifi::AssignIpMethod::STATIC): - ipConfig.assignMethod = Wifi::AssignIpMethod::STATIC; - break; - default: - ipConfig.assignMethod = Wifi::AssignIpMethod::UNASSIGNED; - break; - } -} - -void MessageParcelUtils::ProcessPhase2Method(int32_t phase2, Wifi::WifiEapConfig &eapConfig) -{ - switch (phase2) { - case static_cast(Wifi::Phase2Method::PAP): - eapConfig.phase2Method = Wifi::Phase2Method::PAP; - break; - case static_cast(Wifi::Phase2Method::MSCHAP): - eapConfig.phase2Method = Wifi::Phase2Method::MSCHAP; - break; - case static_cast(Wifi::Phase2Method::MSCHAPV2): - eapConfig.phase2Method = Wifi::Phase2Method::MSCHAPV2; - break; - case static_cast(Wifi::Phase2Method::GTC): - eapConfig.phase2Method = Wifi::Phase2Method::GTC; - break; - case static_cast(Wifi::Phase2Method::SIM): - eapConfig.phase2Method = Wifi::Phase2Method::SIM; - break; - case static_cast(Wifi::Phase2Method::AKA): - eapConfig.phase2Method = Wifi::Phase2Method::AKA; - break; - case static_cast(Wifi::Phase2Method::AKA_PRIME): - eapConfig.phase2Method = Wifi::Phase2Method::AKA_PRIME; - break; - default: - eapConfig.phase2Method = Wifi::Phase2Method::NONE; - break; - } -} - -void MessageParcelUtils::ProcessConfigureProxyMethod(int32_t proxyMethod, Wifi::WifiProxyConfig &proxyConfig) -{ - switch (proxyMethod) { - case static_cast(Wifi::ConfigureProxyMethod::AUTOCONFIGUE): - proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::AUTOCONFIGUE; - break; - case static_cast(Wifi::ConfigureProxyMethod::MANUALCONFIGUE): - proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::MANUALCONFIGUE; - break; - default: - proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::CLOSED; - break; - } -} - -void MessageParcelUtils::ProcessPrivacyConfig(int32_t privacyConfig, Wifi::WifiDeviceConfig &config) -{ - if (privacyConfig == static_cast(Wifi::WifiPrivacyConfig::RANDOMMAC)) { - config.wifiPrivacySetting = Wifi::WifiPrivacyConfig::RANDOMMAC; - } else { - config.wifiPrivacySetting = Wifi::WifiPrivacyConfig::DEVICEMAC; - } -} - -void MessageParcelUtils::ReadIpAddress(MessageParcel &data, Wifi::WifiIpAddress &address) -{ - constexpr int MAX_LIMIT_SIZE = 1024; - address.family = data.ReadInt32(); - address.addressIpv4 = data.ReadUint32(); - int size = data.ReadInt32(); - if (size > MAX_LIMIT_SIZE) { - EDMLOGE("Read ip address parameter error: %{public}d", size); - return; - } - for (int i = 0; i < size; i++) { - address.addressIpv6.push_back(data.ReadUint8()); - } -} -} // EDM -} // OHOS \ No newline at end of file +/* + * 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 "message_parcel_utils.h" + +#include "edm_log.h" +#include "securec.h" + +namespace OHOS { +namespace EDM { +void MessageParcelUtils::WriteWifiDeviceConfig(const Wifi::WifiDeviceConfig &config, MessageParcel &data) +{ + data.WriteInt32(config.networkId); + data.WriteInt32(config.status); + data.WriteString(config.bssid); + data.WriteString(config.ssid); + data.WriteInt32(config.band); + data.WriteInt32(config.channel); + data.WriteInt32(config.frequency); + data.WriteInt32(config.level); + data.WriteBool(config.isPasspoint); + data.WriteBool(config.isEphemeral); + data.WriteString(config.preSharedKey); + data.WriteString(config.keyMgmt); + for (int i = 0; i < WEPKEYS_SIZE; i++) { + data.WriteString(config.wepKeys[i]); + } + data.WriteInt32(config.wepTxKeyIndex); + data.WriteInt32(config.priority); + data.WriteBool(config.hiddenSSID); + data.WriteInt32(static_cast(config.wifiIpConfig.assignMethod)); + WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.ipAddress.address); + data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.flags); + data.WriteInt32(config.wifiIpConfig.staticIpAddress.ipAddress.scope); + WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.gateway); + WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer1); + WriteIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer2); + data.WriteString(config.wifiIpConfig.staticIpAddress.domains); + data.WriteString(config.wifiEapConfig.eap); + data.WriteString(config.wifiEapConfig.identity); + data.WriteString(config.wifiEapConfig.password); + data.WriteString(config.wifiEapConfig.clientCert); + data.WriteString(config.wifiEapConfig.privateKey); + data.WriteUInt8Vector(config.wifiEapConfig.certEntry); + data.WriteString(std::string(config.wifiEapConfig.certPassword)); + data.WriteInt32(static_cast(config.wifiEapConfig.phase2Method)); + data.WriteInt32(static_cast(config.wifiProxyconfig.configureMethod)); + data.WriteString(config.wifiProxyconfig.autoProxyConfig.pacWebAddress); + data.WriteString(config.wifiProxyconfig.manualProxyConfig.serverHostName); + data.WriteInt32(config.wifiProxyconfig.manualProxyConfig.serverPort); + data.WriteString(config.wifiProxyconfig.manualProxyConfig.exclusionObjectList); + data.WriteInt32(static_cast(config.wifiPrivacySetting)); +} + +void MessageParcelUtils::WriteIpAddress(MessageParcel &data, const Wifi::WifiIpAddress &address) +{ + data.WriteInt32(address.family); + data.WriteUint32(address.addressIpv4); + size_t size = address.addressIpv6.size(); + data.WriteInt32(size); + for (size_t i = 0; i < size; i++) { + data.WriteUint8(address.addressIpv6[i]); + } +} + +void MessageParcelUtils::ReadWifiDeviceConfig(MessageParcel &data, Wifi::WifiDeviceConfig &config) +{ + config.networkId = data.ReadInt32(); + config.status = data.ReadInt32(); + config.bssid = data.ReadString(); + config.ssid = data.ReadString(); + config.band = data.ReadInt32(); + config.channel = data.ReadInt32(); + config.frequency = data.ReadInt32(); + config.level = data.ReadInt32(); + config.isPasspoint = data.ReadBool(); + config.isEphemeral = data.ReadBool(); + config.preSharedKey = data.ReadString(); + config.keyMgmt = data.ReadString(); + for (int i = 0; i < WEPKEYS_SIZE; i++) { + config.wepKeys[i] = data.ReadString(); + } + config.wepTxKeyIndex = data.ReadInt32(); + config.priority = data.ReadInt32(); + config.hiddenSSID = data.ReadBool(); + ProcessAssignIpMethod(data.ReadInt32(), config.wifiIpConfig); + ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.ipAddress.address); + config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength = data.ReadInt32(); + config.wifiIpConfig.staticIpAddress.ipAddress.flags = data.ReadInt32(); + config.wifiIpConfig.staticIpAddress.ipAddress.scope = data.ReadInt32(); + ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.gateway); + ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer1); + ReadIpAddress(data, config.wifiIpConfig.staticIpAddress.dnsServer2); + config.wifiIpConfig.staticIpAddress.domains = data.ReadString(); + config.wifiEapConfig.eap = data.ReadString(); + config.wifiEapConfig.identity = data.ReadString(); + config.wifiEapConfig.password = data.ReadString(); + config.wifiEapConfig.clientCert = data.ReadString(); + config.wifiEapConfig.privateKey = data.ReadString(); + data.ReadUInt8Vector(&config.wifiEapConfig.certEntry); + strncpy_s(config.wifiEapConfig.certPassword, sizeof(config.wifiEapConfig.certPassword), data.ReadString().c_str(), + sizeof(config.wifiEapConfig.certPassword) - 1); + ProcessPhase2Method(data.ReadInt32(), config.wifiEapConfig); + ProcessConfigureProxyMethod(data.ReadInt32(), config.wifiProxyconfig); + config.wifiProxyconfig.autoProxyConfig.pacWebAddress = data.ReadString(); + config.wifiProxyconfig.manualProxyConfig.serverHostName = data.ReadString(); + config.wifiProxyconfig.manualProxyConfig.serverPort = data.ReadInt32(); + config.wifiProxyconfig.manualProxyConfig.exclusionObjectList = data.ReadString(); + ProcessPrivacyConfig(data.ReadInt32(), config); +} + +void MessageParcelUtils::ProcessAssignIpMethod(int32_t ipMethod, Wifi::WifiIpConfig &ipConfig) +{ + switch (ipMethod) { + case static_cast(Wifi::AssignIpMethod::DHCP): + ipConfig.assignMethod = Wifi::AssignIpMethod::DHCP; + break; + case static_cast(Wifi::AssignIpMethod::STATIC): + ipConfig.assignMethod = Wifi::AssignIpMethod::STATIC; + break; + default: + ipConfig.assignMethod = Wifi::AssignIpMethod::UNASSIGNED; + break; + } +} + +void MessageParcelUtils::ProcessPhase2Method(int32_t phase2, Wifi::WifiEapConfig &eapConfig) +{ + switch (phase2) { + case static_cast(Wifi::Phase2Method::PAP): + eapConfig.phase2Method = Wifi::Phase2Method::PAP; + break; + case static_cast(Wifi::Phase2Method::MSCHAP): + eapConfig.phase2Method = Wifi::Phase2Method::MSCHAP; + break; + case static_cast(Wifi::Phase2Method::MSCHAPV2): + eapConfig.phase2Method = Wifi::Phase2Method::MSCHAPV2; + break; + case static_cast(Wifi::Phase2Method::GTC): + eapConfig.phase2Method = Wifi::Phase2Method::GTC; + break; + case static_cast(Wifi::Phase2Method::SIM): + eapConfig.phase2Method = Wifi::Phase2Method::SIM; + break; + case static_cast(Wifi::Phase2Method::AKA): + eapConfig.phase2Method = Wifi::Phase2Method::AKA; + break; + case static_cast(Wifi::Phase2Method::AKA_PRIME): + eapConfig.phase2Method = Wifi::Phase2Method::AKA_PRIME; + break; + default: + eapConfig.phase2Method = Wifi::Phase2Method::NONE; + break; + } +} + +void MessageParcelUtils::ProcessConfigureProxyMethod(int32_t proxyMethod, Wifi::WifiProxyConfig &proxyConfig) +{ + switch (proxyMethod) { + case static_cast(Wifi::ConfigureProxyMethod::AUTOCONFIGUE): + proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::AUTOCONFIGUE; + break; + case static_cast(Wifi::ConfigureProxyMethod::MANUALCONFIGUE): + proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::MANUALCONFIGUE; + break; + default: + proxyConfig.configureMethod = Wifi::ConfigureProxyMethod::CLOSED; + break; + } +} + +void MessageParcelUtils::ProcessPrivacyConfig(int32_t privacyConfig, Wifi::WifiDeviceConfig &config) +{ + if (privacyConfig == static_cast(Wifi::WifiPrivacyConfig::RANDOMMAC)) { + config.wifiPrivacySetting = Wifi::WifiPrivacyConfig::RANDOMMAC; + } else { + config.wifiPrivacySetting = Wifi::WifiPrivacyConfig::DEVICEMAC; + } +} + +void MessageParcelUtils::ReadIpAddress(MessageParcel &data, Wifi::WifiIpAddress &address) +{ + constexpr int MAX_LIMIT_SIZE = 1024; + address.family = data.ReadInt32(); + address.addressIpv4 = data.ReadUint32(); + int size = data.ReadInt32(); + if (size > MAX_LIMIT_SIZE) { + EDMLOGE("Read ip address parameter error: %{public}d", size); + return; + } + for (int i = 0; i < size; i++) { + address.addressIpv6.push_back(data.ReadUint8()); + } +} +} // namespace EDM +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_api/common/include/policy_info.h b/interfaces/inner_api/common/include/policy_info.h index 080fe34a657696f9126a145795273448afe0c811..c8afbfa1d3f377695c2467af977a7f85e70501d3 100644 --- a/interfaces/inner_api/common/include/policy_info.h +++ b/interfaces/inner_api/common/include/policy_info.h @@ -44,6 +44,7 @@ enum { UNINSTALL = 1020, DISABLED_PRINTER = 1021, DISABLED_HDC = 1022, + IPTABLES_RULE = 1023, POLICY_CODE_END = 3000, }; diff --git a/interfaces/inner_api/network_manager/include/network_manager_proxy.h b/interfaces/inner_api/network_manager/include/network_manager_proxy.h index b46bf218ac9860b7a3ba11612d87c2b6180c3a62..8e1275c2721af86568827cfa0702567ef665a347 100644 --- a/interfaces/inner_api/network_manager/include/network_manager_proxy.h +++ b/interfaces/inner_api/network_manager/include/network_manager_proxy.h @@ -17,6 +17,7 @@ #define INTERFACES_INNER_API_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_PROXY_H #include "enterprise_device_mgr_proxy.h" +#include "iptables_utils.h" namespace OHOS { namespace EDM { @@ -26,17 +27,21 @@ public: ~NetworkManagerProxy(); static std::shared_ptr GetNetworkManagerProxy(); int32_t GetAllNetworkInterfaces(const AppExecFwk::ElementName &admin, std::vector &networkInterface); - int32_t GetIpOrMacAddress(const AppExecFwk::ElementName &admin, const std::string &networkInterface, - int policyCode, std::string &info); + int32_t GetIpOrMacAddress(const AppExecFwk::ElementName &admin, const std::string &networkInterface, int policyCode, + std::string &info); int32_t SetNetworkInterfaceDisabled(const AppExecFwk::ElementName &admin, const std::string &networkInterface, bool isDisabled); int32_t IsNetworkInterfaceDisabled(const AppExecFwk::ElementName &admin, const std::string &networkInterface, bool &status); + int32_t AddIptablesFilterRule(const AppExecFwk::ElementName &admin, const IPTABLES::AddFilter &filter); + int32_t RemoveIptablesFilterRule(const AppExecFwk::ElementName &admin, const IPTABLES::RemoveFilter &filter); + int32_t ListIptablesFilterRules(const AppExecFwk::ElementName &admin, std::string &result); + private: static std::shared_ptr instance_; static std::mutex mutexLock_; }; -} // namespace EDM -} // namespace OHOS +} // namespace EDM +} // namespace OHOS -#endif // INTERFACES_INNER_API_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_PROXY_H +#endif // INTERFACES_INNER_API_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_PROXY_H diff --git a/interfaces/inner_api/network_manager/src/network_manager_proxy.cpp b/interfaces/inner_api/network_manager/src/network_manager_proxy.cpp index 3ef99538774a16c57943736242516a32da329493..0d628afe91cf7ce1699ebfe78c69f0f35d792a62 100644 --- a/interfaces/inner_api/network_manager/src/network_manager_proxy.cpp +++ b/interfaces/inner_api/network_manager/src/network_manager_proxy.cpp @@ -14,6 +14,7 @@ */ #include "network_manager_proxy.h" + #include "edm_log.h" #include "func_code.h" #include "policy_info.h" @@ -113,8 +114,8 @@ int32_t NetworkManagerProxy::SetNetworkInterfaceDisabled(const AppExecFwk::Eleme data.WriteInterfaceToken(DESCRIPTOR); data.WriteInt32(WITHOUT_USERID); data.WriteParcelable(&admin); - std::vector key { networkInterface }; - std::vector value { isDisabled ? "true" : "false" }; + std::vector key{networkInterface}; + std::vector value{isDisabled ? "true" : "false"}; data.WriteStringVector(key); data.WriteStringVector(value); return proxy->HandleDevicePolicy(funcCode, data); @@ -146,5 +147,51 @@ int32_t NetworkManagerProxy::IsNetworkInterfaceDisabled(const AppExecFwk::Elemen reply.ReadBool(status); return ERR_OK; } -} // namespace EDM -} // namespace OHOS + +int32_t NetworkManagerProxy::AddIptablesFilterRule(const AppExecFwk::ElementName &admin, + const IPTABLES::AddFilter &filter) +{ + EDMLOGD("NetworkManagerProxy::AddIptablesFilterRule"); + MessageParcel data; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::SET, IPTABLES_RULE); + data.WriteInterfaceToken(DESCRIPTOR); + data.WriteInt32(WITHOUT_USERID); + data.WriteParcelable(&admin); + IPTABLES::IptablesUtils::WriteAddFilterConfig(filter, data); + return EnterpriseDeviceMgrProxy::GetInstance()->HandleDevicePolicy(funcCode, data); +} + +int32_t NetworkManagerProxy::RemoveIptablesFilterRule(const AppExecFwk::ElementName &admin, + const IPTABLES::RemoveFilter &filter) +{ + EDMLOGD("NetworkManagerProxy::RemoveIptablesFilterRule"); + MessageParcel data; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::REMOVE, IPTABLES_RULE); + data.WriteInterfaceToken(DESCRIPTOR); + data.WriteInt32(WITHOUT_USERID); + data.WriteParcelable(&admin); + IPTABLES::IptablesUtils::WriteRemoveFilterConfig(filter, data); + return EnterpriseDeviceMgrProxy::GetInstance()->HandleDevicePolicy(funcCode, data); +} + +int32_t NetworkManagerProxy::ListIptablesFilterRules(const AppExecFwk::ElementName &admin, std::string &result) +{ + EDMLOGD("NetworkManagerProxy::ListIptablesFilterRules"); + MessageParcel data; + MessageParcel reply; + data.WriteInterfaceToken(DESCRIPTOR); + data.WriteInt32(WITHOUT_USERID); + data.WriteInt32(HAS_ADMIN); + data.WriteParcelable(&admin); + EnterpriseDeviceMgrProxy::GetInstance()->GetPolicy(IPTABLES_RULE, data, reply); + int32_t ret = ERR_INVALID_VALUE; + bool blRes = reply.ReadInt32(ret) && (ret == ERR_OK); + if (!blRes) { + EDMLOGW("EnterpriseDeviceMgrProxy:GetPolicy fail. %{public}d", ret); + return ret; + } + reply.ReadString(result); + return ERR_OK; +} +} // namespace EDM +} // namespace OHOS diff --git a/interfaces/kits/common/src/napi_edm_common.cpp b/interfaces/kits/common/src/napi_edm_common.cpp index fe5891ef2bc753a6729972981bbd05df9d241a13..39542923339605abb1f7a898398ccc8b77f87236 100644 --- a/interfaces/kits/common/src/napi_edm_common.cpp +++ b/interfaces/kits/common/src/napi_edm_common.cpp @@ -119,7 +119,7 @@ bool ParseString(napi_env env, std::string ¶m, napi_value args) EDMLOGE("can not get string value"); return false; } - EDMLOGD("ParseString param = %{public}s.", param.c_str()); + EDMLOGD("ParseString param = %{public}s", param.c_str()); return true; } diff --git a/interfaces/kits/network_manager/BUILD.gn b/interfaces/kits/network_manager/BUILD.gn index 0c37154a804409ee2b61152ae781bc25bef3f4c2..6033a4f54c6d301d38439e786cea9fd1455a64c3 100644 --- a/interfaces/kits/network_manager/BUILD.gn +++ b/interfaces/kits/network_manager/BUILD.gn @@ -27,7 +27,10 @@ ohos_shared_library("networkmanager") { configs = [ "../../../common/config:coverage_flags" ] - deps = [ "../../inner_api:edmservice_kits" ] + deps = [ + "../../../common/native:edm_commom", + "../../inner_api:edmservice_kits", + ] external_deps = [ "ability_base:want", diff --git a/interfaces/kits/network_manager/include/network_manager_addon.h b/interfaces/kits/network_manager/include/network_manager_addon.h index 58f0855ac00d34411a9384dd6a71a0ba773d3a66..cdbf09b7b91e43de8267ecae39324fe284c5cd66 100644 --- a/interfaces/kits/network_manager/include/network_manager_addon.h +++ b/interfaces/kits/network_manager/include/network_manager_addon.h @@ -16,11 +16,11 @@ #ifndef INTERFACES_KITS_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_ADDON_H #define INTERFACES_KITS_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_ADDON_H -#include "napi_edm_error.h" -#include "napi_edm_common.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" -#include "napi/native_api.h" +#include "napi_edm_common.h" +#include "napi_edm_error.h" #include "network_manager_proxy.h" #include "want.h" @@ -42,6 +42,11 @@ struct AsyncSetNetworkInterfaceCallbackInfo : AsyncCallbackInfo { bool isDisabled = false; }; +struct AsyncIptablesCallbackInfo : AsyncCallbackInfo { + OHOS::AppExecFwk::ElementName elementName; + IPTABLES::AddFilter addFilter; + IPTABLES::RemoveFilter removeFilter; +}; class NetworkManagerAddon { public: @@ -49,6 +54,7 @@ public: ~NetworkManagerAddon() = default; static napi_value Init(napi_env env, napi_value exports); + private: static napi_value GetAllNetworkInterfaces(napi_env env, napi_callback_info info); static napi_value GetIpAddress(napi_env env, napi_callback_info info); @@ -56,12 +62,24 @@ private: static napi_value GetIpOrMacAddress(napi_env env, napi_callback_info info, int policyCode); static napi_value SetNetworkInterfaceDisabled(napi_env env, napi_callback_info info); static napi_value IsNetworkInterfaceDisabled(napi_env env, napi_callback_info info); + static napi_value AddIptablesFilterRule(napi_env env, napi_callback_info info); + static napi_value RemoveIptablesFilterRule(napi_env env, napi_callback_info info); + static napi_value ListIptablesFilterRules(napi_env env, napi_callback_info info); static void NativeGetAllNetworkInterfaces(napi_env env, void *data); static void NativeGetIpOrMacAddress(napi_env env, void *data); static void NativeSetNetworkInterfaceDisabled(napi_env env, void *data); static void NativeIsNetworkInterfaceDisabled(napi_env env, void *data); + static void NativeAddIptalbsFilterRule(napi_env env, void *data); + static void NativeRemoveIptalbsFilterRule(napi_env env, void *data); + static void NativeListIptablesFilterRules(napi_env env, void *data); + static void CreateFirewallActionObject(napi_env env, napi_value value); + static void CreateFirewallProtocolObject(napi_env env, napi_value value); + static void CreateFirewallDirectionObject(napi_env env, napi_value value); + static void CreateFirewallAddMethodObject(napi_env env, napi_value value); + static bool JsObjToAddFirewallObject(napi_env env, napi_value object, IPTABLES::AddFilter &addFilter); + static bool JsObjToRemoveFirewallObject(napi_env env, napi_value object, IPTABLES::RemoveFilter &removeFilter); }; -} // namespace EDM -} // namespace OHOS +} // namespace EDM +} // namespace OHOS -#endif // INTERFACES_KITS_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_ADDON_H +#endif // INTERFACES_KITS_NETWORK_MANAGER_INCLUDE_NETWORK_MANAGER_ADDON_H diff --git a/interfaces/kits/network_manager/src/network_manager_addon.cpp b/interfaces/kits/network_manager/src/network_manager_addon.cpp index 583a3fba7afdae87b044cdd0ec328bed47254e69..ee1faf9f553af513bef87571ab3adae485ee1612 100644 --- a/interfaces/kits/network_manager/src/network_manager_addon.cpp +++ b/interfaces/kits/network_manager/src/network_manager_addon.cpp @@ -13,20 +13,92 @@ * limitations under the License. */ #include "network_manager_addon.h" + #include "edm_log.h" +#include "iptables_utils.h" #include "napi_edm_common.h" #include "policy_info.h" using namespace OHOS::EDM; +void NetworkManagerAddon::CreateFirewallActionObject(napi_env env, napi_value value) +{ + napi_value nAllow; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Action::ALLOW), &nAllow)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "ALLOW", nAllow)); + napi_value nDeny; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Action::DENY), &nDeny)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "DENY", nDeny)); +} + +void NetworkManagerAddon::CreateFirewallProtocolObject(napi_env env, napi_value value) +{ + napi_value nAll; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Protocol::ALL), &nAll)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "ALL", nAll)); + napi_value nTCP; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Protocol::TCP), &nTCP)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "TCP", nTCP)); + napi_value nUDP; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Protocol::UDP), &nUDP)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "UDP", nUDP)); + napi_value nICMP; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Protocol::ICMP), &nICMP)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "ICMP", nICMP)); +} + +void NetworkManagerAddon::CreateFirewallDirectionObject(napi_env env, napi_value value) +{ + napi_value nInput; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Direction::INPUT), &nInput)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "INPUT", nInput)); + napi_value nOutput; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::Direction::OUTPUT), &nOutput)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "OUTPUT", nOutput)); +} + +void NetworkManagerAddon::CreateFirewallAddMethodObject(napi_env env, napi_value value) +{ + napi_value nAppend; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::AddMethod::APPEND), &nAppend)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "APPEND", nAppend)); + napi_value nInsert; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(IPTABLES::AddMethod::INSERT), &nInsert)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "INSERT", nInsert)); +} + napi_value NetworkManagerAddon::Init(napi_env env, napi_value exports) { + napi_value nFirewallAction = nullptr; + NAPI_CALL(env, napi_create_object(env, &nFirewallAction)); + CreateFirewallActionObject(env, nFirewallAction); + + napi_value nFirewallProtocol = nullptr; + NAPI_CALL(env, napi_create_object(env, &nFirewallProtocol)); + CreateFirewallProtocolObject(env, nFirewallProtocol); + + napi_value nFirewallDirection = nullptr; + NAPI_CALL(env, napi_create_object(env, &nFirewallDirection)); + CreateFirewallDirectionObject(env, nFirewallDirection); + + napi_value nFirewallAddMethod = nullptr; + NAPI_CALL(env, napi_create_object(env, &nFirewallAddMethod)); + CreateFirewallAddMethodObject(env, nFirewallAddMethod); + napi_property_descriptor property[] = { DECLARE_NAPI_FUNCTION("getAllNetworkInterfaces", GetAllNetworkInterfaces), DECLARE_NAPI_FUNCTION("getIpAddress", GetIpAddress), DECLARE_NAPI_FUNCTION("getMac", GetMac), DECLARE_NAPI_FUNCTION("setNetworkInterfaceDisabled", SetNetworkInterfaceDisabled), DECLARE_NAPI_FUNCTION("isNetworkInterfaceDisabled", IsNetworkInterfaceDisabled), + + DECLARE_NAPI_PROPERTY("Action", nFirewallAction), + DECLARE_NAPI_PROPERTY("Protocol", nFirewallProtocol), + DECLARE_NAPI_PROPERTY("Direction", nFirewallDirection), + DECLARE_NAPI_PROPERTY("AddMethod", nFirewallAddMethod), + DECLARE_NAPI_FUNCTION("addIptablesFilterRule", AddIptablesFilterRule), + DECLARE_NAPI_FUNCTION("removeIptablesFilterRule", RemoveIptablesFilterRule), + DECLARE_NAPI_FUNCTION("listIptablesFilterRules", ListIptablesFilterRules), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(property) / sizeof(property[0]), property)); return exports; @@ -49,10 +121,11 @@ napi_value NetworkManagerAddon::GetAllNetworkInterfaces(napi_env env, napi_callb if (asyncCallbackInfo == nullptr) { return nullptr; } - std::unique_ptr callbackPtr {asyncCallbackInfo}; + std::unique_ptr callbackPtr{asyncCallbackInfo}; ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), "element name param error"); - EDMLOGD("GetAllNetworkInterfaces: asyncCallbackInfo->elementName.bundlename %{public}s, " + EDMLOGD( + "GetAllNetworkInterfaces: asyncCallbackInfo->elementName.bundlename %{public}s, " "asyncCallbackInfo->abilityname:%{public}s", asyncCallbackInfo->elementName.GetBundleName().c_str(), asyncCallbackInfo->elementName.GetAbilityName().c_str()); @@ -79,8 +152,8 @@ void NetworkManagerAddon::NativeGetAllNetworkInterfaces(napi_env env, void *data EDMLOGE("can not get GetNetworkManagerProxy"); return; } - asyncCallbackInfo->ret = networkManagerProxy->GetAllNetworkInterfaces(asyncCallbackInfo->elementName, - asyncCallbackInfo->arrayStringRet); + asyncCallbackInfo->ret = + networkManagerProxy->GetAllNetworkInterfaces(asyncCallbackInfo->elementName, asyncCallbackInfo->arrayStringRet); } napi_value NetworkManagerAddon::GetIpAddress(napi_env env, napi_callback_info info) @@ -103,8 +176,8 @@ napi_value NetworkManagerAddon::GetIpOrMacAddress(napi_env env, napi_callback_in void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_TWO, "parameter count error"); - bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object) && - MatchValueType(env, argv[ARR_INDEX_ONE], napi_string); + bool matchFlag = + MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object) && MatchValueType(env, argv[ARR_INDEX_ONE], napi_string); if (argc > ARGS_SIZE_TWO) { matchFlag = matchFlag && MatchValueType(env, argv[ARGS_SIZE_TWO], napi_function); } @@ -113,12 +186,13 @@ napi_value NetworkManagerAddon::GetIpOrMacAddress(napi_env env, napi_callback_in if (asyncCallbackInfo == nullptr) { return nullptr; } - std::unique_ptr callbackPtr {asyncCallbackInfo}; + std::unique_ptr callbackPtr{asyncCallbackInfo}; ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), "element name param error"); ASSERT_AND_THROW_PARAM_ERROR(env, ParseString(env, asyncCallbackInfo->networkInterface, argv[ARR_INDEX_ONE]), "parameter networkInterface error"); - EDMLOGD("GetIpOrMacAddress: asyncCallbackInfo->elementName.bundlename %{public}s, " + EDMLOGD( + "GetIpOrMacAddress: asyncCallbackInfo->elementName.bundlename %{public}s, " "asyncCallbackInfo->abilityname:%{public}s", asyncCallbackInfo->elementName.GetBundleName().c_str(), asyncCallbackInfo->elementName.GetAbilityName().c_str()); @@ -127,8 +201,8 @@ napi_value NetworkManagerAddon::GetIpOrMacAddress(napi_env env, napi_callback_in napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); } asyncCallbackInfo->policyCode = policyCode; - napi_value asyncWorkReturn = HandleAsyncWork(env, asyncCallbackInfo, "GetIpAddress", - NativeGetIpOrMacAddress, NativeStringCallbackComplete); + napi_value asyncWorkReturn = + HandleAsyncWork(env, asyncCallbackInfo, "GetIpAddress", NativeGetIpOrMacAddress, NativeStringCallbackComplete); callbackPtr.release(); return asyncWorkReturn; } @@ -159,8 +233,7 @@ napi_value NetworkManagerAddon::SetNetworkInterfaceDisabled(napi_env env, napi_c NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_THREE, "parameter count error"); bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object) && - MatchValueType(env, argv[ARR_INDEX_ONE], napi_string) && - MatchValueType(env, argv[ARR_INDEX_TWO], napi_boolean); + MatchValueType(env, argv[ARR_INDEX_ONE], napi_string) && MatchValueType(env, argv[ARR_INDEX_TWO], napi_boolean); if (argc > ARGS_SIZE_THREE) { matchFlag = matchFlag && MatchValueType(env, argv[ARGS_SIZE_THREE], napi_function); } @@ -169,14 +242,15 @@ napi_value NetworkManagerAddon::SetNetworkInterfaceDisabled(napi_env env, napi_c if (asyncCallbackInfo == nullptr) { return nullptr; } - std::unique_ptr callbackPtr {asyncCallbackInfo}; + std::unique_ptr callbackPtr{asyncCallbackInfo}; ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), "parameter element name error"); ASSERT_AND_THROW_PARAM_ERROR(env, ParseString(env, asyncCallbackInfo->networkInterface, argv[ARR_INDEX_ONE]), "parameter networkInterface error"); ASSERT_AND_THROW_PARAM_ERROR(env, ParseBool(env, asyncCallbackInfo->isDisabled, argv[ARR_INDEX_TWO]), "parameter isDisabled error"); - EDMLOGD("SetNetworkInterfaceDisabled: asyncCallbackInfo->elementName.bundlename %{public}s, " + EDMLOGD( + "SetNetworkInterfaceDisabled: asyncCallbackInfo->elementName.bundlename %{public}s, " "asyncCallbackInfo->abilityname:%{public}s", asyncCallbackInfo->elementName.GetBundleName().c_str(), asyncCallbackInfo->elementName.GetAbilityName().c_str()); @@ -215,8 +289,8 @@ napi_value NetworkManagerAddon::IsNetworkInterfaceDisabled(napi_env env, napi_ca void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_TWO, "parameter count error"); - bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object) && - MatchValueType(env, argv[ARR_INDEX_ONE], napi_string); + bool matchFlag = + MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object) && MatchValueType(env, argv[ARR_INDEX_ONE], napi_string); if (argc > ARGS_SIZE_TWO) { matchFlag = matchFlag && MatchValueType(env, argv[ARGS_SIZE_TWO], napi_function); } @@ -225,12 +299,13 @@ napi_value NetworkManagerAddon::IsNetworkInterfaceDisabled(napi_env env, napi_ca if (asyncCallbackInfo == nullptr) { return nullptr; } - std::unique_ptr callbackPtr {asyncCallbackInfo}; + std::unique_ptr callbackPtr{asyncCallbackInfo}; ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), "parameter element name error"); ASSERT_AND_THROW_PARAM_ERROR(env, ParseString(env, asyncCallbackInfo->networkInterface, argv[ARR_INDEX_ONE]), "parameter networkInterface error"); - EDMLOGD("IsNetworkInterfaceDisabled: asyncCallbackInfo->elementName.bundlename %{public}s, " + EDMLOGD( + "IsNetworkInterfaceDisabled: asyncCallbackInfo->elementName.bundlename %{public}s, " "asyncCallbackInfo->abilityname:%{public}s", asyncCallbackInfo->elementName.GetBundleName().c_str(), asyncCallbackInfo->elementName.GetAbilityName().c_str()); @@ -261,6 +336,210 @@ void NetworkManagerAddon::NativeIsNetworkInterfaceDisabled(napi_env env, void *d asyncCallbackInfo->networkInterface, asyncCallbackInfo->boolRet); } +napi_value NetworkManagerAddon::AddIptablesFilterRule(napi_env env, napi_callback_info info) +{ + EDMLOGI("NetworkManagerAddon::AddIptablesFilterRule called"); + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + napi_value thisArg = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_TWO, "parameter count error"); + bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object); + matchFlag = matchFlag && MatchValueType(env, argv[ARR_INDEX_ONE], napi_object); + if (argc > ARGS_SIZE_TWO) { + matchFlag = matchFlag && MatchValueType(env, argv[ARR_INDEX_TWO], napi_function); + } + ASSERT_AND_THROW_PARAM_ERROR(env, matchFlag, "parameter type error"); + auto asyncCallbackInfo = new (std::nothrow) AsyncIptablesCallbackInfo(); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr{asyncCallbackInfo}; + ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), + "element name param error"); + EDMLOGD( + "AddIptalbsFilterRule: asyncCallbackInfo->elementName.bundlename %{public}s, " + "asyncCallbackInfo->abilityname:%{public}s", + asyncCallbackInfo->elementName.GetBundleName().c_str(), + asyncCallbackInfo->elementName.GetAbilityName().c_str()); + ASSERT_AND_THROW_PARAM_ERROR(env, JsObjToAddFirewallObject(env, argv[ARR_INDEX_ONE], asyncCallbackInfo->addFilter), + "addFilter param error"); + if (argc > ARGS_SIZE_TWO) { + EDMLOGD("NAPI_AddIptalbsFilterRule argc == ARGS_SIZE_THREE"); + napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + } + napi_value asyncWorkReturn = HandleAsyncWork(env, asyncCallbackInfo, "AddIptablesFilterRule", + NativeAddIptalbsFilterRule, NativeVoidCallbackComplete); + callbackPtr.release(); + return asyncWorkReturn; +} + +bool NetworkManagerAddon::JsObjToAddFirewallObject(napi_env env, napi_value object, IPTABLES::AddFilter &filter) +{ + JsObjectToUint(env, object, "ruleNo", false, filter.ruleNo); + JsObjectToString(env, object, "srcAddr", false, filter.srcAddr); + JsObjectToString(env, object, "destAddr", false, filter.destAddr); + JsObjectToString(env, object, "srcPort", false, filter.srcPort); + JsObjectToString(env, object, "destPort", false, filter.destPort); + JsObjectToString(env, object, "uid", false, filter.uid); + int32_t method = -1; + if (!JsObjectToInt(env, object, "method", true, method) || + !IPTABLES::IptablesUtils::ProcessFirewallMethod(method, filter.method)) { + EDMLOGE("NAPI_AddIptalbsFilterRule JsObjToAddFirewallObject method trans failed"); + return false; + } + int32_t direction = -1; + if (!JsObjectToInt(env, object, "direction", true, direction) || + !IPTABLES::IptablesUtils::ProcessFirewallDirection(direction, filter.direction)) { + EDMLOGE("NAPI_AddIptalbsFilterRule JsObjToAddFirewallObject direction trans failed"); + return false; + } + int32_t action = -1; + if (!JsObjectToInt(env, object, "action", true, action) || + !IPTABLES::IptablesUtils::ProcessFirewallAction(action, filter.action)) { + EDMLOGE("NAPI_AddIptalbsFilterRule JsObjToAddFirewallObject action trans failed"); + return false; + } + int32_t protocol = -1; + JsObjectToInt(env, object, "protocol", false, protocol); + IPTABLES::IptablesUtils::ProcessFirewallProtocol(protocol, filter.protocol); + return true; +} + +void NetworkManagerAddon::NativeAddIptalbsFilterRule(napi_env env, void *data) +{ + EDMLOGI("NAPI_NativeAddIptalbsFilterRule called"); + if (data == nullptr) { + EDMLOGE("data is nullptr"); + return; + } + AsyncIptablesCallbackInfo *asyncCallbackInfo = static_cast(data); + asyncCallbackInfo->ret = NetworkManagerProxy::GetNetworkManagerProxy()->AddIptablesFilterRule( + asyncCallbackInfo->elementName, asyncCallbackInfo->addFilter); +} + +napi_value NetworkManagerAddon::RemoveIptablesFilterRule(napi_env env, napi_callback_info info) +{ + EDMLOGI("NetworkManagerAddon::RemoveIptablesFilterRule called"); + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + napi_value thisArg = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_TWO, "parameter count error"); + bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object); + matchFlag = matchFlag && MatchValueType(env, argv[ARR_INDEX_ONE], napi_object); + if (argc > ARGS_SIZE_TWO) { + matchFlag = matchFlag && MatchValueType(env, argv[ARR_INDEX_TWO], napi_function); + } + ASSERT_AND_THROW_PARAM_ERROR(env, matchFlag, "parameter type error"); + auto asyncCallbackInfo = new (std::nothrow) AsyncIptablesCallbackInfo(); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr{asyncCallbackInfo}; + ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), + "element name param error"); + EDMLOGD( + "RemoveIptablesFilterRule: asyncCallbackInfo->elementName.bundlename %{public}s, " + "asyncCallbackInfo->abilityname:%{public}s", + asyncCallbackInfo->elementName.GetBundleName().c_str(), + asyncCallbackInfo->elementName.GetAbilityName().c_str()); + ASSERT_AND_THROW_PARAM_ERROR(env, + JsObjToRemoveFirewallObject(env, argv[ARR_INDEX_ONE], asyncCallbackInfo->removeFilter), "firewall param error"); + if (argc > ARGS_SIZE_TWO) { + EDMLOGD("NAPI_RemoveIptablesFilterRule argc == ARGS_SIZE_THREE"); + napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + } + napi_value asyncWorkReturn = HandleAsyncWork(env, asyncCallbackInfo, "RemoveIptablesFilterRule", + NativeRemoveIptalbsFilterRule, NativeVoidCallbackComplete); + callbackPtr.release(); + return asyncWorkReturn; +} + +bool NetworkManagerAddon::JsObjToRemoveFirewallObject(napi_env env, napi_value object, IPTABLES::RemoveFilter &firewall) +{ + JsObjectToString(env, object, "srcAddr", false, firewall.srcAddr); + JsObjectToString(env, object, "destAddr", false, firewall.destAddr); + JsObjectToString(env, object, "srcPort", false, firewall.srcPort); + JsObjectToString(env, object, "destPort", false, firewall.destPort); + JsObjectToString(env, object, "uid", false, firewall.uid); + int32_t direction = -1; + if (!JsObjectToInt(env, object, "direction", true, direction) || + !IPTABLES::IptablesUtils::ProcessFirewallDirection(direction, firewall.direction)) { + EDMLOGE("NAPI_removeIptalbsFilterRule JsObjToRemoveFirewallObject direction trans failed"); + return false; + } + int32_t action = -1; + JsObjectToInt(env, object, "action", false, action); + IPTABLES::IptablesUtils::ProcessFirewallAction(action, firewall.action); + int32_t protocol = -1; + JsObjectToInt(env, object, "protocol", false, protocol); + IPTABLES::IptablesUtils::ProcessFirewallProtocol(protocol, firewall.protocol); + return true; +} + +void NetworkManagerAddon::NativeRemoveIptalbsFilterRule(napi_env env, void *data) +{ + EDMLOGI("NAPI_NativeDeleteIptalbsFilterRule called"); + if (data == nullptr) { + EDMLOGE("data is nullptr"); + return; + } + AsyncIptablesCallbackInfo *asyncCallbackInfo = static_cast(data); + auto networkManagerProxy = NetworkManagerProxy::GetNetworkManagerProxy(); + asyncCallbackInfo->ret = + networkManagerProxy->RemoveIptablesFilterRule(asyncCallbackInfo->elementName, asyncCallbackInfo->removeFilter); +} + +napi_value NetworkManagerAddon::ListIptablesFilterRules(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + napi_value thisArg = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + ASSERT_AND_THROW_PARAM_ERROR(env, argc >= ARGS_SIZE_ONE, "parameter count error"); + bool matchFlag = MatchValueType(env, argv[ARR_INDEX_ZERO], napi_object); + if (argc > ARGS_SIZE_ONE) { + matchFlag = matchFlag && MatchValueType(env, argv[ARGS_SIZE_ONE], napi_function); + } + ASSERT_AND_THROW_PARAM_ERROR(env, matchFlag, "parameter type error"); + auto asyncCallbackInfo = new (std::nothrow) AsyncIptablesCallbackInfo(); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr{asyncCallbackInfo}; + ASSERT_AND_THROW_PARAM_ERROR(env, ParseElementName(env, asyncCallbackInfo->elementName, argv[ARR_INDEX_ZERO]), + "element name param error"); + EDMLOGD( + "ListIptablesFilterRules: asyncCallbackInfo->elementName.bundlename %{public}s, " + "asyncCallbackInfo->abilityname:%{public}s", + asyncCallbackInfo->elementName.GetBundleName().c_str(), + asyncCallbackInfo->elementName.GetAbilityName().c_str()); + if (argc > ARGS_SIZE_ONE) { + EDMLOGD("NAPI_ListIptablesFilterRule argc == ARGS_SIZE_TWO"); + napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + } + napi_value asyncWorkReturn = HandleAsyncWork(env, asyncCallbackInfo, "ListIptablesFilterRules", + NativeListIptablesFilterRules, NativeStringCallbackComplete); + callbackPtr.release(); + return asyncWorkReturn; +} + +void NetworkManagerAddon::NativeListIptablesFilterRules(napi_env env, void *data) +{ + EDMLOGI("NAPI_NativeListIptablesFilterRule called"); + if (data == nullptr) { + EDMLOGE("data is nullptr"); + return; + } + AsyncIptablesCallbackInfo *asyncCallbackInfo = static_cast(data); + asyncCallbackInfo->ret = NetworkManagerProxy::GetNetworkManagerProxy()->ListIptablesFilterRules( + asyncCallbackInfo->elementName, asyncCallbackInfo->stringRet); +} + static napi_module g_networkManagerModule = { .nm_version = 1, .nm_flags = 0, @@ -268,7 +547,7 @@ static napi_module g_networkManagerModule = { .nm_register_func = NetworkManagerAddon::Init, .nm_modname = "enterprise.networkManager", .nm_priv = ((void *)0), - .reserved = { 0 }, + .reserved = {0}, }; extern "C" __attribute__((constructor)) void NetworkManagerRegister() diff --git a/services/edm_plugin/BUILD.gn b/services/edm_plugin/BUILD.gn index b3538cede391a8429e534e312b793204d5eb0f1a..6a60862aacaf46ccb79597e08be536f02f66f616 100644 --- a/services/edm_plugin/BUILD.gn +++ b/services/edm_plugin/BUILD.gn @@ -89,10 +89,14 @@ edm_plugin_shared_library("network_manager_plugin") { "./src/get_all_network_interfaces_plugin.cpp", "./src/get_ip_address_plugin.cpp", "./src/get_mac_plugin.cpp", + "./src/iptables_rule_plugin.cpp", ] + deps = [ "../../common/native:edm_commom" ] + external_deps = [ "c_utils:utils", + "netmanager_base:netsys_controller", "netmanager_ext:ethernet_manager_if", ] } diff --git a/services/edm_plugin/include/iptables_rule_plugin.h b/services/edm_plugin/include/iptables_rule_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..42c64d7b81121f1c6005fdd3e4ec4d4dfcef51a9 --- /dev/null +++ b/services/edm_plugin/include/iptables_rule_plugin.h @@ -0,0 +1,66 @@ +/* + * 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 SERVICES_EDM_PLUGIN_INCLUDE_IPTABLES_RULE_PLUGIN_H +#define SERVICES_EDM_PLUGIN_INCLUDE_IPTABLES_RULE_PLUGIN_H + +#include + +#include "iplugin.h" +#include "iptables_utils.h" + +namespace OHOS { +namespace EDM { +class IptablesRulePlugin : public IPlugin { +public: + IptablesRulePlugin(); + ErrCode OnHandlePolicy(std::uint32_t funcCode, MessageParcel &data, MessageParcel &reply, std::string &policyData, + bool &isChanged, int32_t userId) override; + + void OnHandlePolicyDone(std::uint32_t funcCode, const std::string &adminName, bool isGlobalChanged, + int32_t userId) override{}; + + ErrCode OnAdminRemove(const std::string &adminName, const std::string &policyData, int32_t userId) override + { + return ERR_OK; + }; + + void OnAdminRemoveDone(const std::string &adminName, const std::string ¤tJsonData, int32_t userId) override{}; + + ErrCode OnGetPolicy(std::string &policyData, MessageParcel &data, MessageParcel &reply, int32_t userId) override; + +private: + void InitFirewallChain(); + bool ConvertAddFilterToIptablesCommand(const IPTABLES::AddFilter &addFilter, std::string &Command); + ErrCode ExecRemoveFilterIptablesCommand(const IPTABLES::RemoveFilter &removeFilter); + ErrCode ExecRemoveFilterBySimpleCommand(const IPTABLES::Direction &direction); + ErrCode ExecRemoveFilterByDetailedCommand(const IPTABLES::RemoveFilter &removeFilter); + bool ConvertChainCommand(const IPTABLES::Action &action, const IPTABLES::Direction &direction, + std::string &Command); + void ConvertIpAddressCommand(const std::string &ipAddress, const bool isSourceIp, std::string &Command); + void ConvertPortCommand(const std::string &port, const bool isSourcePort, std::string &Command); + void ConvertProtocolCommand(const IPTABLES::Protocol &protocol, std::string &Command); + bool ConvertActionCommand(const IPTABLES::Action &action, std::string &Command); + void ConvertRuleNoCommand(const IPTABLES::AddMethod &method, uint32_t ruleNo, std::string &Command); + void ConvertUidCommand(const std::string &uid, std::string &Command); + ErrCode AddIptablesFilterRule(MessageParcel &data); + ErrCode RemoveIptablesFilterRule(MessageParcel &data); + + static bool isChainInit_; +}; +} // namespace EDM +} // namespace OHOS + +#endif // SERVICES_EDM_PLUGIN_INCLUDE_IPTABLES_RULE_PLUGIN_H diff --git a/services/edm_plugin/src/iptables_rule_plugin.cpp b/services/edm_plugin/src/iptables_rule_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b96fbc9d965235003b7eaaaf1fc2649babc69ce0 --- /dev/null +++ b/services/edm_plugin/src/iptables_rule_plugin.cpp @@ -0,0 +1,304 @@ +/* + * 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 "iptables_rule_plugin.h" + +#include "edm_log.h" +#include "func_code_utils.h" +#include "iplugin_manager.h" +#include "netsys_controller.h" +#include "policy_info.h" + +namespace OHOS { +namespace EDM { +const bool REGISTER_RESULT = IPluginManager::GetInstance()->AddPlugin(std::make_shared()); +const std::string EDM_CHAIN_ALLOW_INPUT = "edm_allow_input"; +const std::string EDM_CHAIN_ALLOW_OUTPUT = "edm_allow_output"; +const std::string EDM_CHAIN_DENY_INPUT = "edm_deny_input"; +const std::string EDM_CHAIN_DENY_OUTPUT = "edm_deny_output"; + +bool IptablesRulePlugin::isChainInit_ = false; + +IptablesRulePlugin::IptablesRulePlugin() +{ + policyCode_ = IPTABLES_RULE; + POLICY_CODE_TO_NAME(IPTABLES_RULE, policyName_); + permission_ = "ohos.permission.ENTERPRISE_MANAGE_NETWORK"; + permissionType_ = IPlugin::PermissionType::SUPER_DEVICE_ADMIN; + needSave_ = false; +} + +ErrCode IptablesRulePlugin::OnHandlePolicy(std::uint32_t funcCode, MessageParcel &data, MessageParcel &reply, + std::string &policyData, bool &isChanged, int32_t userId) +{ + uint32_t typeCode = FUNC_TO_OPERATE(funcCode); + FuncOperateType type = FuncCodeUtils::ConvertOperateType(typeCode); + if (type == FuncOperateType::SET) { + return AddIptablesFilterRule(data); + } else if (type == FuncOperateType::REMOVE) { + return RemoveIptablesFilterRule(data); + } else { + return EdmReturnErrCode::SYSTEM_ABNORMALLY; + } +} + +ErrCode IptablesRulePlugin::OnGetPolicy(std::string &policyData, MessageParcel &data, MessageParcel &reply, + int32_t userId) +{ + std::string result; + std::string command("-t filter -n -v -L --line-number"); + int32_t ret = NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(command, result); + EDMLOGI("IptablesRulePlugin::OnGetPolicy end retCode = %{public}d", ret); + if (ret == ERR_OK) { + reply.WriteInt32(ERR_OK); + reply.WriteString(result); + return ERR_OK; + } + reply.WriteInt32(EdmReturnErrCode::SYSTEM_ABNORMALLY); + return EdmReturnErrCode::SYSTEM_ABNORMALLY; +} + +ErrCode IptablesRulePlugin::AddIptablesFilterRule(MessageParcel &data) +{ + IPTABLES::AddFilter addFilter; + IPTABLES::IptablesUtils::ReadAddFilterConfig(addFilter, data); + std::string command; + if (!ConvertAddFilterToIptablesCommand(addFilter, command)) { + EDMLOGE("ConvertAddFilterToIptablesCommand failed"); + return EdmReturnErrCode::PARAM_ERROR; + } + InitFirewallChain(); + std::string result; + int32_t ret = NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(command, result); + EDMLOGI("AddIptablesFilterRule errcode = %{public}d, response = %{public}s", ret, result.c_str()); + return ret; +} + +ErrCode IptablesRulePlugin::RemoveIptablesFilterRule(MessageParcel &data) +{ + IPTABLES::RemoveFilter removeFilter; + IPTABLES::IptablesUtils::ReadRemoveFilterConfig(removeFilter, data); + return ExecRemoveFilterIptablesCommand(removeFilter); +} + +void IptablesRulePlugin::InitFirewallChain() +{ + if (isChainInit_) { + EDMLOGD("not need InitFirewallChain"); + return; + } + std::string allowInputChain = "-t filter -N " + EDM_CHAIN_ALLOW_INPUT; + std::string allowOutputChain = "-t filter -N " + EDM_CHAIN_ALLOW_OUTPUT; + std::string denyInputChain = "-t filter -N " + EDM_CHAIN_DENY_INPUT; + std::string denyOutputChain = "-t filter -N " + EDM_CHAIN_DENY_OUTPUT; + + std::string result; + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(allowInputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(allowOutputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(denyInputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(denyOutputChain, result); + + std::string refDenyOutputChain = "-t filter -I OUTPUT -j " + EDM_CHAIN_DENY_OUTPUT; + std::string refDenyInputChain = "-t filter -I INPUT -j " + EDM_CHAIN_DENY_INPUT; + std::string refAllowOutputChain = "-t filter -I OUTPUT -j " + EDM_CHAIN_ALLOW_OUTPUT; + std::string refAllowInputChain = "-t filter -I INPUT -j " + EDM_CHAIN_ALLOW_INPUT; + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(refDenyOutputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(refDenyInputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(refAllowOutputChain, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(refAllowInputChain, result); + isChainInit_ = true; + EDMLOGD("InitFirewallChain success"); +} + +bool IptablesRulePlugin::ConvertAddFilterToIptablesCommand(const IPTABLES::AddFilter &addFilter, std::string &command) +{ + command = "-t filter"; + if (addFilter.method == IPTABLES::AddMethod::APPEND) { + command.append(" -A"); + } else if (addFilter.method == IPTABLES::AddMethod::INSERT) { + command.append(" -I"); + } else { + EDMLOGE("ConvertFirewallToIptablesCommand AddMethod must specify"); + return false; + } + if (!ConvertChainCommand(addFilter.action, addFilter.direction, command)) { + EDMLOGE("ConvertFirewallToIptablesCommand action and direction must specify"); + return false; + } + ConvertRuleNoCommand(addFilter.method, addFilter.ruleNo, command); + ConvertProtocolCommand(addFilter.protocol, command); + ConvertIpAddressCommand(addFilter.srcAddr, true, command); + ConvertIpAddressCommand(addFilter.destAddr, false, command); + ConvertPortCommand(addFilter.srcPort, true, command); + ConvertPortCommand(addFilter.destPort, false, command); + ConvertUidCommand(addFilter.uid, command); + return ConvertActionCommand(addFilter.action, command); +} + +ErrCode IptablesRulePlugin::ExecRemoveFilterIptablesCommand(const IPTABLES::RemoveFilter &removeFilter) +{ + if (removeFilter.direction == IPTABLES::Direction::INVALID) { + return EdmReturnErrCode::PARAM_ERROR; + } + bool enumValue = + removeFilter.action == IPTABLES::Action::INVALID && removeFilter.protocol == IPTABLES::Protocol::INVALID; + bool otherValue = removeFilter.srcAddr.empty() && removeFilter.destAddr.empty() && removeFilter.srcPort.empty() && + removeFilter.destPort.empty() && removeFilter.uid.empty(); + if (enumValue && otherValue) { + return ExecRemoveFilterBySimpleCommand(removeFilter.direction); + } + return ExecRemoveFilterByDetailedCommand(removeFilter); +} + +ErrCode IptablesRulePlugin::ExecRemoveFilterBySimpleCommand(const IPTABLES::Direction &direction) +{ + std::string commandAllow("-t filter -F"); + std::string commandDeny("-t filter -F"); + switch (direction) { + case IPTABLES::Direction::INPUT: + commandAllow.append(" " + EDM_CHAIN_ALLOW_INPUT); + commandDeny.append(" " + EDM_CHAIN_DENY_INPUT); + break; + case IPTABLES::Direction::OUTPUT: + commandAllow.append(" " + EDM_CHAIN_ALLOW_OUTPUT); + commandDeny.append(" " + EDM_CHAIN_DENY_OUTPUT); + break; + default: + break; + } + std::string result; + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(commandAllow, result); + NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(commandDeny, result); + return ERR_OK; +} + +ErrCode IptablesRulePlugin::ExecRemoveFilterByDetailedCommand(const IPTABLES::RemoveFilter &removeFilter) +{ + std::string command = "-t filter -D"; + ConvertChainCommand(removeFilter.action, removeFilter.direction, command); + ConvertProtocolCommand(removeFilter.protocol, command); + ConvertIpAddressCommand(removeFilter.srcAddr, true, command); + ConvertIpAddressCommand(removeFilter.destAddr, false, command); + ConvertPortCommand(removeFilter.srcPort, true, command); + ConvertPortCommand(removeFilter.destPort, false, command); + ConvertUidCommand(removeFilter.uid, command); + ConvertActionCommand(removeFilter.action, command); + std::string result; + return NetManagerStandard::NetsysController::GetInstance().SetIptablesCommandForRes(command, result); +} + +bool IptablesRulePlugin::ConvertChainCommand(const IPTABLES::Action &action, const IPTABLES::Direction &direction, + std::string &command) +{ + if (action == IPTABLES::Action::ALLOW && direction == IPTABLES::Direction::INPUT) { + command.append(" " + EDM_CHAIN_ALLOW_INPUT); + } else if (action == IPTABLES::Action::ALLOW && direction == IPTABLES::Direction::OUTPUT) { + command.append(" " + EDM_CHAIN_ALLOW_OUTPUT); + } else if (action == IPTABLES::Action::DENY && direction == IPTABLES::Direction::INPUT) { + command.append(" " + EDM_CHAIN_DENY_INPUT); + } else if (action == IPTABLES::Action::DENY && direction == IPTABLES::Direction::OUTPUT) { + command.append(" " + EDM_CHAIN_DENY_OUTPUT); + } else { + return false; + } + return true; +} + +void IptablesRulePlugin::ConvertProtocolCommand(const IPTABLES::Protocol &protocol, std::string &command) +{ + switch (protocol) { + case IPTABLES::Protocol::TCP: + command.append(" -p tcp"); + break; + case IPTABLES::Protocol::UDP: + command.append(" -p udp"); + break; + case IPTABLES::Protocol::ICMP: + command.append(" -p icmp"); + break; + case IPTABLES::Protocol::ALL: + command.append(" -p all"); + break; + default: + break; + } +} + +bool IptablesRulePlugin::ConvertActionCommand(const IPTABLES::Action &action, std::string &command) +{ + switch (action) { + case IPTABLES::Action::ALLOW: + command.append(" -j ACCEPT"); + break; + case IPTABLES::Action::DENY: + command.append(" -j REJECT"); + break; + default: + return false; + } + return true; +} + +void IptablesRulePlugin::ConvertIpAddressCommand(const std::string &ipAddress, const bool isSourceIp, + std::string &command) +{ + if (ipAddress.empty()) { + return; + } + std::string key = "-"; + std::string::size_type idx = ipAddress.find(key); + if (idx == std::string::npos) { + if (isSourceIp) { + command.append(" -s " + ipAddress); + } else { + command.append(" -d " + ipAddress); + } + } else { + if (isSourceIp) { + command.append(" -m iprange --src-range " + ipAddress); + } else { + command.append(" -m iprange --dst-range " + ipAddress); + } + } +} + +void IptablesRulePlugin::ConvertPortCommand(const std::string &port, const bool isSourcePort, std::string &command) +{ + if (port.empty()) { + return; + } + if (isSourcePort) { + command.append(" --sport " + port); + } else { + command.append(" --dport " + port); + } +} + +void IptablesRulePlugin::ConvertUidCommand(const std::string &uid, std::string &command) +{ + if (uid.empty()) { + return; + } + command.append(" -m owner --uid-owner " + uid); +} + +void IptablesRulePlugin::ConvertRuleNoCommand(const IPTABLES::AddMethod &method, uint32_t ruleNo, std::string &command) +{ + if (method == IPTABLES::AddMethod::INSERT && ruleNo != 0) { + command.append(" " + std::to_string(ruleNo)); + } +} +} // namespace EDM +} // namespace OHOS diff --git a/test/unittest/edm_plugin/BUILD.gn b/test/unittest/edm_plugin/BUILD.gn index b891b4698544d5dcf6a08d3dd8b61f03e942fc3a..0f4602687c7513bece7cc90786bbae6c0a1a557f 100644 --- a/test/unittest/edm_plugin/BUILD.gn +++ b/test/unittest/edm_plugin/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("EdmGetDeviceNamePluginTest") { "./src/edm_data_ability_utils_mock.cpp", "./src/get_device_name_plugin_test.cpp", "./src/get_screen_off_time_plugin_test.cpp", + "./src/iptables_rule_plugin_test.cpp", "./src/is_wifi_active_plugin_test.cpp", "./src/network_manager_plugin_test.cpp", "./src/reset_factory_plugin_test.cpp", @@ -115,6 +116,7 @@ ohos_static_library("edm_all_plugin_static") { "../../../services/edm_plugin/src/get_ip_address_plugin.cpp", "../../../services/edm_plugin/src/get_mac_plugin.cpp", "../../../services/edm_plugin/src/get_screen_off_time_plugin.cpp", + "../../../services/edm_plugin/src/iptables_rule_plugin.cpp", "../../../services/edm_plugin/src/is_wifi_active_plugin.cpp", "../../../services/edm_plugin/src/reset_factory_plugin.cpp", "../../../services/edm_plugin/src/set_wifi_profile_plugin.cpp", @@ -146,6 +148,7 @@ ohos_static_library("edm_all_plugin_static") { "bundle_framework:appexecfwk_core", "c_utils:utils", "init:libbegetutil", + "netmanager_base:netsys_controller", "netmanager_ext:ethernet_manager_if", "os_account:os_account_innerkits", "wifi:wifi_sdk", diff --git a/test/unittest/edm_plugin/src/iptables_rule_plugin_test.cpp b/test/unittest/edm_plugin/src/iptables_rule_plugin_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5539b7986f24969370ddef85ed894be25aef7ad --- /dev/null +++ b/test/unittest/edm_plugin/src/iptables_rule_plugin_test.cpp @@ -0,0 +1,151 @@ +/* + * 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 "iptables_rule_plugin.h" + +#include + +#include "policy_info.h" +#include "utils.h" + +using namespace testing::ext; +using namespace testing; + +namespace OHOS { +namespace EDM { +namespace TEST { +class IptablesRulePluginTest : public testing::Test { +protected: + static void SetUpTestSuite(void); + + static void TearDownTestSuite(void); +}; + +void IptablesRulePluginTest::SetUpTestSuite(void) +{ + Utils::SetEdmInitialEnv(); +} + +void IptablesRulePluginTest::TearDownTestSuite(void) +{ + Utils::ResetTokenTypeAndUid(); + ASSERT_TRUE(Utils::IsOriginalUTEnv()); + std::cout << "now ut process is orignal ut env : " << Utils::IsOriginalUTEnv() << std::endl; +} + +/** + * @tc.name: TestIptablesRulePlugin001 + * @tc.desc: Test IptablesRulePlugin::OnSetPolicy function. + * @tc.type: FUNC + */ +HWTEST_F(IptablesRulePluginTest, TestIptablesRulePlugin001, TestSize.Level1) +{ + std::shared_ptr plugin = std::make_shared(); + MessageParcel data; + MessageParcel reply; + std::string policyData{"TestString"}; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::GET, IPTABLES_RULE); + bool isChanged = false; + ErrCode ret = plugin->OnHandlePolicy(funcCode, data, reply, policyData, isChanged, DEFAULT_USER_ID); + ASSERT_TRUE(ret == EdmReturnErrCode::SYSTEM_ABNORMALLY); +} + +/** + * @tc.name: TestIptablesRulePlugin002 + * @tc.desc: Test IptablesRulePlugin::OnHandlePolicy set function. + * @tc.type: FUNC + */ +HWTEST_F(IptablesRulePluginTest, TestIptablesRulePlugin002, TestSize.Level1) +{ + std::shared_ptr plugin = std::make_shared(); + IPTABLES::AddFilter addFilter; + MessageParcel data; + MessageParcel reply; + IPTABLES::IptablesUtils::WriteAddFilterConfig(addFilter, data); + std::string policyData{"TestString"}; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::SET, IPTABLES_RULE); + bool isChanged = false; + ErrCode ret = plugin->OnHandlePolicy(funcCode, data, reply, policyData, isChanged, DEFAULT_USER_ID); + ASSERT_TRUE(ret == EdmReturnErrCode::PARAM_ERROR); +} + +/** + * @tc.name: TestIptablesRulePlugin003 + * @tc.desc: Test IptablesRulePlugin::OnHandlePolicy remove function. + * @tc.type: FUNC + */ +HWTEST_F(IptablesRulePluginTest, TestIptablesRulePlugin003, TestSize.Level1) +{ + std::shared_ptr plugin = std::make_shared(); + IPTABLES::RemoveFilter filter; + MessageParcel data; + MessageParcel reply; + IPTABLES::IptablesUtils::WriteRemoveFilterConfig(filter, data); + std::string policyData{"TestString"}; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::REMOVE, IPTABLES_RULE); + bool isChanged = false; + ErrCode ret = plugin->OnHandlePolicy(funcCode, data, reply, policyData, isChanged, DEFAULT_USER_ID); + ASSERT_TRUE(ret == EdmReturnErrCode::PARAM_ERROR); +} + +/** + * @tc.name: TestIptablesRulePlugin004 + * @tc.desc: Test IptablesRulePlugin::OnHandlePolicy set success. + * @tc.type: FUNC + */ +HWTEST_F(IptablesRulePluginTest, TestIptablesRulePlugin004, TestSize.Level1) +{ + std::shared_ptr plugin = std::make_shared(); + IPTABLES::AddFilter addFilter; + addFilter.action = IPTABLES::Action::ALLOW; + addFilter.direction = IPTABLES::Direction::INPUT; + addFilter.method = IPTABLES::AddMethod::APPEND; + MessageParcel data; + MessageParcel reply; + IPTABLES::IptablesUtils::WriteAddFilterConfig(addFilter, data); + std::string policyData{"TestString"}; + std::uint32_t funcCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::SET, IPTABLES_RULE); + bool isChanged = false; + ErrCode ret = plugin->OnHandlePolicy(funcCode, data, reply, policyData, isChanged, DEFAULT_USER_ID); + ASSERT_TRUE(ret == ERR_OK); + + IPTABLES::RemoveFilter removeFilter; + removeFilter.direction = IPTABLES::Direction::INPUT; + MessageParcel removeData; + MessageParcel removeReply; + IPTABLES::IptablesUtils::WriteRemoveFilterConfig(removeFilter, removeData); + std::string policyRemoveData{"TestString"}; + std::uint32_t removeFuncCode = POLICY_FUNC_CODE((std::uint32_t)FuncOperateType::REMOVE, IPTABLES_RULE); + ret = plugin->OnHandlePolicy(removeFuncCode, removeData, removeReply, policyRemoveData, isChanged, DEFAULT_USER_ID); + ASSERT_TRUE(ret == ERR_OK); +} + +/** + * @tc.name: TestIptablesRulePlugingGetPolicy + * @tc.desc: Test OnGetPolicy function. + * @tc.type: FUNC + */ +HWTEST_F(IptablesRulePluginTest, TestIptablesRulePlugingGetPolicy, TestSize.Level1) +{ + std::shared_ptr plugin = std::make_shared(); + std::string policyData{"TestString"}; + MessageParcel data; + MessageParcel reply; + ErrCode ret = plugin->OnGetPolicy(policyData, data, reply, DEFAULT_USER_ID); + ASSERT_TRUE(ret == ERR_OK); +} +} // namespace TEST +} // namespace EDM +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/network_manager_proxy/network_manager_proxy_test/network_manager_proxy_test.cpp b/test/unittest/network_manager_proxy/network_manager_proxy_test/network_manager_proxy_test.cpp index aee301d86176005e8a321fc760b5fc87d96f4dc4..54f185c7ec0f44aa4f57eb4bd3ce279a37f7e069 100644 --- a/test/unittest/network_manager_proxy/network_manager_proxy_test/network_manager_proxy_test.cpp +++ b/test/unittest/network_manager_proxy/network_manager_proxy_test/network_manager_proxy_test.cpp @@ -13,14 +13,16 @@ * limitations under the License. */ +#include "network_manager_proxy.h" + #include -#include #include + +#include #include -#include "enterprise_device_mgr_stub_mock.h" #include "edm_sys_manager_mock.h" -#include "network_manager_proxy.h" +#include "enterprise_device_mgr_stub_mock.h" #include "policy_info.h" #include "utils.h" @@ -196,6 +198,102 @@ HWTEST_F(NetworkManagerProxyTest, TestSetNetworkInterfaceDisabledFail, TestSize. int32_t ret = networkManagerProxy->SetNetworkInterfaceDisabled(admin, "eth0", true); ASSERT_TRUE(ret == EdmReturnErrCode::ADMIN_INACTIVE); } -} // namespace TEST -} // namespace EDM -} // namespace OHOS + +/** + * @tc.name: TestAddIptablesFilterRuleSuc + * @tc.desc: Test AddIptablesFilterRule func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestAddIptablesFilterRuleSuc, TestSize.Level1) +{ + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + EXPECT_CALL(*object_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(object_.GetRefPtr(), &EnterpriseDeviceMgrStubMock::InvokeSendRequestSetPolicy)); + IPTABLES::AddFilter addFilter; + int32_t ret = networkManagerProxy->AddIptablesFilterRule(admin, addFilter); + ASSERT_TRUE(ret == ERR_OK); +} + +/** + * @tc.name: TestAddIptablesFilterRuleFail + * @tc.desc: Test AddIptablesFilterRule func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestAddIptablesFilterRuleFail, TestSize.Level1) +{ + Utils::SetEdmServiceDisable(); + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + IPTABLES::AddFilter addFilter; + int32_t ret = networkManagerProxy->AddIptablesFilterRule(admin, addFilter); + ASSERT_TRUE(ret == EdmReturnErrCode::ADMIN_INACTIVE); +} + +/** + * @tc.name: TestRemoveIptablesFilterRuleSuc + * @tc.desc: Test RemoveIptablesFilterRule func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestRemoveIptablesFilterRuleSuc, TestSize.Level1) +{ + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + EXPECT_CALL(*object_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(object_.GetRefPtr(), &EnterpriseDeviceMgrStubMock::InvokeSendRequestSetPolicy)); + IPTABLES::RemoveFilter removeFilter; + int32_t ret = networkManagerProxy->RemoveIptablesFilterRule(admin, removeFilter); + ASSERT_TRUE(ret == ERR_OK); +} + +/** + * @tc.name: TestRemoveIptablesFilterRuleFail + * @tc.desc: Test RemoveIptablesFilterRule func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestRemoveIptablesFilterRuleFail, TestSize.Level1) +{ + Utils::SetEdmServiceDisable(); + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + IPTABLES::RemoveFilter removeFilter; + int32_t ret = networkManagerProxy->RemoveIptablesFilterRule(admin, removeFilter); + ASSERT_TRUE(ret == EdmReturnErrCode::ADMIN_INACTIVE); +} + +/** + * @tc.name: TestListIptablesFilterRulesSuc + * @tc.desc: Test ListIptablesFilterRules func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestListIptablesFilterRulesSuc, TestSize.Level1) +{ + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + EXPECT_CALL(*object_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(object_.GetRefPtr(), &EnterpriseDeviceMgrStubMock::InvokeSendRequestGetPolicy)); + std::string result; + int32_t ret = networkManagerProxy->ListIptablesFilterRules(admin, result); + ASSERT_TRUE(ret == ERR_OK); +} + +/** + * @tc.name: TestListIptablesFilterRulesFail + * @tc.desc: Test ListIptablesFilterRules func. + * @tc.type: FUNC + */ +HWTEST_F(NetworkManagerProxyTest, TestListIptablesFilterRulesFail, TestSize.Level1) +{ + Utils::SetEdmServiceDisable(); + AppExecFwk::ElementName admin; + admin.SetBundleName(ADMIN_PACKAGENAME); + std::string result; + int32_t ret = networkManagerProxy->ListIptablesFilterRules(admin, result); + ASSERT_TRUE(ret == EdmReturnErrCode::ADMIN_INACTIVE); +} +} // namespace TEST +} // namespace EDM +} // namespace OHOS