(no commit message)
[ikiwiki.git] / docs / ipfw3 / index.mdwn
1 [[!meta title="Ipfw3 Documentation"]]
2 [[!meta robots="index, follow"]]
3
4
5 bycn82
6
7 22 Feb. 2016 (lantern festival)
8
9 ---
10
11 [[!toc  levels=3]]
12
13 # Introduction
14 Ipfw is a controlling utility for ipfw/ipacct facilities for FreeBSD 2.0 which released in November, 1994. After 20 years of evolution. it becomes a stateful firewall. It is comprised of several components, e.g. the kernel firewall filter rule processor and its integrated packet accounting facility, the logging facility, NAT, the dummynet(4) traffic shaper, a forward facility, a bridge facility, and an ipstealth facility. It is one of the most advanced opensource firewall.
15
16 DragonflyBSD is a logical continuation of the FreeBSD 4.x series, DragonFly's development has diverged significantly from FreeBSD's, e.g. a new Light Weight Kernel Threads implementation (LWKT), a lightweight ports/messaging system,
17
18 In DragonFly, each CPU has its own thread scheduler. Upon creation, threads are assigned to processors and are never preemptively switched from one processor to another; they are only migrated by the passing of an inter-processor interrupt (IPI) message between the CPUs involved. Inter-processor thread scheduling is also accomplished by sending asynchronous IPI messages. One advantage to this clean compartmentalization of the threading subsystem is that the processors' on-board caches in Symmetric Multiprocessor Systems do not contain duplicated data, allowing for higher performance by giving each processor in the system the ability to use its own cache to store different things to work on.
19
20 The LWKT subsystem is being employed to partition work among multiple kernel threads (for example in the networking code there is one thread per protocol per processor), reducing competition by removing the need to share certain resources among various kernel tasks.
21
22 This ipfw was rewritten from scratch for DragonflyBSD and named 'ipfw3', it is in modular design, and inherited the "SMP-Friendly" feature of DragonflyBSD's LWKT, it is a lockless and stateful firewall.
23
24 ## Brief notes on design
25 Ipfw3 was in modular design. all the functionalities are implemented in different loadable modules, it can be loaded when it is required. the core framework of the ipfw3 only comes with default'accept' or 'deny' actions. by triggering below command, the core module will be loaded.
26
27         kldload ipfw3
28
29 the fundamental core framework is loaded now. 
30
31 More basic firewall filtering features like 'filtering based on source IP' are implemented in basic module, so basic module need to be loaded before we start to the features. and below is the command to load the basic module, the basic module is relying on the core framework, so the core framework will be loaded automatically if it is not loaded yet,
32
33         kldload ipfw3_basic
34
35 The basic module is loaded now. then the user can start to use the filters which was implemented in the basic module. besides the basic module, there are layer2 module, layer4 module, in-kernel NAT module, dummynet module.
36
37 Each module contains 2 parts. library in user-space which will be loaded and parse the command line into rules. and kernel space portion will be invoked when the traffic hit the firewall and it will trigger the correct action according to the firewall rules.
38
39 ## Compare with FreeBSD's ipfw
40 Ipfw3 inherited all feature from FreeBSD's ipfw, and lots of new features are introduced from PF or other rivals.
41
42 **Much more extensible**
43
44 Every filter/action needs to be identified using ID, but there are only 8 bits space to store the ID, so theoretically it can support 256 filters/actions in maximum in FreeBSD' ipfw. While in ipfw3, the space for ID are still the same, but one space introduced to keep the module's ID, so theoretically ipfw3 can have 256 modules and 256 filter/action in each module.
45
46 And in ipfw3, both user-space library and kernel space module are implemented with a simple interface, it is quite easy to build your own filter/module by following the interface.
47
48 **Much more concise**
49
50 the rules of ipfw3 are much more concise. for example, the simple rule command like 
51
52     ipfw add allow ip from any to any
53    
54 the "from any to any" actually is just try to make the rule more human-readable. In ipfw3 we support the syntax of FreeBSD's ipfw, but we recommend to use simplified version as below:
55
56     #1. ipfw3 add allow all 
57     #2. ipfw3 add allow icmp from 1.1.1.1
58     #3. ipfw3 add allow tcp via em0
59
60 **Higher Performance**
61
62 All modern CPUs are having mutil-cores, and each core are running independently. So the LWKT of DragonflyBSD is the best way to fully utilize the CPU power. by duplicating the environment for each CPU, all the CPU can run as fast as it can without any interference. So it is a lockless and stateful firewall.
63
64
65 # Basic Configuration
66
67 ## Core Framework
68
69 Below actions are directly supported from the core framework.
70
71 **accept**  -- accept the traffic
72
73 **deny**  -- deny the traffic
74
75 the default action of the firewall was compiled in the core framework. but it still can be interfered by below sysctl when the module was loading into the kernel.
76
77     sysctl net.filters_default_to_accept
78
79 ## Basic Module
80
81 Below filter/actions are supported in basic module.
82
83 **proto** -- matches traffic protocol, it is implicit after the action.
84
85 **from** -- matches the source.
86
87 Filter 'from' supports multiple type of parameters.
88
89     from 8.8.8.8 -- match traffic from IP 8.8.8.8
90     from table 1    -- match traffic where source IP found in table 1
91     from any  -- not filtering
92     from me  -- match traffic from the host
93     from 192.168.1.0/24 -- match traffic from the IP range
94  
95 **to** -- matches the destination.
96
97 Filter 'to' supports same parameters as filter 'from'
98
99 **count** -- action count the traffic
100
101 **skipto** -- skipto another line in the rules
102
103 **forward** -- forward the current traffic to a destination
104
105 **in** -- matches the in direction traffic
106
107 **out** -- matches the out direction traffic
108
109 **via** -- matches the traffic go throught an interface
110
111 **xmit** -- matches the out direction traffic thought an interface
112
113 **recv** -- matches the in direction traffic thought an interface
114
115 **src-port** --matches the src port of TCP/UDP traffic
116
117 **dst-port** --matches the dst port of TCP/UDP traffic
118
119 **prob** -- randomly match the traffic
120
121 **keep-state** -- setup a state in current CPU only
122
123 **check-state** -- loop the state table current CPU, match if its state exists
124
125 **tag** -- add a tag the traffic
126
127 **untag** -- remove the tag from the traffic
128
129 **tagged** -- matched the traffic with the tag
130
131 **//** -- append some comment at the end of the rule
132
133 ## Layer2 Module
134
135 **layer2** -- matches layer2 traffic
136
137 **mac** -- matches layer2 traffic with src and dst MAC addresses
138
139 **mac-from** -- matches layer2 traffic with src MAC address (supports lookup table)
140
141 **mac-to** -- matches layer2 traffic with dst MAC address (supports lookup table)
142  
143 ## Layer4 Module
144
145 **tcpflag**  -- matches the TCP flag
146
147 **uid** -- matches the sockets owner ID
148
149 **gid** -- matches the sockets owner's group ID
150
151 **established** --matched the established TCP connection
152
153 **bpf**  -- filter traffic with bpf syntax
154  
155 ## NAT Module
156
157 **nat** -- NAT traffic with pre-defined NAT configuration
158  
159 ## Dummynet3 Module
160
161 **pipe** -- pipe traffic with pre-defined pipe configuration
162
163 **queue** -- queue traffic with pre-defined queue configuration
164
165 # Advanced Configuration
166
167 ## Rule Set
168
169 Each rule belongs to one of 32 different sets , numbered 0 to 31. Set 31 is reserved for the default rule.
170
171 By default, rules are put in set 0, unless you use the set N attribute when entering a new rule. Sets can be individually and atomically enabled or disabled, so this mechanism permits an easy way to store multiple configurations of the firewall and quickly (and atomically) switch between them.  The command to enable/disable sets is
172
173     ipfw set [disable number ...] [enable number ...]
174
175 where multiple enable or disable sections can be specified.  Command execution is atomic on all the sets specified in the command.  By default, all sets are enabled.
176
177 ## Lookup Table
178
179 In the following example, We need to create several rules in order to block ICMP traffic from whole range of the network 192.168.0.0/24.
180
181     ipfw3 add deny icmp from 192.168.0.1
182  ipfw3 add deny icmp from 192.168.0.2
183  ipfw3 add deny icmp from 192.168.0.3
184  ...
185  ipfw3 add deny icmp from 192.168.0.254
186
187 The firewall need to process the 254 lines of rule line by line. in this situation, the lookup table was introduced in order to increase the performance and enhance the usability.
188
189     ipfw3 table 1 append range 192.168.0.0/24
190  ipfw3 add deny icmp from table 1
191  
192 and lookup table are supported by multiple filters.
193
194 ## Forwarding
195
196 The forward action will change the next-hop on matching packets to ipaddr, which can be an IP address in dotted quad format or a host name.The search terminates if this rule matches.
197
198 If ipaddr it can be is a local addresses, then matching packets will be forwarded to port (or the port number in the packet if one is not specified in the rule) on the local machine. If ipaddr is not a local address, then the port number (if specified) is ignored, and the packet will be forwarded to the remote address, using the route as found in the local routing table for that IP.  Use commas to separate multiple ip addresses.
199
200 forward action supports multiple options, it can be `round-robin' or `sticky'.  `sticky' is calculated based on the src ip addresses, and if no forward-option, by default it will be 'random'.
201
202     ipfw3 add forward 192.168.1.1:80,192.168.1.2:80 round-robin tcp from ....
203  
204 Above example can forward the traffic to 2 destination in round-robin.
205
206 A forward rule will not match layer-2 packets (those received on ether_input() or ether_output()). The forward action does not change the contents of the packet at all.  In particular, the destination address remains unmodified, so packets forwarded to another system will usually be rejected by that system unless there is a matching rule on that system to capture them.  For packets forwarded locally, the local address of the socket will be set to the original destination address of the packet.  This makes the netstat(1) entry look rather weird but is intended for use with transparent proxy servers.
207     
208 ## BPF Filtering
209
210 Berkeley Packet Filter (BPF)'s filtering capabilities are implemented as an interpreter for a machine language for the BPF virtual machine; programs in that language can fetch data from the packet, perform arithmetic operations on data from the packet, and compare the results against constants or against data in the packet or test bits in the results, accepting or rejecting the packet based on the results of those tests. The original paper was written by Steven McCanne and Van Jacobson in 1992 while at Lawrence Berkeley Laboratory.
211
212 The ipfw3 firewall integrates with a BPF filter, a just-in-time compilation is used to convert virtual machine instructions into native code, and it will be invoked when the traffic hits a rule with BPF filter.
213     
214     ipfw3 add allow all bpf "icmp and src 8.8.8.8"
215  
216 the bpf filter can be used to filter all parts of the packet, includes the payload.
217
218 ## Stateful
219
220 Stateful operation is a way for the firewall to dynamically create states for specific flows when packets that match a given pattern are detected. Support for stateful operation comes through the check-state, keep-state of rules.
221
222 States are created when a packet matches a keep-state rule, causing the creation of a dynamic rule which will match all and only packets with a given protocol between a src-ip/src-port dst-ip/dst-port pair of addresses (src and dst are used here only to denote the initial match addresses, but they are completely equivalent afterwards).  Dynamic rules will be checked at the first check-state, keep-state or limit occurrence, and the action performed upon a match will be the same as in the parent rule.
223
224 Note that no additional attributes other than protocol and IP addresses and ports are checked on dynamic rules.
225
226 The typical use of dynamic rules is to keep a closed firewall configuration, but let the first TCP SYN packet from the inside network install a state for the flow so that packets belonging to that session will be allowed through the firewall:
227
228     ipfw3 add check-state
229     ipfw3 add allow tcp from my-subnet to any keep-state
230     ipfw3 add deny tcp from any to any
231
232 A similar approach can be used for UDP, where an UDP packet coming from the inside will install a dynamic rule to let the response through the firewall:
233
234     ipfw3 add check-state
235     ipfw3 add allow udp from my-subnet to any keep-state
236     ipfw3 add deny udp from any to any
237
238 States expire after some time, which depends on the status of the flow and the setting of some sysctl variables.  See Section SYSCTL VARIABLES for more details.  For TCP sessions, dynamic rules can be instructed to periodically send keepalive packets to refresh the state of the rule when it is about to expire.
239
240 States can be added/deleted using the ipfw3 utility. and the inserted states will be hosted on the current CPU only. once the live time expired, the state will be purged by the housekeeping process and will not be able to influence the traffic.
241  
242     ipfw state add rule 1000 udp 192.168.1.100:0 8.8.8.8:53 expiry 600
243
244 Above example can immediately  insert a state which will link to rule 1000 for the UDP traffic which is from 192.168.1.100 to 8.8.8.8:53, and the state will be expired in 600 seconds if no traffic update the states.
245   
246 ## In-Kernel NAT
247
248 Ipfw3 supports NAT using the kernel version of libalias which is a moderately portable set of functions designed to assist in the process of IP masquerading and network address translation. Out-going packets from a local network with unregistered IP addresses can be aliased to appear as if they came from an accessible IP address. Incoming packets are then de-aliased so that they are sent to the correct machine on the local network.
249
250 A certain amount of flexibility is built into the packet aliasing engine.In the simplest mode of operation, a many-to-one address mapping takes place between the local network and the packet aliasing host.  This is known as IP masquerading. In addition, one-to-one mappings between local and public addresses can also be implemented, which is known as static NAT.  In between these extremes, different groups of private addresses can be linked to different public addresses, comprising several distinct many-to-one mappings.  Also, a given public address and port can be statically redirected to a private address/port.
251
252 ## Ipfwsync
253
254 The facility in ipfw3 which was create in order to synchronize firewall states between machines running ipfw3 firewall for high availability is named 'ipfw3sync'. It can be used together with CARP to make ensure a backup firewall has the same states as the main firewall. When the master machine in the firewall cluster dies, the slave machine is able to takeover the service and accept current connections without loss. And each ipfw3sync can be configured in centre or edge. the centre will continuously sync the states to the edges using UDP protocol.
255
256 Use below commands to configure an ipfw3sync edge. The edge will listen on the UDP port 5000.
257
258     ipfw3 sync edge 5000
259     ipfw3 sync start edge
260
261 Below command to configure an ipfw3sync centre, and this ipfw3sync centre will automatically sync the states to edge 192.168.1.1:5000 and edge 192.168.1.2:5001.
262
263     ipfw3 sync centre 192.168.1.1:5000,192.168.1.2:5001
264     ipfw3 sync start centre
265
266 Below command to verify whether the ipfw3 centre can send the test message to all the configured edges.
267
268     ipfw3 sync test centre 1
269
270 #Additional Topics
271
272 ## Logging
273
274 Ipfw3 support 10 pseudo ipfw interfaces for logging. and the pseudo intercaces can be create with below command:
275
276         ifconfig ipfw1 create
277
278 Traffic matching a rule with the 'log' action will be captured by the BPF and duplicated into an ipfw pseudo interface accordingly. e.g.
279
280         ipfw add 100 allow log 1 icmp from 8.8.8.8
281
282 Above rule will attach the ICMP packet to the ipfw1 interface and the ICMP packets are from 8.8.8.8. 
283  
284 # Example Rules
285
286 Collection of the ipfw3 samples/articles.
287
288 * [IPFW3 and NAT](http://lists.dragonflybsd.org/pipermail/users/2015-June/207790.html)