1# Network Firewall (For System Applications Only)
2
3## Introduction
4
5Network firewalls provide the following functions:
6- Basic firewall management functions, such as enabling and disabling of firewalls and firewall rules, and audit.
7- Firewall rule configuration, including the rule name, description, operation, applicable application, protocol type, address, port, and outbound/inbound direction.
8- DNS policy configuration, including the domain names allowed or not allowed for resolution and the DNS server (active or standby) used for resolution (application level).
9
10> **NOTE**
11> To maximize the application running efficiency, all APIs are called asynchronously in callback or promise mode. The following code examples use the promise mode. For details about the APIs, see [API Reference](../reference/apis-network-kit/js-apis-net-netfirewall.md).
12
13## **Constraints**
14
15- Programming language: JS
16
17## When to Use
18
19Typical firewall scenarios include:
20- IP address-based access control
211. Restricting network access for specific applications
222. Restricting network communication to specific IP addresses, protocols, and ports
233. Restricting network communication of specific applications to specific IP addresses, protocols, and ports
244. Putting interception rules into effect immediately after delivery (This function is applicable only to the TCP protocol. An intercepted TCP connection must be disconnected.)
25- Domain name-based access control
261. Restricting DNS resolution of an application for specific domain names (This function is applicable to standard unencrypted DNS protocols, but not encrypted and private DNS protocols.)
272. Restricting DNS resolution of specific applications for specific domain names (This function is applicable to standard unencrypted DNS protocols, but not encrypted and private DNS protocols.)
283. Putting interception rules into effect immediately after delivery (This function is applicable only to the TCP protocol. An intercepted TCP connection must be disconnected.)
29- Traceable network access
301. Query of interception records for system applications
312. Automatic saving of interception rules and automatic recovery upon startup
32
33The following describes the development procedure specific to each application scenario.
34
35## Available APIs
36
37For the complete list of APIs and example code, see [Network Firewall](../reference/apis-network-kit/js-apis-net-netfirewall.md).
38
39| Name                                                                                              | Description             |
40| -------------------------------------------------------------------------------------------------- | ----------------- |
41| setNetFirewallPolicy(userId: number, policy: NetFirewallPolicy): Promise\<void>                    | Sets the firewall status.   |
42| getNetFirewallPolicy(userId: number): Promise\<NetFirewallPolicy>                                  | Obtains the firewall status.   |
43| addNetFirewallRule(rule: NetFirewallRule): Promise\<number>                                        | Adds firewall rules.   |
44| updateNetFirewallRule(rule: NetFirewallRule): Promise\<void>                                       | Updates firewall rules.   |
45| removeNetFirewallRule(userId: number, ruleId: number): Promise\<void>                              | Removes firewall rules.   |
46| getNetFirewallRules(userId: number, requestParam: RequestParam): Promise\<FirewallRulePage>        | Performs pagination query on firewall rules.|
47| getNetFirewallRule(userId: number, ruleId: number): Promise\<NetFirewallRule>                      | Queries a firewall rule.|
48| getInterceptedRecords(userId: number, requestParam: RequestParam): Promise\<InterceptedRecordPage> | Queries firewall interception records.|
49
50## IP Address-based Access Control
51
521. Use a network cable to connect the device to a network port.
532. Import the **netfirewall** namespace from **@ohos.net.netFirewall**.
543. Call **setNetFirewallPolicy** to enable the firewall.
554. Call **addNetFirewallRule** to add firewall rules.
56
57```ts
58// Import the netFirewall namespace from @kit.NetworkKit.
59import { netFirewall } '@kit.NetworkKit';
60import { BusinessError } from '@kit.BasicServicesKit';
61
62// Define the firewall policy to enable the firewall and deny inbound traffic while allowing outbound traffic.
63let policy: netFirewall.NetFirewallPolicy = {
64  isOpen: true,
65  inAction: netFirewall.FirewallRuleAction.RULE_DENY,
66  outAction: netFirewall.FirewallRuleAction.RULE_ALLOW
67};
68// Set the firewall policy for user 100.
69netFirewall.setNetFirewallPolicy(100, policy).then(() => {
70  console.info("set firewall policy success.");
71}).catch((error : BusinessError) => {
72  console.error("set firewall policy failed: " + JSON.stringify(error));
73});
74
75// Initialize firewall rules for specific types of IP addresses.
76let ipRule: netFirewall.NetFirewallRule = {
77  name: "rule1",
78  description: "rule1 description",
79  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
80  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
81  type: netFirewall.NetFirewallRuleType.RULE_IP,
82  isEnabled: true,
83  appUid: 20001,
84  localIps: [
85    {
86      family: 1,
87      type: 1,
88      address: "10.10.1.1",
89      mask: 24
90    },{
91      family: 1,
92      type: 2,
93      startIp: "10.20.1.1",
94      endIp: "10.20.1.10"
95    }],
96  remoteIps:[
97    {
98      family: 1,
99      type: 1,
100      address: "20.10.1.1",
101      mask: 24
102    },{
103      family: 1,
104      type: 2,
105      startIp: "20.20.1.1",
106      endIp: "20.20.1.10"
107    }],
108  protocol: 6,
109  localPorts: [
110    {
111      startPort: 1000,
112      endPort: 1000
113    },{
114      startPort: 2000,
115      endPort: 2001
116    }],
117  remotePorts: [
118    {
119      startPort: 443,
120      endPort: 443
121    }],
122  userId: 100
123};
124// Add firewall rules.
125netFirewall.addNetFirewallRule(ipRule).then((result: number) => {
126  console.info('rule Id: ', result);
127}, (reason: BusinessError) => {
128  console.error('add firewall rule failed: ', JSON.stringify(reason));
129});
130```
131
132## Domain Name-based Access Control
133
1341. Use a network cable to connect the device to a network port.
1352. Import the **netFirewall** namespace from **@ohos.net.netfirewall**.
1363. Call **setNetFirewallPolicy** to enable the firewall in user mode.
1374. Call **addNetFirewallRule** to add firewall rules in user mode.
138
139```ts
140// Import the netfirewall namespace from @kit.NetworkKit.
141import { netFirewall } '@kit.NetworkKit';
142import { BusinessError } from '@kit.BasicServicesKit';
143
144// Define the firewall policy to enable the firewall and deny inbound traffic while allowing outbound traffic.
145let policy: netFirewall.NetFirewallPolicy = {
146  isOpen: true,
147  inAction: netFirewall.FirewallRuleAction.RULE_DENY,
148  outAction: netFirewall.FirewallRuleAction.RULE_ALLOW
149};
150// Set the firewall policy for user 100.
151netFirewall.setNetFirewallPolicy(100, policy).then(() => {
152  console.info("set firewall policy success.");
153}).catch((error : BusinessError) => {
154  console.error("set firewall policy failed: " + JSON.stringify(error));
155});
156
157// Initialize firewall rules for specific types of domain names.
158let domainRule: netFirewall.NetFirewallRule = {
159  name: "rule2",
160  description: "rule2 description",
161  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
162  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
163  type: netFirewall.NetFirewallRuleType.RULE_DOMAIN,
164  isEnabled: true,
165  appUid: 20002,
166  domains: [
167    {
168      isWildcard: false,
169      domain: "www.openharmony.cn"
170    },{
171      isWildcard: true,
172      domain: "*.openharmony.cn"
173    }],
174  userId: 100
175};
176// Add firewall rules.
177netFirewall.addNetFirewallRule(domainRule).then((result: number) => {
178  console.info('rule Id: ', result);
179}, (reason: BusinessError) => {
180  console.error('add firewall rule failed: ', JSON.stringify(reason));
181});
182```
183
184## Query of Firewall Interception Records
185
1861. Use a network cable to connect the device to a network port.
1872. Import the **netfirewall** namespace from **@ohos.net.netFirewall**.
1883. Call **getInterceptRecords** to query firewall interception records in user mode.
189
190```ts
191// Import the netFirewall namespace from @kit.NetworkKit.
192import { netFirewall } '@kit.NetworkKit';
193import { BusinessError } from '@kit.BasicServicesKit';
194
195// Call getInterceptedRecords to perform pagination query on firewall interception records.
196let interceptRecordParam: netFirewall.RequestParam = {
197  page: 1,
198  pageSize: 10,
199  orderField: netFirewall.NetFirewallOrderField.ORDER_BY_RECORD_TIME,
200  orderType: netFirewall.NetFirewallOrderType.ORDER_DESC
201};
202netFirewall.getInterceptedRecords(100, interceptRecordParam).then((result: netFirewall.InterceptedRecordPage) => {
203  console.info("result:", JSON.stringify(result));
204}, (error: BusinessError) => {
205  console.error("get intercept records failed: " + JSON.stringify(error));
206});
207```
208