xref: /freebsd/sbin/ipfw/ipfw.8 (revision 99f3b482da15db6f2ae4702d592b53dd36d4cf55)
1.\"
2.\" $FreeBSD$
3.\"
4.Dd July 25, 2006
5.Dt IPFW 8
6.Os
7.Sh NAME
8.Nm ipfw
9.Nd IP firewall and traffic shaper control program
10.Sh SYNOPSIS
11.Nm
12.Op Fl cq
13.Cm add
14.Ar rule
15.Nm
16.Op Fl acdefnNStT
17.Brq Cm list | show
18.Op Ar rule | first-last ...
19.Nm
20.Op Fl f | q
21.Cm flush
22.Nm
23.Op Fl q
24.Brq Cm delete | zero | resetlog
25.Op Cm set
26.Op Ar number ...
27.Nm
28.Cm enable
29.Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
30.Nm
31.Cm disable
32.Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
33.Pp
34.Nm
35.Cm set Oo Cm disable Ar number ... Oc Op Cm enable Ar number ...
36.Nm
37.Cm set move
38.Op Cm rule
39.Ar number Cm to Ar number
40.Nm
41.Cm set swap Ar number number
42.Nm
43.Cm set show
44.Pp
45.Nm
46.Cm table Ar number Cm add Ar addr Ns Oo / Ns Ar masklen Oc Op Ar value
47.Nm
48.Cm table Ar number Cm delete Ar addr Ns Op / Ns Ar masklen
49.Nm
50.Cm table Ar number Cm flush
51.Nm
52.Cm table Ar number Cm list
53.Pp
54.Nm
55.Brq Cm pipe | queue
56.Ar number
57.Cm config
58.Ar config-options
59.Nm
60.Op Fl s Op Ar field
61.Brq Cm pipe | queue
62.Brq Cm delete | list | show
63.Op Ar number ...
64.Pp
65.Nm
66.Op Fl cfnNqS
67.Oo
68.Fl p Ar preproc
69.Oo
70.Ar preproc-flags
71.Oc
72.Oc
73.Ar pathname
74.Sh DESCRIPTION
75The
76.Nm
77utility is the user interface for controlling the
78.Xr ipfw 4
79firewall and the
80.Xr dummynet 4
81traffic shaper in
82.Fx .
83.Pp
84An
85.Nm
86configuration, or
87.Em ruleset ,
88is made of a list of
89.Em rules
90numbered from 1 to 65535.
91Packets are passed to
92.Nm
93from a number of different places in the protocol stack
94(depending on the source and destination of the packet,
95it is possible that
96.Nm
97is invoked multiple times on the same packet).
98The packet passed to the firewall is compared
99against each of the rules in the firewall
100.Em ruleset .
101When a match is found, the action corresponding to the
102matching rule is performed.
103.Pp
104Depending on the action and certain system settings, packets
105can be reinjected into the firewall at some rule after the
106matching one for further processing.
107.Pp
108An
109.Nm
110ruleset always includes a
111.Em default
112rule (numbered 65535) which cannot be modified or deleted,
113and matches all packets.
114The action associated with the
115.Em default
116rule can be either
117.Cm deny
118or
119.Cm allow
120depending on how the kernel is configured.
121.Pp
122If the ruleset includes one or more rules with the
123.Cm keep-state
124or
125.Cm limit
126option, then
127.Nm
128assumes a
129.Em stateful
130behaviour, i.e., upon a match it will create dynamic rules matching
131the exact parameters (addresses and ports) of the matching packet.
132.Pp
133These dynamic rules, which have a limited lifetime, are checked
134at the first occurrence of a
135.Cm check-state ,
136.Cm keep-state
137or
138.Cm limit
139rule, and are typically used to open the firewall on-demand to
140legitimate traffic only.
141See the
142.Sx STATEFUL FIREWALL
143and
144.Sx EXAMPLES
145Sections below for more information on the stateful behaviour of
146.Nm .
147.Pp
148All rules (including dynamic ones) have a few associated counters:
149a packet count, a byte count, a log count and a timestamp
150indicating the time of the last match.
151Counters can be displayed or reset with
152.Nm
153commands.
154.Pp
155Rules can be added with the
156.Cm add
157command; deleted individually or in groups with the
158.Cm delete
159command, and globally (except those in set 31) with the
160.Cm flush
161command; displayed, optionally with the content of the
162counters, using the
163.Cm show
164and
165.Cm list
166commands.
167Finally, counters can be reset with the
168.Cm zero
169and
170.Cm resetlog
171commands.
172.Pp
173Also, each rule belongs to one of 32 different
174.Em sets
175, and there are
176.Nm
177commands to atomically manipulate sets, such as enable,
178disable, swap sets, move all rules in a set to another
179one, delete all rules in a set.
180These can be useful to
181install temporary configurations, or to test them.
182See Section
183.Sx SETS OF RULES
184for more information on
185.Em sets .
186.Pp
187The following options are available:
188.Bl -tag -width indent
189.It Fl a
190While listing, show counter values.
191The
192.Cm show
193command just implies this option.
194.It Fl b
195Only show the action and the comment, not the body of a rule.
196Implies
197.Fl c .
198.It Fl c
199When entering or showing rules, print them in compact form,
200i.e., without the optional "ip from any to any" string
201when this does not carry any additional information.
202.It Fl d
203While listing, show dynamic rules in addition to static ones.
204.It Fl e
205While listing, if the
206.Fl d
207option was specified, also show expired dynamic rules.
208.It Fl f
209Do not ask for confirmation for commands that can cause problems
210if misused,
211.No i.e. Cm flush .
212If there is no tty associated with the process, this is implied.
213.It Fl n
214Only check syntax of the command strings, without actually passing
215them to the kernel.
216.It Fl N
217Try to resolve addresses and service names in output.
218.It Fl q
219While
220.Cm add Ns ing ,
221.Cm zero Ns ing ,
222.Cm resetlog Ns ging
223or
224.Cm flush Ns ing ,
225be quiet about actions
226(implies
227.Fl f ) .
228This is useful for adjusting rules by executing multiple
229.Nm
230commands in a script
231(e.g.,
232.Ql sh\ /etc/rc.firewall ) ,
233or by processing a file of many
234.Nm
235rules across a remote login session. It also stops a table add or delete
236from failing if the entry already exists or is not present.
237If a
238.Cm flush
239is performed in normal (verbose) mode (with the default kernel
240configuration), it prints a message.
241Because all rules are flushed, the message might not be delivered
242to the login session, causing the remote login session to be closed
243and the remainder of the ruleset to not be processed.
244Access to the console would then be required to recover.
245.It Fl S
246While listing rules, show the
247.Em set
248each rule belongs to.
249If this flag is not specified, disabled rules will not be
250listed.
251.It Fl s Op Ar field
252While listing pipes, sort according to one of the four
253counters (total or current packets or bytes).
254.It Fl t
255While listing, show last match timestamp (converted with ctime()).
256.It Fl T
257While listing, show last match timestamp (as seconds from the epoch).
258This form can be more convenient for postprocessing by scripts.
259.El
260.Pp
261To ease configuration, rules can be put into a file which is
262processed using
263.Nm
264as shown in the last synopsis line.
265An absolute
266.Ar pathname
267must be used.
268The file will be read line by line and applied as arguments to the
269.Nm
270utility.
271.Pp
272Optionally, a preprocessor can be specified using
273.Fl p Ar preproc
274where
275.Ar pathname
276is to be piped through.
277Useful preprocessors include
278.Xr cpp 1
279and
280.Xr m4 1 .
281If
282.Ar preproc
283does not start with a slash
284.Pq Ql /
285as its first character, the usual
286.Ev PATH
287name search is performed.
288Care should be taken with this in environments where not all
289file systems are mounted (yet) by the time
290.Nm
291is being run (e.g.\& when they are mounted over NFS).
292Once
293.Fl p
294has been specified, any additional arguments as passed on to the preprocessor
295for interpretation.
296This allows for flexible configuration files (like conditionalizing
297them on the local hostname) and the use of macros to centralize
298frequently required arguments like IP addresses.
299.Pp
300The
301.Nm
302.Cm pipe
303and
304.Cm queue
305commands are used to configure the traffic shaper, as shown in the
306.Sx TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
307Section below.
308.Pp
309If the world and the kernel get out of sync the
310.Nm
311ABI may break, preventing you from being able to add any rules.
312This can
313adversely effect the booting process.
314You can use
315.Nm
316.Cm disable
317.Cm firewall
318to temporarily disable the firewall to regain access to the network,
319allowing you to fix the problem.
320.Sh PACKET FLOW
321A packet is checked against the active ruleset in multiple places
322in the protocol stack, under control of several sysctl variables.
323These places and variables are shown below, and it is important to
324have this picture in mind in order to design a correct ruleset.
325.Bd -literal -offset indent
326       ^    to upper layers    V
327       |                       |
328       +----------->-----------+
329       ^                       V
330 [ip(6)_input]           [ip(6)_output]     net.inet(6).ip(6).fw.enable=1
331       |                       |
332       ^                       V
333 [ether_demux]        [ether_output_frame]  net.link.ether.ipfw=1
334       |                       |
335       +-->--[bdg_forward]-->--+            net.link.bridge.ipfw=1
336       ^                       V
337       |      to devices       |
338.Ed
339.Pp
340As can be noted from the above picture, the number of
341times the same packet goes through the firewall can
342vary between 0 and 4 depending on packet source and
343destination, and system configuration.
344.Pp
345Note that as packets flow through the stack, headers can be
346stripped or added to it, and so they may or may not be available
347for inspection.
348E.g., incoming packets will include the MAC header when
349.Nm
350is invoked from
351.Cm ether_demux() ,
352but the same packets will have the MAC header stripped off when
353.Nm
354is invoked from
355.Cm ip_input()
356or
357.Cm ip6_input() .
358.Pp
359Also note that each packet is always checked against the complete ruleset,
360irrespective of the place where the check occurs, or the source of the packet.
361If a rule contains some match patterns or actions which are not valid
362for the place of invocation (e.g.\& trying to match a MAC header within
363.Cm ip_input
364or
365.Cm ip6_input ),
366the match pattern will not match, but a
367.Cm not
368operator in front of such patterns
369.Em will
370cause the pattern to
371.Em always
372match on those packets.
373It is thus the responsibility of
374the programmer, if necessary, to write a suitable ruleset to
375differentiate among the possible places.
376.Cm skipto
377rules can be useful here, as an example:
378.Bd -literal -offset indent
379# packets from ether_demux or bdg_forward
380ipfw add 10 skipto 1000 all from any to any layer2 in
381# packets from ip_input
382ipfw add 10 skipto 2000 all from any to any not layer2 in
383# packets from ip_output
384ipfw add 10 skipto 3000 all from any to any not layer2 out
385# packets from ether_output_frame
386ipfw add 10 skipto 4000 all from any to any layer2 out
387.Ed
388.Pp
389(yes, at the moment there is no way to differentiate between
390ether_demux and bdg_forward).
391.Sh SYNTAX
392In general, each keyword or argument must be provided as
393a separate command line argument, with no leading or trailing
394spaces.
395Keywords are case-sensitive, whereas arguments may
396or may not be case-sensitive depending on their nature
397(e.g.\& uid's are, hostnames are not).
398.Pp
399In
400.Nm ipfw2
401you can introduce spaces after commas ',' to make
402the line more readable.
403You can also put the entire
404command (including flags) into a single argument.
405E.g., the following forms are equivalent:
406.Bd -literal -offset indent
407ipfw -q add deny src-ip 10.0.0.0/24,127.0.0.1/8
408ipfw -q add deny src-ip 10.0.0.0/24, 127.0.0.1/8
409ipfw "-q add deny src-ip 10.0.0.0/24, 127.0.0.1/8"
410.Ed
411.Sh RULE FORMAT
412The format of
413.Nm
414rules is the following:
415.Bd -ragged -offset indent
416.Bk -words
417.Op Ar rule_number
418.Op Cm set Ar set_number
419.Op Cm prob Ar match_probability
420.Ar action
421.Op Cm log Op Cm logamount Ar number
422.Op Cm altq Ar queue
423.Oo
424.Bro Cm tag | untag
425.Brc Ar number
426.Oc
427.Ar body
428.Ek
429.Ed
430.Pp
431where the body of the rule specifies which information is used
432for filtering packets, among the following:
433.Pp
434.Bl -tag -width "Source and dest. addresses and ports" -offset XXX -compact
435.It Layer-2 header fields
436When available
437.It IPv4 and IPv6 Protocol
438TCP, UDP, ICMP, etc.
439.It Source and dest. addresses and ports
440.It Direction
441See Section
442.Sx PACKET FLOW
443.It Transmit and receive interface
444By name or address
445.It Misc. IP header fields
446Version, type of service, datagram length, identification,
447fragment flag (non-zero IP offset),
448Time To Live
449.It IP options
450.It IPv6 Extension headers
451Fragmentation, Hop-by-Hop options,
452source routing, IPSec options.
453.It IPv6 Flow-ID
454.It Misc. TCP header fields
455TCP flags (SYN, FIN, ACK, RST, etc.),
456sequence number, acknowledgment number,
457window
458.It TCP options
459.It ICMP types
460for ICMP packets
461.It ICMP6 types
462for ICMP6 packets
463.It User/group ID
464When the packet can be associated with a local socket.
465.It Divert status
466Whether a packet came from a divert socket (e.g.,
467.Xr natd 8 ) .
468.El
469.Pp
470Note that some of the above information, e.g.\& source MAC or IP addresses and
471TCP/UDP ports, could easily be spoofed, so filtering on those fields
472alone might not guarantee the desired results.
473.Bl -tag -width indent
474.It Ar rule_number
475Each rule is associated with a
476.Ar rule_number
477in the range 1..65535, with the latter reserved for the
478.Em default
479rule.
480Rules are checked sequentially by rule number.
481Multiple rules can have the same number, in which case they are
482checked (and listed) according to the order in which they have
483been added.
484If a rule is entered without specifying a number, the kernel will
485assign one in such a way that the rule becomes the last one
486before the
487.Em default
488rule.
489Automatic rule numbers are assigned by incrementing the last
490non-default rule number by the value of the sysctl variable
491.Ar net.inet.ip.fw.autoinc_step
492which defaults to 100.
493If this is not possible (e.g.\& because we would go beyond the
494maximum allowed rule number), the number of the last
495non-default value is used instead.
496.It Cm set Ar set_number
497Each rule is associated with a
498.Ar set_number
499in the range 0..31.
500Sets can be individually disabled and enabled, so this parameter
501is of fundamental importance for atomic ruleset manipulation.
502It can be also used to simplify deletion of groups of rules.
503If a rule is entered without specifying a set number,
504set 0 will be used.
505.br
506Set 31 is special in that it cannot be disabled,
507and rules in set 31 are not deleted by the
508.Nm ipfw flush
509command (but you can delete them with the
510.Nm ipfw delete set 31
511command).
512Set 31 is also used for the
513.Em default
514rule.
515.It Cm prob Ar match_probability
516A match is only declared with the specified probability
517(floating point number between 0 and 1).
518This can be useful for a number of applications such as
519random packet drop or
520(in conjunction with
521.Xr dummynet 4 )
522to simulate the effect of multiple paths leading to out-of-order
523packet delivery.
524.Pp
525Note: this condition is checked before any other condition, including
526ones such as keep-state or check-state which might have side effects.
527.It Cm log Op Cm logamount Ar number
528When a packet matches a rule with the
529.Cm log
530keyword, a message will be
531logged to
532.Xr syslogd 8
533with a
534.Dv LOG_SECURITY
535facility.
536The logging only occurs if the sysctl variable
537.Em net.inet.ip.fw.verbose
538is set to 1
539(which is the default when the kernel is compiled with
540.Dv IPFIREWALL_VERBOSE )
541and the number of packets logged so far for that
542particular rule does not exceed the
543.Cm logamount
544parameter.
545If no
546.Cm logamount
547is specified, the limit is taken from the sysctl variable
548.Em net.inet.ip.fw.verbose_limit .
549In both cases, a value of 0 removes the logging limit.
550.Pp
551Once the limit is reached, logging can be re-enabled by
552clearing the logging counter or the packet counter for that entry, see the
553.Cm resetlog
554command.
555.Pp
556Note: logging is done after all other packet matching conditions
557have been successfully verified, and before performing the final
558action (accept, deny, etc.) on the packet.
559.It Cm tag Ar number
560When a packet matches a rule with the
561.Cm tag
562keyword, the numeric tag for the given
563.Ar number
564in the range 1..65534 will be attached to the packet.
565The tag acts as an internal marker (it is not sent out over
566the wire) that can be used to identify these packets later on.
567This can be used, for example, to provide trust between interfaces
568and to start doing policy-based filtering.
569A packet can have mutiple tags at the same time.
570Tags are "sticky", meaning once a tag is applied to a packet by a
571matching rule it exists until explicit removal.
572Tags are kept with the packet everywhere within the kernel, but are
573lost when packet leaves the kernel, for example, on transmitting
574packet out to the network or sending packet to a
575.Xr divert 4
576socket.
577.Pp
578To check for previously applied tags, use the
579.Cm tagged
580rule option. To delete previously applied tag, use the
581.Cm untag
582keyword.
583.Pp
584Note: since tags are kept with the packet everywhere in kernelspace,
585they can be set and unset anywhere in kernel network subsystem
586(using
587.Xr mbuf_tags 9
588facility), not only by means of
589.Xr ipfw 4
590.Cm tag
591and
592.Cm untag
593keywords.
594For example, there can be a specialized
595.Xr netgraph 4
596node doing traffic analyzing and tagging for later inspecting
597in firewall.
598.It Cm untag Ar number
599When a packet matches a rule with the
600.Cm untag
601keyword, the tag with the number
602.Ar number
603is searched among the tags attached to this packet and,
604if found, removed from it.
605Other tags bound to packet, if present, are left untouched.
606.It Cm altq Ar queue
607When a packet matches a rule with the
608.Cm altq
609keyword, the ALTQ identifier for the given
610.Ar queue
611(see
612.Xr altq 4 )
613will be attached.
614Note that this ALTQ tag is only meaningful for packets going "out" of IPFW,
615and not being rejected or going to divert sockets.
616Note that if there is insufficient memory at the time the packet is
617processed, it will not be tagged, so it is wise to make your ALTQ
618"default" queue policy account for this.
619If multiple
620.Cm altq
621rules match a single packet, only the first one adds the ALTQ classification
622tag.
623In doing so, traffic may be shaped by using
624.Cm count Cm altq Ar queue
625rules for classification early in the ruleset, then later applying
626the filtering decision.
627For example,
628.Cm check-state
629and
630.Cm keep-state
631rules may come later and provide the actual filtering decisions in
632addition to the fallback ALTQ tag.
633.Pp
634You must run
635.Xr pfctl 8
636to set up the queues before IPFW will be able to look them up by name,
637and if the ALTQ disciplines are rearranged, the rules in containing the
638queue identifiers in the kernel will likely have gone stale and need
639to be reloaded.
640Stale queue identifiers will probably result in misclassification.
641.Pp
642All system ALTQ processing can be turned on or off via
643.Nm
644.Cm enable Ar altq
645and
646.Nm
647.Cm disable Ar altq .
648The usage of
649.Em net.inet.ip.fw.one_pass
650is irrelevant to ALTQ traffic shaping, as the actual rule action is followed
651always after adding an ALTQ tag.
652.El
653.Ss RULE ACTIONS
654A rule can be associated with one of the following actions, which
655will be executed when the packet matches the body of the rule.
656.Bl -tag -width indent
657.It Cm allow | accept | pass | permit
658Allow packets that match rule.
659The search terminates.
660.It Cm check-state
661Checks the packet against the dynamic ruleset.
662If a match is found, execute the action associated with
663the rule which generated this dynamic rule, otherwise
664move to the next rule.
665.br
666.Cm Check-state
667rules do not have a body.
668If no
669.Cm check-state
670rule is found, the dynamic ruleset is checked at the first
671.Cm keep-state
672or
673.Cm limit
674rule.
675.It Cm count
676Update counters for all packets that match rule.
677The search continues with the next rule.
678.It Cm deny | drop
679Discard packets that match this rule.
680The search terminates.
681.It Cm divert Ar port
682Divert packets that match this rule to the
683.Xr divert 4
684socket bound to port
685.Ar port .
686The search terminates.
687.It Cm fwd | forward Ar ipaddr | tablearg Ns Op , Ns Ar port
688Change the next-hop on matching packets to
689.Ar ipaddr ,
690which can be an IP address or a host name.
691The next hop can also be supplied by the last table
692looked up for the packet by using the
693.Cm tablearg
694keyword instead of an explicit address.
695The search terminates if this rule matches.
696.Pp
697If
698.Ar ipaddr
699is a local address, then matching packets will be forwarded to
700.Ar port
701(or the port number in the packet if one is not specified in the rule)
702on the local machine.
703.br
704If
705.Ar ipaddr
706is not a local address, then the port number
707(if specified) is ignored, and the packet will be
708forwarded to the remote address, using the route as found in
709the local routing table for that IP.
710.br
711A
712.Ar fwd
713rule will not match layer-2 packets (those received
714on ether_input, ether_output, or bridged).
715.br
716The
717.Cm fwd
718action does not change the contents of the packet at all.
719In particular, the destination address remains unmodified, so
720packets forwarded to another system will usually be rejected by that system
721unless there is a matching rule on that system to capture them.
722For packets forwarded locally,
723the local address of the socket will be
724set to the original destination address of the packet.
725This makes the
726.Xr netstat 1
727entry look rather weird but is intended for
728use with transparent proxy servers.
729.Pp
730To enable
731.Cm fwd
732a custom kernel needs to be compiled with the option
733.Cd "options IPFIREWALL_FORWARD" .
734.It Cm pipe Ar pipe_nr
735Pass packet to a
736.Xr dummynet 4
737.Dq pipe
738(for bandwidth limitation, delay, etc.).
739See the
740.Sx TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
741Section for further information.
742The search terminates; however, on exit from the pipe and if
743the
744.Xr sysctl 8
745variable
746.Em net.inet.ip.fw.one_pass
747is not set, the packet is passed again to the firewall code
748starting from the next rule.
749.It Cm queue Ar queue_nr
750Pass packet to a
751.Xr dummynet 4
752.Dq queue
753(for bandwidth limitation using WF2Q+).
754.It Cm reject
755(Deprecated).
756Synonym for
757.Cm unreach host .
758.It Cm reset
759Discard packets that match this rule, and if the
760packet is a TCP packet, try to send a TCP reset (RST) notice.
761The search terminates.
762.It Cm reset6
763Discard packets that match this rule, and if the
764packet is a TCP packet, try to send a TCP reset (RST) notice.
765The search terminates.
766.It Cm skipto Ar number
767Skip all subsequent rules numbered less than
768.Ar number .
769The search continues with the first rule numbered
770.Ar number
771or higher.
772.It Cm tee Ar port
773Send a copy of packets matching this rule to the
774.Xr divert 4
775socket bound to port
776.Ar port .
777The search continues with the next rule.
778.It Cm unreach Ar code
779Discard packets that match this rule, and try to send an ICMP
780unreachable notice with code
781.Ar code ,
782where
783.Ar code
784is a number from 0 to 255, or one of these aliases:
785.Cm net , host , protocol , port ,
786.Cm needfrag , srcfail , net-unknown , host-unknown ,
787.Cm isolated , net-prohib , host-prohib , tosnet ,
788.Cm toshost , filter-prohib , host-precedence
789or
790.Cm precedence-cutoff .
791The search terminates.
792.It Cm unreach6 Ar code
793Discard packets that match this rule, and try to send an ICMPv6
794unreachable notice with code
795.Ar code ,
796where
797.Ar code
798is a number from 0, 1, 3 or 4, or one of these aliases:
799.Cm no-route, admin-prohib, address
800or
801.Cm port .
802The search terminates.
803.It Cm netgraph Ar cookie
804Divert packet into netgraph with given
805.Ar cookie .
806The search terminates.
807If packet is later returned from netgraph it is either
808accepted or continues with the next rule, depending on
809.Em net.inet.ip.fw.one_pass
810sysctl variable.
811.It Cm ngtee Ar cookie
812A copy of packet is diverted into netgraph, original
813packet is either accepted or continues with the next rule, depending on
814.Em net.inet.ip.fw.one_pass
815sysctl variable.
816See
817.Xr ng_ipfw 4
818for more information on
819.Cm netgraph
820and
821.Cm ngtee
822actions.
823.El
824.Ss RULE BODY
825The body of a rule contains zero or more patterns (such as
826specific source and destination addresses or ports,
827protocol options, incoming or outgoing interfaces, etc.)
828that the packet must match in order to be recognised.
829In general, the patterns are connected by (implicit)
830.Cm and
831operators -- i.e., all must match in order for the
832rule to match.
833Individual patterns can be prefixed by the
834.Cm not
835operator to reverse the result of the match, as in
836.Pp
837.Dl "ipfw add 100 allow ip from not 1.2.3.4 to any"
838.Pp
839Additionally, sets of alternative match patterns
840.Pq Em or-blocks
841can be constructed by putting the patterns in
842lists enclosed between parentheses ( ) or braces { }, and
843using the
844.Cm or
845operator as follows:
846.Pp
847.Dl "ipfw add 100 allow ip from { x or not y or z } to any"
848.Pp
849Only one level of parentheses is allowed.
850Beware that most shells have special meanings for parentheses
851or braces, so it is advisable to put a backslash \\ in front of them
852to prevent such interpretations.
853.Pp
854The body of a rule must in general include a source and destination
855address specifier.
856The keyword
857.Ar any
858can be used in various places to specify that the content of
859a required field is irrelevant.
860.Pp
861The rule body has the following format:
862.Bd -ragged -offset indent
863.Op Ar proto Cm from Ar src Cm to Ar dst
864.Op Ar options
865.Ed
866.Pp
867The first part (proto from src to dst) is for backward
868compatibility with earlier versions of
869.Fx .
870In modern
871.Fx
872any match pattern (including MAC headers, IP protocols,
873addresses and ports) can be specified in the
874.Ar options
875section.
876.Pp
877Rule fields have the following meaning:
878.Bl -tag -width indent
879.It Ar proto : protocol | Cm { Ar protocol Cm or ... }
880.It Ar protocol : Oo Cm not Oc Ar protocol-name | protocol-number
881An IP protocol specified by number or name
882(for a complete list see
883.Pa /etc/protocols ) ,
884or one of the following keywords:
885.Bl -tag -width indent
886.It Cm ip4 | ipv4
887Matches IPv4 packets.
888.It Cm ip6 | ipv6
889Matches IPv6 packets.
890.It Cm ip | all
891Matches any packet.
892.El
893.Pp
894The
895.Cm ipv6
896in
897.Cm proto
898option will be treated as inner protocol.
899And, the
900.Cm ipv4
901is not available in
902.Cm proto
903option.
904.Pp
905The
906.Cm { Ar protocol Cm or ... }
907format (an
908.Em or-block )
909is provided for convenience only but its use is deprecated.
910.It Ar src No and Ar dst : Bro Cm addr | Cm { Ar addr Cm or ... } Brc Op Oo Cm not Oc Ar ports
911An address (or a list, see below)
912optionally followed by
913.Ar ports
914specifiers.
915.Pp
916The second format
917.Em ( or-block
918with multiple addresses) is provided for convenience only and
919its use is discouraged.
920.It Ar addr : Oo Cm not Oc Bro
921.Cm any | me | me6 |
922.Cm table Ns Pq Ar number Ns Op , Ns Ar value
923.Ar | addr-list | addr-set
924.Brc
925.It Cm any
926matches any IP address.
927.It Cm me
928matches any IP address configured on an interface in the system.
929.It Cm me6
930matches any IPv6 address configured on an interface in the system.
931The address list is evaluated at the time the packet is
932analysed.
933.It Cm table Ns Pq Ar number Ns Op , Ns Ar value
934Matches any IPv4 address for which an entry exists in the lookup table
935.Ar number .
936If an optional 32-bit unsigned
937.Ar value
938is also specified, an entry will match only if it has this value.
939See the
940.Sx LOOKUP TABLES
941section below for more information on lookup tables.
942.It Ar addr-list : ip-addr Ns Op Ns , Ns Ar addr-list
943.It Ar ip-addr :
944A host or subnet address specified in one of the following ways:
945.Bl -tag -width indent
946.It Ar numeric-ip | hostname
947Matches a single IPv4 address, specified as dotted-quad or a hostname.
948Hostnames are resolved at the time the rule is added to the firewall list.
949.It Ar addr Ns / Ns Ar masklen
950Matches all addresses with base
951.Ar addr
952(specified as an IP address or a hostname)
953and mask width of
954.Cm masklen
955bits.
956As an example, 1.2.3.4/25 will match
957all IP numbers from 1.2.3.0 to 1.2.3.127 .
958.It Ar addr Ns : Ns Ar mask
959Matches all addresses with base
960.Ar addr
961(specified as an IP address or a hostname)
962and the mask of
963.Ar mask ,
964specified as a dotted quad.
965As an example, 1.2.3.4:255.0.255.0 will match
9661.*.3.*.
967This form is advised only for non-contiguous
968masks.
969It is better to resort to the
970.Ar addr Ns / Ns Ar masklen
971format for contiguous masks, which is more compact and less
972error-prone.
973.El
974.It Ar addr-set : addr Ns Oo Ns / Ns Ar masklen Oc Ns Cm { Ns Ar list Ns Cm }
975.It Ar list : Bro Ar num | num-num Brc Ns Op Ns , Ns Ar list
976Matches all addresses with base address
977.Ar addr
978(specified as an IP address or a hostname)
979and whose last byte is in the list between braces { } .
980Note that there must be no spaces between braces and
981numbers (spaces after commas are allowed).
982Elements of the list can be specified as single entries
983or ranges.
984The
985.Ar masklen
986field is used to limit the size of the set of addresses,
987and can have any value between 24 and 32.
988If not specified,
989it will be assumed as 24.
990.br
991This format is particularly useful to handle sparse address sets
992within a single rule.
993Because the matching occurs using a
994bitmask, it takes constant time and dramatically reduces
995the complexity of rulesets.
996.br
997As an example, an address specified as 1.2.3.4/24{128,35-55,89}
998will match the following IP addresses:
999.br
10001.2.3.128, 1.2.3.35 to 1.2.3.55, 1.2.3.89 .
1001.It Ar addr6-list : ip6-addr Ns Op Ns , Ns Ar addr6-list
1002.It Ar ip6-addr :
1003A host or subnet specified one of the following ways:
1004.Pp
1005.Bl -tag -width indent
1006.It Ar numeric-ip | hostname
1007Matches a single IPv6 address as allowed by
1008.Xr inet_pton 3
1009or a hostname.
1010Hostnames are resolved at the time the rule is added to the firewall
1011list.
1012.It Ar addr Ns / Ns Ar masklen
1013Matches all IPv6 addresses with base
1014.Ar addr
1015(specified as allowed by
1016.Xr inet_pton
1017or a hostname)
1018and mask width of
1019.Cm masklen
1020bits.
1021.El
1022.Pp
1023No support for sets of IPv6 addresses is provided because IPv6 addresses
1024are typically random past the initial prefix.
1025.It Ar ports : Bro Ar port | port Ns \&- Ns Ar port Ns Brc Ns Op , Ns Ar ports
1026For protocols which support port numbers (such as TCP and UDP), optional
1027.Cm ports
1028may be specified as one or more ports or port ranges, separated
1029by commas but no spaces, and an optional
1030.Cm not
1031operator.
1032The
1033.Ql \&-
1034notation specifies a range of ports (including boundaries).
1035.Pp
1036Service names (from
1037.Pa /etc/services )
1038may be used instead of numeric port values.
1039The length of the port list is limited to 30 ports or ranges,
1040though one can specify larger ranges by using an
1041.Em or-block
1042in the
1043.Cm options
1044section of the rule.
1045.Pp
1046A backslash
1047.Pq Ql \e
1048can be used to escape the dash
1049.Pq Ql -
1050character in a service name (from a shell, the backslash must be
1051typed twice to avoid the shell itself interpreting it as an escape
1052character).
1053.Pp
1054.Dl "ipfw add count tcp from any ftp\e\e-data-ftp to any"
1055.Pp
1056Fragmented packets which have a non-zero offset (i.e., not the first
1057fragment) will never match a rule which has one or more port
1058specifications.
1059See the
1060.Cm frag
1061option for details on matching fragmented packets.
1062.El
1063.Ss RULE OPTIONS (MATCH PATTERNS)
1064Additional match patterns can be used within
1065rules.
1066Zero or more of these so-called
1067.Em options
1068can be present in a rule, optionally prefixed by the
1069.Cm not
1070operand, and possibly grouped into
1071.Em or-blocks .
1072.Pp
1073The following match patterns can be used (listed in alphabetical order):
1074.Bl -tag -width indent
1075.It Cm // this is a comment.
1076Inserts the specified text as a comment in the rule.
1077Everything following // is considered as a comment and stored in the rule.
1078You can have comment-only rules, which are listed as having a
1079.Cm count
1080action followed by the comment.
1081.It Cm bridged
1082Alias for
1083.Cm layer2 .
1084.It Cm diverted
1085Matches only packets generated by a divert socket.
1086.It Cm diverted-loopback
1087Matches only packets coming from a divert socket back into the IP stack
1088input for delivery.
1089.It Cm diverted-output
1090Matches only packets going from a divert socket back outward to the IP
1091stack output for delivery.
1092.It Cm dst-ip Ar ip-address
1093Matches IPv4 packets whose destination IP is one of the address(es)
1094specified as argument.
1095.It Bro Cm dst-ip6 | dst-ipv6 Brc Ar ip6-address
1096Matches IPv6 packets whose destination IP is one of the address(es)
1097specified as argument.
1098.It Cm dst-port Ar ports
1099Matches IP packets whose destination port is one of the port(s)
1100specified as argument.
1101.It Cm established
1102Matches TCP packets that have the RST or ACK bits set.
1103.It Cm ext6hdr Ar header
1104Matches IPv6 packets containing the extended header given by
1105.Ar header .
1106Supported headers are:
1107.Pp
1108Fragment,
1109.Pq Cm frag ,
1110Hop-to-hop options
1111.Pq Cm hopopt ,
1112Source routing
1113.Pq Cm route ,
1114Destination options
1115.Pq Cm dstopt ,
1116IPSec authentication headers
1117.Pq Cm ah ,
1118and IPSec encapsulated security payload headers
1119.Pq Cm esp .
1120.It Cm flow-id Ar labels
1121Matches IPv6 packets containing any of the flow labels given in
1122.Ar labels .
1123.Ar labels
1124is a comma seperate list of numeric flow labels.
1125.It Cm frag
1126Matches packets that are fragments and not the first
1127fragment of an IP datagram.
1128Note that these packets will not have
1129the next protocol header (e.g.\& TCP, UDP) so options that look into
1130these headers cannot match.
1131.It Cm gid Ar group
1132Matches all TCP or UDP packets sent by or received for a
1133.Ar group .
1134A
1135.Ar group
1136may be specified by name or number.
1137This option should be used only if debug.mpsafenet=0 to avoid possible
1138deadlocks due to layering violations in its implementation.
1139.It Cm jail Ar prisonID
1140Matches all TCP or UDP packets sent by or received for the
1141jail whos prison ID is
1142.Ar prisonID .
1143This option should be used only if debug.mpsafenet=0 to avoid possible
1144deadlocks due to layering violations in its implementation.
1145.It Cm icmptypes Ar types
1146Matches ICMP packets whose ICMP type is in the list
1147.Ar types .
1148The list may be specified as any combination of
1149individual types (numeric) separated by commas.
1150.Em Ranges are not allowed.
1151The supported ICMP types are:
1152.Pp
1153echo reply
1154.Pq Cm 0 ,
1155destination unreachable
1156.Pq Cm 3 ,
1157source quench
1158.Pq Cm 4 ,
1159redirect
1160.Pq Cm 5 ,
1161echo request
1162.Pq Cm 8 ,
1163router advertisement
1164.Pq Cm 9 ,
1165router solicitation
1166.Pq Cm 10 ,
1167time-to-live exceeded
1168.Pq Cm 11 ,
1169IP header bad
1170.Pq Cm 12 ,
1171timestamp request
1172.Pq Cm 13 ,
1173timestamp reply
1174.Pq Cm 14 ,
1175information request
1176.Pq Cm 15 ,
1177information reply
1178.Pq Cm 16 ,
1179address mask request
1180.Pq Cm 17
1181and address mask reply
1182.Pq Cm 18 .
1183.It Cm icmp6types Ar types
1184Matches ICMP6 packets whose ICMP6 type is in the list of
1185.Ar types .
1186The list may be specified as any combination of
1187individual types (numeric) separated by commas.
1188.Em Ranges are not allowed.
1189.It Cm in | out
1190Matches incoming or outgoing packets, respectively.
1191.Cm in
1192and
1193.Cm out
1194are mutually exclusive (in fact,
1195.Cm out
1196is implemented as
1197.Cm not in Ns No ).
1198.It Cm ipid Ar id-list
1199Matches IPv4 packets whose
1200.Cm ip_id
1201field has value included in
1202.Ar id-list ,
1203which is either a single value or a list of values or ranges
1204specified in the same way as
1205.Ar ports .
1206.It Cm iplen Ar len-list
1207Matches IP packets whose total length, including header and data, is
1208in the set
1209.Ar len-list ,
1210which is either a single value or a list of values or ranges
1211specified in the same way as
1212.Ar ports .
1213.It Cm ipoptions Ar spec
1214Matches packets whose IPv4 header contains the comma separated list of
1215options specified in
1216.Ar spec .
1217The supported IP options are:
1218.Pp
1219.Cm ssrr
1220(strict source route),
1221.Cm lsrr
1222(loose source route),
1223.Cm rr
1224(record packet route) and
1225.Cm ts
1226(timestamp).
1227The absence of a particular option may be denoted
1228with a
1229.Ql \&! .
1230.It Cm ipprecedence Ar precedence
1231Matches IPv4 packets whose precedence field is equal to
1232.Ar precedence .
1233.It Cm ipsec
1234Matches packets that have IPSEC history associated with them
1235(i.e., the packet comes encapsulated in IPSEC, the kernel
1236has IPSEC support and IPSEC_FILTERGIF option, and can correctly
1237decapsulate it).
1238.Pp
1239Note that specifying
1240.Cm ipsec
1241is different from specifying
1242.Cm proto Ar ipsec
1243as the latter will only look at the specific IP protocol field,
1244irrespective of IPSEC kernel support and the validity of the IPSEC data.
1245.Pp
1246Further note that this flag is silently ignored in kernels without
1247IPSEC support.
1248It does not affect rule processing when given and the
1249rules are handled as if with no
1250.Cm ipsec
1251flag.
1252.It Cm iptos Ar spec
1253Matches IPv4 packets whose
1254.Cm tos
1255field contains the comma separated list of
1256service types specified in
1257.Ar spec .
1258The supported IP types of service are:
1259.Pp
1260.Cm lowdelay
1261.Pq Dv IPTOS_LOWDELAY ,
1262.Cm throughput
1263.Pq Dv IPTOS_THROUGHPUT ,
1264.Cm reliability
1265.Pq Dv IPTOS_RELIABILITY ,
1266.Cm mincost
1267.Pq Dv IPTOS_MINCOST ,
1268.Cm congestion
1269.Pq Dv IPTOS_CE .
1270The absence of a particular type may be denoted
1271with a
1272.Ql \&! .
1273.It Cm ipttl Ar ttl-list
1274Matches IPv4 packets whose time to live is included in
1275.Ar ttl-list ,
1276which is either a single value or a list of values or ranges
1277specified in the same way as
1278.Ar ports .
1279.It Cm ipversion Ar ver
1280Matches IP packets whose IP version field is
1281.Ar ver .
1282.It Cm keep-state
1283Upon a match, the firewall will create a dynamic rule, whose
1284default behaviour is to match bidirectional traffic between
1285source and destination IP/port using the same protocol.
1286The rule has a limited lifetime (controlled by a set of
1287.Xr sysctl 8
1288variables), and the lifetime is refreshed every time a matching
1289packet is found.
1290.It Cm layer2
1291Matches only layer2 packets, i.e., those passed to
1292.Nm
1293from ether_demux() and ether_output_frame().
1294.It Cm limit Bro Cm src-addr | src-port | dst-addr | dst-port Brc Ar N
1295The firewall will only allow
1296.Ar N
1297connections with the same
1298set of parameters as specified in the rule.
1299One or more
1300of source and destination addresses and ports can be
1301specified.
1302Currently,
1303only IPv4 flows are supported.
1304.It Cm { MAC | mac } Ar dst-mac src-mac
1305Match packets with a given
1306.Ar dst-mac
1307and
1308.Ar src-mac
1309addresses, specified as the
1310.Cm any
1311keyword (matching any MAC address), or six groups of hex digits
1312separated by colons,
1313and optionally followed by a mask indicating the significant bits.
1314The mask may be specified using either of the following methods:
1315.Bl -enum -width indent
1316.It
1317A slash
1318.Pq /
1319followed by the number of significant bits.
1320For example, an address with 33 significant bits could be specified as:
1321.Pp
1322.Dl "MAC 10:20:30:40:50:60/33 any"
1323.Pp
1324.It
1325An ampersand
1326.Pq &
1327followed by a bitmask specified as six groups of hex digits separated
1328by colons.
1329For example, an address in which the last 16 bits are significant could
1330be specified as:
1331.Pp
1332.Dl "MAC 10:20:30:40:50:60&00:00:00:00:ff:ff any"
1333.Pp
1334Note that the ampersand character has a special meaning in many shells
1335and should generally be escaped.
1336.Pp
1337.El
1338Note that the order of MAC addresses (destination first,
1339source second) is
1340the same as on the wire, but the opposite of the one used for
1341IP addresses.
1342.It Cm mac-type Ar mac-type
1343Matches packets whose Ethernet Type field
1344corresponds to one of those specified as argument.
1345.Ar mac-type
1346is specified in the same way as
1347.Cm port numbers
1348(i.e., one or more comma-separated single values or ranges).
1349You can use symbolic names for known values such as
1350.Em vlan , ipv4, ipv6 .
1351Values can be entered as decimal or hexadecimal (if prefixed by 0x),
1352and they are always printed as hexadecimal (unless the
1353.Cm -N
1354option is used, in which case symbolic resolution will be attempted).
1355.It Cm proto Ar protocol
1356Matches packets with the corresponding IP protocol.
1357.It Cm recv | xmit | via Brq Ar ifX | Ar if Ns Cm * | Ar ipno | Ar any
1358Matches packets received, transmitted or going through,
1359respectively, the interface specified by exact name
1360.Ns No ( Ar ifX Ns No ),
1361by device name
1362.Ns No ( Ar if Ns Ar * Ns No ),
1363by IP address, or through some interface.
1364.Pp
1365The
1366.Cm via
1367keyword causes the interface to always be checked.
1368If
1369.Cm recv
1370or
1371.Cm xmit
1372is used instead of
1373.Cm via ,
1374then only the receive or transmit interface (respectively)
1375is checked.
1376By specifying both, it is possible to match packets based on
1377both receive and transmit interface, e.g.:
1378.Pp
1379.Dl "ipfw add deny ip from any to any out recv ed0 xmit ed1"
1380.Pp
1381The
1382.Cm recv
1383interface can be tested on either incoming or outgoing packets,
1384while the
1385.Cm xmit
1386interface can only be tested on outgoing packets.
1387So
1388.Cm out
1389is required (and
1390.Cm in
1391is invalid) whenever
1392.Cm xmit
1393is used.
1394.Pp
1395A packet may not have a receive or transmit interface: packets
1396originating from the local host have no receive interface,
1397while packets destined for the local host have no transmit
1398interface.
1399.It Cm setup
1400Matches TCP packets that have the SYN bit set but no ACK bit.
1401This is the short form of
1402.Dq Li tcpflags\ syn,!ack .
1403.It Cm src-ip Ar ip-address
1404Matches IPv4 packets whose source IP is one of the address(es)
1405specified as an argument.
1406.It Cm src-ip6 Ar ip6-address
1407Matches IPv6 packets whose source IP is one of the address(es)
1408specified as an argument.
1409.It Cm src-port Ar ports
1410Matches IP packets whose source port is one of the port(s)
1411specified as argument.
1412.It Cm tagged Ar tag-list
1413Matches packets whose tags are included in
1414.Ar tag-list ,
1415which is either a single value or a list of values or ranges
1416specified in the same way as
1417.Ar ports .
1418Tags can be applied to the packet using
1419.Cm tag
1420rule action parameter (see it's description for details on tags).
1421.It Cm tcpack Ar ack
1422TCP packets only.
1423Match if the TCP header acknowledgment number field is set to
1424.Ar ack .
1425.It Cm tcpdatalen Ar tcpdatalen-list
1426Matches TCP packets whose length of TCP data is
1427.Ar tcpdatalen-list ,
1428which is either a single value or a list of values or ranges
1429specified in the same way as
1430.Ar ports .
1431.It Cm tcpflags Ar spec
1432TCP packets only.
1433Match if the TCP header contains the comma separated list of
1434flags specified in
1435.Ar spec .
1436The supported TCP flags are:
1437.Pp
1438.Cm fin ,
1439.Cm syn ,
1440.Cm rst ,
1441.Cm psh ,
1442.Cm ack
1443and
1444.Cm urg .
1445The absence of a particular flag may be denoted
1446with a
1447.Ql \&! .
1448A rule which contains a
1449.Cm tcpflags
1450specification can never match a fragmented packet which has
1451a non-zero offset.
1452See the
1453.Cm frag
1454option for details on matching fragmented packets.
1455.It Cm tcpseq Ar seq
1456TCP packets only.
1457Match if the TCP header sequence number field is set to
1458.Ar seq .
1459.It Cm tcpwin Ar win
1460TCP packets only.
1461Match if the TCP header window field is set to
1462.Ar win .
1463.It Cm tcpoptions Ar spec
1464TCP packets only.
1465Match if the TCP header contains the comma separated list of
1466options specified in
1467.Ar spec .
1468The supported TCP options are:
1469.Pp
1470.Cm mss
1471(maximum segment size),
1472.Cm window
1473(tcp window advertisement),
1474.Cm sack
1475(selective ack),
1476.Cm ts
1477(rfc1323 timestamp) and
1478.Cm cc
1479(rfc1644 t/tcp connection count).
1480The absence of a particular option may be denoted
1481with a
1482.Ql \&! .
1483.It Cm uid Ar user
1484Match all TCP or UDP packets sent by or received for a
1485.Ar user .
1486A
1487.Ar user
1488may be matched by name or identification number.
1489This option should be used only if debug.mpsafenet=0 to avoid possible
1490deadlocks due to layering violations in its implementation.
1491.It Cm verrevpath
1492For incoming packets,
1493a routing table lookup is done on the packet's source address.
1494If the interface on which the packet entered the system matches the
1495outgoing interface for the route,
1496the packet matches.
1497If the interfaces do not match up,
1498the packet does not match.
1499All outgoing packets or packets with no incoming interface match.
1500.Pp
1501The name and functionality of the option is intentionally similar to
1502the Cisco IOS command:
1503.Pp
1504.Dl ip verify unicast reverse-path
1505.Pp
1506This option can be used to make anti-spoofing rules to reject all
1507packets with source addresses not from this interface.
1508See also the option
1509.Cm antispoof .
1510.It Cm versrcreach
1511For incoming packets,
1512a routing table lookup is done on the packet's source address.
1513If a route to the source address exists, but not the default route
1514or a blackhole/reject route, the packet matches.
1515Otherwise, the packet does not match.
1516All outgoing packets match.
1517.Pp
1518The name and functionality of the option is intentionally similar to
1519the Cisco IOS command:
1520.Pp
1521.Dl ip verify unicast source reachable-via any
1522.Pp
1523This option can be used to make anti-spoofing rules to reject all
1524packets whose source address is unreachable.
1525.It Cm antispoof
1526For incoming packets, the packet's source address is checked if it
1527belongs to a directly connected network.
1528If the network is directly connected, then the interface the packet
1529came on in is compared to the interface the network is connected to.
1530When incoming interface and directly connected interface are not the
1531same, the packet does not match.
1532Otherwise, the packet does match.
1533All outgoing packets match.
1534.Pp
1535This option can be used to make anti-spoofing rules to reject all
1536packets that pretend to be from a directly connected network but do
1537not come in through that interface.
1538This option is similar to but more restricted than
1539.Cm verrevpath
1540because it engages only on packets with source addresses of directly
1541connected networks instead of all source addresses.
1542.El
1543.Sh LOOKUP TABLES
1544Lookup tables are useful to handle large sparse address sets,
1545typically from a hundred to several thousands of entries.
1546There may be up to 128 different lookup tables, numbered 0 to 127.
1547.Pp
1548Each entry is represented by an
1549.Ar addr Ns Op / Ns Ar masklen
1550and will match all addresses with base
1551.Ar addr
1552(specified as an IP address or a hostname)
1553and mask width of
1554.Ar masklen
1555bits.
1556If
1557.Ar masklen
1558is not specified, it defaults to 32.
1559When looking up an IP address in a table, the most specific
1560entry will match.
1561Associated with each entry is a 32-bit unsigned
1562.Ar value ,
1563which can optionally be checked by a rule matching code.
1564When adding an entry, if
1565.Ar value
1566is not specified, it defaults to 0.
1567.Pp
1568An entry can be added to a table
1569.Pq Cm add ,
1570removed from a table
1571.Pq Cm delete ,
1572a table can be examined
1573.Pq Cm list
1574or flushed
1575.Pq Cm flush .
1576.Pp
1577Internally, each table is stored in a Radix tree, the same way as
1578the routing table (see
1579.Xr route 4 ) .
1580.Pp
1581Lookup tables currently support IPv4 addresses only.
1582.Pp
1583The
1584.Cm tablearg
1585feature provides the ability to use a value, looked up in the table, as
1586the argument for a rule action, action parameter or rule option.
1587This can significantly reduce number of rules in some configurations.
1588The
1589.Cm tablearg
1590argument can be used with the following actions:
1591.Cm pipe , queue, divert, tee, netgraph, ngtee, fwd
1592action parameters:
1593.Cm tag, untag,
1594rule options:
1595.Cm limit, tagged.
1596.Pp
1597When used with
1598.Cm fwd
1599it is possible to supply table entries with values
1600that are in the form of IP addresses or hostnames.
1601See the
1602.Sx EXAMPLES
1603Section for example usage of tables and the tablearg keyword.
1604.Sh SETS OF RULES
1605Each rule belongs to one of 32 different
1606.Em sets
1607, numbered 0 to 31.
1608Set 31 is reserved for the default rule.
1609.Pp
1610By default, rules are put in set 0, unless you use the
1611.Cm set N
1612attribute when entering a new rule.
1613Sets can be individually and atomically enabled or disabled,
1614so this mechanism permits an easy way to store multiple configurations
1615of the firewall and quickly (and atomically) switch between them.
1616The command to enable/disable sets is
1617.Bd -ragged -offset indent
1618.Nm
1619.Cm set Oo Cm disable Ar number ... Oc Op Cm enable Ar number ...
1620.Ed
1621.Pp
1622where multiple
1623.Cm enable
1624or
1625.Cm disable
1626sections can be specified.
1627Command execution is atomic on all the sets specified in the command.
1628By default, all sets are enabled.
1629.Pp
1630When you disable a set, its rules behave as if they do not exist
1631in the firewall configuration, with only one exception:
1632.Bd -ragged -offset indent
1633dynamic rules created from a rule before it had been disabled
1634will still be active until they expire.
1635In order to delete
1636dynamic rules you have to explicitly delete the parent rule
1637which generated them.
1638.Ed
1639.Pp
1640The set number of rules can be changed with the command
1641.Bd -ragged -offset indent
1642.Nm
1643.Cm set move
1644.Brq Cm rule Ar rule-number | old-set
1645.Cm to Ar new-set
1646.Ed
1647.Pp
1648Also, you can atomically swap two rulesets with the command
1649.Bd -ragged -offset indent
1650.Nm
1651.Cm set swap Ar first-set second-set
1652.Ed
1653.Pp
1654See the
1655.Sx EXAMPLES
1656Section on some possible uses of sets of rules.
1657.Sh STATEFUL FIREWALL
1658Stateful operation is a way for the firewall to dynamically
1659create rules for specific flows when packets that
1660match a given pattern are detected.
1661Support for stateful
1662operation comes through the
1663.Cm check-state , keep-state
1664and
1665.Cm limit
1666options of
1667.Nm rules .
1668.Pp
1669Dynamic rules are created when a packet matches a
1670.Cm keep-state
1671or
1672.Cm limit
1673rule, causing the creation of a
1674.Em dynamic
1675rule which will match all and only packets with
1676a given
1677.Em protocol
1678between a
1679.Em src-ip/src-port dst-ip/dst-port
1680pair of addresses
1681.Em ( src
1682and
1683.Em dst
1684are used here only to denote the initial match addresses, but they
1685are completely equivalent afterwards).
1686Dynamic rules will be checked at the first
1687.Cm check-state, keep-state
1688or
1689.Cm limit
1690occurrence, and the action performed upon a match will be the same
1691as in the parent rule.
1692.Pp
1693Note that no additional attributes other than protocol and IP addresses
1694and ports are checked on dynamic rules.
1695.Pp
1696The typical use of dynamic rules is to keep a closed firewall configuration,
1697but let the first TCP SYN packet from the inside network install a
1698dynamic rule for the flow so that packets belonging to that session
1699will be allowed through the firewall:
1700.Pp
1701.Dl "ipfw add check-state"
1702.Dl "ipfw add allow tcp from my-subnet to any setup keep-state"
1703.Dl "ipfw add deny tcp from any to any"
1704.Pp
1705A similar approach can be used for UDP, where an UDP packet coming
1706from the inside will install a dynamic rule to let the response through
1707the firewall:
1708.Pp
1709.Dl "ipfw add check-state"
1710.Dl "ipfw add allow udp from my-subnet to any keep-state"
1711.Dl "ipfw add deny udp from any to any"
1712.Pp
1713Dynamic rules expire after some time, which depends on the status
1714of the flow and the setting of some
1715.Cm sysctl
1716variables.
1717See Section
1718.Sx SYSCTL VARIABLES
1719for more details.
1720For TCP sessions, dynamic rules can be instructed to periodically
1721send keepalive packets to refresh the state of the rule when it is
1722about to expire.
1723.Pp
1724See Section
1725.Sx EXAMPLES
1726for more examples on how to use dynamic rules.
1727.Sh TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
1728.Nm
1729is also the user interface for the
1730.Xr dummynet 4
1731traffic shaper.
1732.Pp
1733.Nm dummynet
1734operates by first using the firewall to classify packets and divide them into
1735.Em flows ,
1736using any match pattern that can be used in
1737.Nm
1738rules.
1739Depending on local policies, a flow can contain packets for a single
1740TCP connection, or from/to a given host, or entire subnet, or a
1741protocol type, etc.
1742.Pp
1743Packets belonging to the same flow are then passed to either of two
1744different objects, which implement the traffic regulation:
1745.Bl -hang -offset XXXX
1746.It Em pipe
1747A pipe emulates a link with given bandwidth, propagation delay,
1748queue size and packet loss rate.
1749Packets are queued in front of the pipe as they come out from the classifier,
1750and then transferred to the pipe according to the pipe's parameters.
1751.Pp
1752.It Em queue
1753A queue
1754is an abstraction used to implement the WF2Q+
1755(Worst-case Fair Weighted Fair Queueing) policy, which is
1756an efficient variant of the WFQ policy.
1757.br
1758The queue associates a
1759.Em weight
1760and a reference pipe to each flow, and then all backlogged (i.e.,
1761with packets queued) flows linked to the same pipe share the pipe's
1762bandwidth proportionally to their weights.
1763Note that weights are not priorities; a flow with a lower weight
1764is still guaranteed to get its fraction of the bandwidth even if a
1765flow with a higher weight is permanently backlogged.
1766.Pp
1767.El
1768In practice,
1769.Em pipes
1770can be used to set hard limits to the bandwidth that a flow can use, whereas
1771.Em queues
1772can be used to determine how different flow share the available bandwidth.
1773.Pp
1774The
1775.Em pipe
1776and
1777.Em queue
1778configuration commands are the following:
1779.Bd -ragged -offset indent
1780.Cm pipe Ar number Cm config Ar pipe-configuration
1781.Pp
1782.Cm queue Ar number Cm config Ar queue-configuration
1783.Ed
1784.Pp
1785The following parameters can be configured for a pipe:
1786.Pp
1787.Bl -tag -width indent -compact
1788.It Cm bw Ar bandwidth | device
1789Bandwidth, measured in
1790.Sm off
1791.Op Cm K | M
1792.Brq Cm bit/s | Byte/s .
1793.Sm on
1794.Pp
1795A value of 0 (default) means unlimited bandwidth.
1796The unit must immediately follow the number, as in
1797.Pp
1798.Dl "ipfw pipe 1 config bw 300Kbit/s"
1799.Pp
1800If a device name is specified instead of a numeric value, as in
1801.Pp
1802.Dl "ipfw pipe 1 config bw tun0"
1803.Pp
1804then the transmit clock is supplied by the specified device.
1805At the moment only the
1806.Xr tun 4
1807device supports this
1808functionality, for use in conjunction with
1809.Xr ppp 8 .
1810.Pp
1811.It Cm delay Ar ms-delay
1812Propagation delay, measured in milliseconds.
1813The value is rounded to the next multiple of the clock tick
1814(typically 10ms, but it is a good practice to run kernels
1815with
1816.Dq "options HZ=1000"
1817to reduce
1818the granularity to 1ms or less).
1819Default value is 0, meaning no delay.
1820.El
1821.Pp
1822The following parameters can be configured for a queue:
1823.Pp
1824.Bl -tag -width indent -compact
1825.It Cm pipe Ar pipe_nr
1826Connects a queue to the specified pipe.
1827Multiple queues (with the same or different weights) can be connected to
1828the same pipe, which specifies the aggregate rate for the set of queues.
1829.Pp
1830.It Cm weight Ar weight
1831Specifies the weight to be used for flows matching this queue.
1832The weight must be in the range 1..100, and defaults to 1.
1833.El
1834.Pp
1835Finally, the following parameters can be configured for both
1836pipes and queues:
1837.Pp
1838.Bl -tag -width XXXX -compact
1839.Pp
1840.It Cm buckets Ar hash-table-size
1841Specifies the size of the hash table used for storing the
1842various queues.
1843Default value is 64 controlled by the
1844.Xr sysctl 8
1845variable
1846.Em net.inet.ip.dummynet.hash_size ,
1847allowed range is 16 to 65536.
1848.Pp
1849.It Cm mask Ar mask-specifier
1850Packets sent to a given pipe or queue by an
1851.Nm
1852rule can be further classified into multiple flows, each of which is then
1853sent to a different
1854.Em dynamic
1855pipe or queue.
1856A flow identifier is constructed by masking the IP addresses,
1857ports and protocol types as specified with the
1858.Cm mask
1859options in the configuration of the pipe or queue.
1860For each different flow identifier, a new pipe or queue is created
1861with the same parameters as the original object, and matching packets
1862are sent to it.
1863.Pp
1864Thus, when
1865.Em dynamic pipes
1866are used, each flow will get the same bandwidth as defined by the pipe,
1867whereas when
1868.Em dynamic queues
1869are used, each flow will share the parent's pipe bandwidth evenly
1870with other flows generated by the same queue (note that other queues
1871with different weights might be connected to the same pipe).
1872.br
1873Available mask specifiers are a combination of one or more of the following:
1874.Pp
1875.Cm dst-ip Ar mask ,
1876.Cm dst-ip6 Ar mask ,
1877.Cm src-ip Ar mask ,
1878.Cm src-ip6 Ar mask ,
1879.Cm dst-port Ar mask ,
1880.Cm src-port Ar mask ,
1881.Cm flow-id Ar mask ,
1882.Cm proto Ar mask
1883or
1884.Cm all ,
1885.Pp
1886where the latter means all bits in all fields are significant.
1887.Pp
1888.It Cm noerror
1889When a packet is dropped by a dummynet queue or pipe, the error
1890is normally reported to the caller routine in the kernel, in the
1891same way as it happens when a device queue fills up.
1892Setting this
1893option reports the packet as successfully delivered, which can be
1894needed for some experimental setups where you want to simulate
1895loss or congestion at a remote router.
1896.Pp
1897.It Cm plr Ar packet-loss-rate
1898Packet loss rate.
1899Argument
1900.Ar packet-loss-rate
1901is a floating-point number between 0 and 1, with 0 meaning no
1902loss, 1 meaning 100% loss.
1903The loss rate is internally represented on 31 bits.
1904.Pp
1905.It Cm queue Brq Ar slots | size Ns Cm Kbytes
1906Queue size, in
1907.Ar slots
1908or
1909.Cm KBytes .
1910Default value is 50 slots, which
1911is the typical queue size for Ethernet devices.
1912Note that for slow speed links you should keep the queue
1913size short or your traffic might be affected by a significant
1914queueing delay.
1915E.g., 50 max-sized ethernet packets (1500 bytes) mean 600Kbit
1916or 20s of queue on a 30Kbit/s pipe.
1917Even worse effects can result if you get packets from an
1918interface with a much larger MTU, e.g.\& the loopback interface
1919with its 16KB packets.
1920.Pp
1921.It Cm red | gred Ar w_q Ns / Ns Ar min_th Ns / Ns Ar max_th Ns / Ns Ar max_p
1922Make use of the RED (Random Early Detection) queue management algorithm.
1923.Ar w_q
1924and
1925.Ar max_p
1926are floating
1927point numbers between 0 and 1 (0 not included), while
1928.Ar min_th
1929and
1930.Ar max_th
1931are integer numbers specifying thresholds for queue management
1932(thresholds are computed in bytes if the queue has been defined
1933in bytes, in slots otherwise).
1934The
1935.Xr dummynet 4
1936also supports the gentle RED variant (gred).
1937Three
1938.Xr sysctl 8
1939variables can be used to control the RED behaviour:
1940.Bl -tag -width indent
1941.It Em net.inet.ip.dummynet.red_lookup_depth
1942specifies the accuracy in computing the average queue
1943when the link is idle (defaults to 256, must be greater than zero)
1944.It Em net.inet.ip.dummynet.red_avg_pkt_size
1945specifies the expected average packet size (defaults to 512, must be
1946greater than zero)
1947.It Em net.inet.ip.dummynet.red_max_pkt_size
1948specifies the expected maximum packet size, only used when queue
1949thresholds are in bytes (defaults to 1500, must be greater than zero).
1950.El
1951.El
1952.Pp
1953When used with IPv6 data, dummynet currently has several limitations.
1954First, debug.mpsafenet=0 must be set.
1955Second, the information necessicary to route link-local packets to an
1956interface is not avalable after processing by dummynet so those packets
1957are dropped in the output path.
1958Care should be taken to insure that link-local packets are not passed to
1959dummynet.
1960.Sh CHECKLIST
1961Here are some important points to consider when designing your
1962rules:
1963.Bl -bullet
1964.It
1965Remember that you filter both packets going
1966.Cm in
1967and
1968.Cm out .
1969Most connections need packets going in both directions.
1970.It
1971Remember to test very carefully.
1972It is a good idea to be near the console when doing this.
1973If you cannot be near the console,
1974use an auto-recovery script such as the one in
1975.Pa /usr/share/examples/ipfw/change_rules.sh .
1976.It
1977Do not forget the loopback interface.
1978.El
1979.Sh FINE POINTS
1980.Bl -bullet
1981.It
1982There are circumstances where fragmented datagrams are unconditionally
1983dropped.
1984TCP packets are dropped if they do not contain at least 20 bytes of
1985TCP header, UDP packets are dropped if they do not contain a full 8
1986byte UDP header, and ICMP packets are dropped if they do not contain
19874 bytes of ICMP header, enough to specify the ICMP type, code, and
1988checksum.
1989These packets are simply logged as
1990.Dq pullup failed
1991since there may not be enough good data in the packet to produce a
1992meaningful log entry.
1993.It
1994Another type of packet is unconditionally dropped, a TCP packet with a
1995fragment offset of one.
1996This is a valid packet, but it only has one use, to try
1997to circumvent firewalls.
1998When logging is enabled, these packets are
1999reported as being dropped by rule -1.
2000.It
2001If you are logged in over a network, loading the
2002.Xr kld 4
2003version of
2004.Nm
2005is probably not as straightforward as you would think.
2006I recommend the following command line:
2007.Bd -literal -offset indent
2008kldload ipfw && \e
2009ipfw add 32000 allow ip from any to any
2010.Ed
2011.Pp
2012Along the same lines, doing an
2013.Bd -literal -offset indent
2014ipfw flush
2015.Ed
2016.Pp
2017in similar surroundings is also a bad idea.
2018.It
2019The
2020.Nm
2021filter list may not be modified if the system security level
2022is set to 3 or higher
2023(see
2024.Xr init 8
2025for information on system security levels).
2026.El
2027.Sh PACKET DIVERSION
2028A
2029.Xr divert 4
2030socket bound to the specified port will receive all packets
2031diverted to that port.
2032If no socket is bound to the destination port, or if the divert module is
2033not loaded, or if the kernel was not compiled with divert socket support,
2034the packets are dropped.
2035.Sh SYSCTL VARIABLES
2036A set of
2037.Xr sysctl 8
2038variables controls the behaviour of the firewall and
2039associated modules
2040.Pq Nm dummynet , bridge .
2041These are shown below together with their default value
2042(but always check with the
2043.Xr sysctl 8
2044command what value is actually in use) and meaning:
2045.Bl -tag -width indent
2046.It Em net.inet.ip.dummynet.expire : No 1
2047Lazily delete dynamic pipes/queue once they have no pending traffic.
2048You can disable this by setting the variable to 0, in which case
2049the pipes/queues will only be deleted when the threshold is reached.
2050.It Em net.inet.ip.dummynet.hash_size : No 64
2051Default size of the hash table used for dynamic pipes/queues.
2052This value is used when no
2053.Cm buckets
2054option is specified when configuring a pipe/queue.
2055.It Em net.inet.ip.dummynet.max_chain_len : No 16
2056Target value for the maximum number of pipes/queues in a hash bucket.
2057The product
2058.Cm max_chain_len*hash_size
2059is used to determine the threshold over which empty pipes/queues
2060will be expired even when
2061.Cm net.inet.ip.dummynet.expire=0 .
2062.It Em net.inet.ip.dummynet.red_lookup_depth : No 256
2063.It Em net.inet.ip.dummynet.red_avg_pkt_size : No 512
2064.It Em net.inet.ip.dummynet.red_max_pkt_size : No 1500
2065Parameters used in the computations of the drop probability
2066for the RED algorithm.
2067.It Em net.inet.ip.fw.autoinc_step : No 100
2068Delta between rule numbers when auto-generating them.
2069The value must be in the range 1..1000.
2070.It Em net.inet.ip.fw.curr_dyn_buckets : Em net.inet.ip.fw.dyn_buckets
2071The current number of buckets in the hash table for dynamic rules
2072(readonly).
2073.It Em net.inet.ip.fw.debug : No 1
2074Controls debugging messages produced by
2075.Nm .
2076.It Em net.inet.ip.fw.dyn_buckets : No 256
2077The number of buckets in the hash table for dynamic rules.
2078Must be a power of 2, up to 65536.
2079It only takes effect when all dynamic rules have expired, so you
2080are advised to use a
2081.Cm flush
2082command to make sure that the hash table is resized.
2083.It Em net.inet.ip.fw.dyn_count : No 3
2084Current number of dynamic rules
2085(read-only).
2086.It Em net.inet.ip.fw.dyn_keepalive : No 1
2087Enables generation of keepalive packets for
2088.Cm keep-state
2089rules on TCP sessions.
2090A keepalive is generated to both
2091sides of the connection every 5 seconds for the last 20
2092seconds of the lifetime of the rule.
2093.It Em net.inet.ip.fw.dyn_max : No 8192
2094Maximum number of dynamic rules.
2095When you hit this limit, no more dynamic rules can be
2096installed until old ones expire.
2097.It Em net.inet.ip.fw.dyn_ack_lifetime : No 300
2098.It Em net.inet.ip.fw.dyn_syn_lifetime : No 20
2099.It Em net.inet.ip.fw.dyn_fin_lifetime : No 1
2100.It Em net.inet.ip.fw.dyn_rst_lifetime : No 1
2101.It Em net.inet.ip.fw.dyn_udp_lifetime : No 5
2102.It Em net.inet.ip.fw.dyn_short_lifetime : No 30
2103These variables control the lifetime, in seconds, of dynamic
2104rules.
2105Upon the initial SYN exchange the lifetime is kept short,
2106then increased after both SYN have been seen, then decreased
2107again during the final FIN exchange or when a RST is received.
2108Both
2109.Em dyn_fin_lifetime
2110and
2111.Em dyn_rst_lifetime
2112must be strictly lower than 5 seconds, the period of
2113repetition of keepalives.
2114The firewall enforces that.
2115.It Em net.inet.ip.fw.enable : No 1
2116Enables the firewall.
2117Setting this variable to 0 lets you run your machine without
2118firewall even if compiled in.
2119.It Em net.inet6.ip6.fw.enable : No 1
2120provides the same functionality as above for the IPv6 case.
2121.It Em net.inet.ip.fw.one_pass : No 1
2122When set, the packet exiting from the
2123.Xr dummynet 4
2124pipe or from
2125.Xr ng_ipfw 4
2126node is not passed though the firewall again.
2127Otherwise, after an action, the packet is
2128reinjected into the firewall at the next rule.
2129.It Em net.inet.ip.fw.verbose : No 1
2130Enables verbose messages.
2131.It Em net.inet.ip.fw.verbose_limit : No 0
2132Limits the number of messages produced by a verbose firewall.
2133.It Em net.inet6.ip6.fw.deny_unknown_exthdrs : No 1
2134If enabled packets with unknown IPv6 Extension Headers will be denied.
2135.It Em net.link.ether.ipfw : No 0
2136Controls whether layer-2 packets are passed to
2137.Nm .
2138Default is no.
2139.It Em net.link.bridge.ipfw : No 0
2140Controls whether bridged packets are passed to
2141.Nm .
2142Default is no.
2143.El
2144.Pp
2145.Sh EXAMPLES
2146There are far too many possible uses of
2147.Nm
2148so this Section will only give a small set of examples.
2149.Pp
2150.Ss BASIC PACKET FILTERING
2151This command adds an entry which denies all tcp packets from
2152.Em cracker.evil.org
2153to the telnet port of
2154.Em wolf.tambov.su
2155from being forwarded by the host:
2156.Pp
2157.Dl "ipfw add deny tcp from cracker.evil.org to wolf.tambov.su telnet"
2158.Pp
2159This one disallows any connection from the entire cracker's
2160network to my host:
2161.Pp
2162.Dl "ipfw add deny ip from 123.45.67.0/24 to my.host.org"
2163.Pp
2164A first and efficient way to limit access (not using dynamic rules)
2165is the use of the following rules:
2166.Pp
2167.Dl "ipfw add allow tcp from any to any established"
2168.Dl "ipfw add allow tcp from net1 portlist1 to net2 portlist2 setup"
2169.Dl "ipfw add allow tcp from net3 portlist3 to net3 portlist3 setup"
2170.Dl "..."
2171.Dl "ipfw add deny tcp from any to any"
2172.Pp
2173The first rule will be a quick match for normal TCP packets,
2174but it will not match the initial SYN packet, which will be
2175matched by the
2176.Cm setup
2177rules only for selected source/destination pairs.
2178All other SYN packets will be rejected by the final
2179.Cm deny
2180rule.
2181.Pp
2182If you administer one or more subnets, you can take advantage
2183of the address sets and or-blocks and write extremely
2184compact rulesets which selectively enable services to blocks
2185of clients, as below:
2186.Pp
2187.Dl "goodguys=\*q{ 10.1.2.0/24{20,35,66,18} or 10.2.3.0/28{6,3,11} }\*q"
2188.Dl "badguys=\*q10.1.2.0/24{8,38,60}\*q"
2189.Dl ""
2190.Dl "ipfw add allow ip from ${goodguys} to any"
2191.Dl "ipfw add deny ip from ${badguys} to any"
2192.Dl "... normal policies ..."
2193.Pp
2194The
2195.Cm verrevpath
2196option could be used to do automated anti-spoofing by adding the
2197following to the top of a ruleset:
2198.Pp
2199.Dl "ipfw add deny ip from any to any not verrevpath in"
2200.Pp
2201This rule drops all incoming packets that appear to be coming to the
2202system on the wrong interface.
2203For example, a packet with a source
2204address belonging to a host on a protected internal network would be
2205dropped if it tried to enter the system from an external interface.
2206.Pp
2207The
2208.Cm antispoof
2209option could be used to do similar but more restricted anti-spoofing
2210by adding the following to the top of a ruleset:
2211.Pp
2212.Dl "ipfw add deny ip from any to any not antispoof in"
2213.Pp
2214This rule drops all incoming packets that appear to be coming from another
2215directly connected system but on the wrong interface.
2216For example, a packet with a source address of
2217.Li 192.168.0.0/24
2218, configured on
2219.Li fxp0
2220, but coming in on
2221.Li fxp1
2222would be dropped.
2223.Ss DYNAMIC RULES
2224In order to protect a site from flood attacks involving fake
2225TCP packets, it is safer to use dynamic rules:
2226.Pp
2227.Dl "ipfw add check-state"
2228.Dl "ipfw add deny tcp from any to any established"
2229.Dl "ipfw add allow tcp from my-net to any setup keep-state"
2230.Pp
2231This will let the firewall install dynamic rules only for
2232those connection which start with a regular SYN packet coming
2233from the inside of our network.
2234Dynamic rules are checked when encountering the first
2235.Cm check-state
2236or
2237.Cm keep-state
2238rule.
2239A
2240.Cm check-state
2241rule should usually be placed near the beginning of the
2242ruleset to minimize the amount of work scanning the ruleset.
2243Your mileage may vary.
2244.Pp
2245To limit the number of connections a user can open
2246you can use the following type of rules:
2247.Pp
2248.Dl "ipfw add allow tcp from my-net/24 to any setup limit src-addr 10"
2249.Dl "ipfw add allow tcp from any to me setup limit src-addr 4"
2250.Pp
2251The former (assuming it runs on a gateway) will allow each host
2252on a /24 network to open at most 10 TCP connections.
2253The latter can be placed on a server to make sure that a single
2254client does not use more than 4 simultaneous connections.
2255.Pp
2256.Em BEWARE :
2257stateful rules can be subject to denial-of-service attacks
2258by a SYN-flood which opens a huge number of dynamic rules.
2259The effects of such attacks can be partially limited by
2260acting on a set of
2261.Xr sysctl 8
2262variables which control the operation of the firewall.
2263.Pp
2264Here is a good usage of the
2265.Cm list
2266command to see accounting records and timestamp information:
2267.Pp
2268.Dl ipfw -at list
2269.Pp
2270or in short form without timestamps:
2271.Pp
2272.Dl ipfw -a list
2273.Pp
2274which is equivalent to:
2275.Pp
2276.Dl ipfw show
2277.Pp
2278Next rule diverts all incoming packets from 192.168.2.0/24
2279to divert port 5000:
2280.Pp
2281.Dl ipfw divert 5000 ip from 192.168.2.0/24 to any in
2282.Pp
2283.Ss TRAFFIC SHAPING
2284The following rules show some of the applications of
2285.Nm
2286and
2287.Xr dummynet 4
2288for simulations and the like.
2289.Pp
2290This rule drops random incoming packets with a probability
2291of 5%:
2292.Pp
2293.Dl "ipfw add prob 0.05 deny ip from any to any in"
2294.Pp
2295A similar effect can be achieved making use of dummynet pipes:
2296.Pp
2297.Dl "ipfw add pipe 10 ip from any to any"
2298.Dl "ipfw pipe 10 config plr 0.05"
2299.Pp
2300We can use pipes to artificially limit bandwidth, e.g.\& on a
2301machine acting as a router, if we want to limit traffic from
2302local clients on 192.168.2.0/24 we do:
2303.Pp
2304.Dl "ipfw add pipe 1 ip from 192.168.2.0/24 to any out"
2305.Dl "ipfw pipe 1 config bw 300Kbit/s queue 50KBytes"
2306.Pp
2307note that we use the
2308.Cm out
2309modifier so that the rule is not used twice.
2310Remember in fact that
2311.Nm
2312rules are checked both on incoming and outgoing packets.
2313.Pp
2314Should we want to simulate a bidirectional link with bandwidth
2315limitations, the correct way is the following:
2316.Pp
2317.Dl "ipfw add pipe 1 ip from any to any out"
2318.Dl "ipfw add pipe 2 ip from any to any in"
2319.Dl "ipfw pipe 1 config bw 64Kbit/s queue 10Kbytes"
2320.Dl "ipfw pipe 2 config bw 64Kbit/s queue 10Kbytes"
2321.Pp
2322The above can be very useful, e.g.\& if you want to see how
2323your fancy Web page will look for a residential user who
2324is connected only through a slow link.
2325You should not use only one pipe for both directions, unless
2326you want to simulate a half-duplex medium (e.g.\& AppleTalk,
2327Ethernet, IRDA).
2328It is not necessary that both pipes have the same configuration,
2329so we can also simulate asymmetric links.
2330.Pp
2331Should we want to verify network performance with the RED queue
2332management algorithm:
2333.Pp
2334.Dl "ipfw add pipe 1 ip from any to any"
2335.Dl "ipfw pipe 1 config bw 500Kbit/s queue 100 red 0.002/30/80/0.1"
2336.Pp
2337Another typical application of the traffic shaper is to
2338introduce some delay in the communication.
2339This can significantly affect applications which do a lot of Remote
2340Procedure Calls, and where the round-trip-time of the
2341connection often becomes a limiting factor much more than
2342bandwidth:
2343.Pp
2344.Dl "ipfw add pipe 1 ip from any to any out"
2345.Dl "ipfw add pipe 2 ip from any to any in"
2346.Dl "ipfw pipe 1 config delay 250ms bw 1Mbit/s"
2347.Dl "ipfw pipe 2 config delay 250ms bw 1Mbit/s"
2348.Pp
2349Per-flow queueing can be useful for a variety of purposes.
2350A very simple one is counting traffic:
2351.Pp
2352.Dl "ipfw add pipe 1 tcp from any to any"
2353.Dl "ipfw add pipe 1 udp from any to any"
2354.Dl "ipfw add pipe 1 ip from any to any"
2355.Dl "ipfw pipe 1 config mask all"
2356.Pp
2357The above set of rules will create queues (and collect
2358statistics) for all traffic.
2359Because the pipes have no limitations, the only effect is
2360collecting statistics.
2361Note that we need 3 rules, not just the last one, because
2362when
2363.Nm
2364tries to match IP packets it will not consider ports, so we
2365would not see connections on separate ports as different
2366ones.
2367.Pp
2368A more sophisticated example is limiting the outbound traffic
2369on a net with per-host limits, rather than per-network limits:
2370.Pp
2371.Dl "ipfw add pipe 1 ip from 192.168.2.0/24 to any out"
2372.Dl "ipfw add pipe 2 ip from any to 192.168.2.0/24 in"
2373.Dl "ipfw pipe 1 config mask src-ip 0x000000ff bw 200Kbit/s queue 20Kbytes"
2374.Dl "ipfw pipe 2 config mask dst-ip 0x000000ff bw 200Kbit/s queue 20Kbytes"
2375.Ss LOOKUP TABLES
2376In the following example, we need to create several traffic bandwidth
2377classes and we need different hosts/networks to fall into different classes.
2378We create one pipe for each class and configure them accordingly.
2379Then we create a single table and fill it with IP subnets and addresses.
2380For each subnet/host we set the argument equal to the number of the pipe
2381that it should use.
2382Then we classify traffic using a single rule:
2383.Pp
2384.Dl "ipfw pipe 1 config bw 1000Kbyte/s"
2385.Dl "ipfw pipe 4 config bw 4000Kbyte/s"
2386.Dl "..."
2387.Dl "ipfw table 1 add 192.168.2.0/24 1"
2388.Dl "ipfw table 1 add 192.168.0.0/27 4"
2389.Dl "ipfw table 1 add 192.168.0.2 1"
2390.Dl "..."
2391.Dl "ipfw pipe tablearg ip from table(1) to any"
2392.Pp
2393Using the
2394.Cm fwd
2395action, the table entries may include hostnames and IP addresses.
2396.Pp
2397.Dl "ipfw table 1 add 192.168.2.0/24 10.23.2.1"
2398.Dl "ipfw table 1 add 192.168.0.0/27 router1.dmz"
2399.Dl "..."
2400.Dl "ipfw add 100 fwd tablearg ip from any to table(1)"
2401.Ss SETS OF RULES
2402To add a set of rules atomically, e.g.\& set 18:
2403.Pp
2404.Dl "ipfw set disable 18"
2405.Dl "ipfw add NN set 18 ...         # repeat as needed"
2406.Dl "ipfw set enable 18"
2407.Pp
2408To delete a set of rules atomically the command is simply:
2409.Pp
2410.Dl "ipfw delete set 18"
2411.Pp
2412To test a ruleset and disable it and regain control if something goes wrong:
2413.Pp
2414.Dl "ipfw set disable 18"
2415.Dl "ipfw add NN set 18 ...         # repeat as needed"
2416.Dl "ipfw set enable 18; echo done; sleep 30 && ipfw set disable 18"
2417.Pp
2418Here if everything goes well, you press control-C before the "sleep"
2419terminates, and your ruleset will be left active.
2420Otherwise, e.g.\& if
2421you cannot access your box, the ruleset will be disabled after
2422the sleep terminates thus restoring the previous situation.
2423.Sh SEE ALSO
2424.Xr cpp 1 ,
2425.Xr m4 1 ,
2426.Xr altq 4 ,
2427.Xr divert 4 ,
2428.Xr dummynet 4 ,
2429.Xr if_bridge 4 ,
2430.Xr ip 4 ,
2431.Xr ipfirewall 4 ,
2432.Xr ng_ipfw 4 ,
2433.Xr protocols 5 ,
2434.Xr services 5 ,
2435.Xr init 8 ,
2436.Xr kldload 8 ,
2437.Xr reboot 8 ,
2438.Xr sysctl 8 ,
2439.Xr syslogd 8
2440.Sh HISTORY
2441The
2442.Nm
2443utility first appeared in
2444.Fx 2.0 .
2445.Xr dummynet 4
2446was introduced in
2447.Fx 2.2.8 .
2448Stateful extensions were introduced in
2449.Fx 4.0 .
2450.Nm ipfw2
2451was introduced in Summer 2002.
2452.Sh AUTHORS
2453.An Ugen J. S. Antsilevich ,
2454.An Poul-Henning Kamp ,
2455.An Alex Nash ,
2456.An Archie Cobbs ,
2457.An Luigi Rizzo .
2458.Pp
2459.An -nosplit
2460API based upon code written by
2461.An Daniel Boulet
2462for BSDI.
2463.Pp
2464Work on
2465.Xr dummynet 4
2466traffic shaper supported by Akamba Corp.
2467.Sh BUGS
2468Use of dummynet with IPv6 requires that debug.mpsafenet be set to 0.
2469.Pp
2470The syntax has grown over the years and sometimes it might be confusing.
2471Unfortunately, backward compatibility prevents cleaning up mistakes
2472made in the definition of the syntax.
2473.Pp
2474.Em !!! WARNING !!!
2475.Pp
2476Misconfiguring the firewall can put your computer in an unusable state,
2477possibly shutting down network services and requiring console access to
2478regain control of it.
2479.Pp
2480Incoming packet fragments diverted by
2481.Cm divert
2482are reassembled before delivery to the socket.
2483The action used on those packet is the one from the
2484rule which matches the first fragment of the packet.
2485.Pp
2486Packets diverted to userland, and then reinserted by a userland process
2487may lose various packet attributes.
2488The packet source interface name
2489will be preserved if it is shorter than 8 bytes and the userland process
2490saves and reuses the sockaddr_in
2491(as does
2492.Xr natd 8 ) ;
2493otherwise, it may be lost.
2494If a packet is reinserted in this manner, later rules may be incorrectly
2495applied, making the order of
2496.Cm divert
2497rules in the rule sequence very important.
2498.Pp
2499Dummynet drops all packets with IPv6 link-local addresses.
2500.Pp
2501Rules using
2502.Cm uid
2503or
2504.Cm gid
2505may not behave as expected.
2506In particular, incoming SYN packets may
2507have no uid or gid associated with them since they do not yet belong
2508to a TCP connection, and the uid/gid associated with a packet may not
2509be as expected if the associated process calls
2510.Xr setuid 2
2511or similar system calls.
2512.Pp
2513Rules which use uid, gid or jail based matching should be used only
2514if debug.mpsafenet=0 to avoid possible deadlocks due to layering
2515violations in its implementation.
2516