xref: /freebsd/sbin/ipfw/ipfw.8 (revision 3fc36ee018bb836bd1796067cf4ef8683f166ebc)
1.\"
2.\" $FreeBSD$
3.\"
4.Dd August 21, 2016
5.Dt IPFW 8
6.Os
7.Sh NAME
8.Nm ipfw
9.Nd User interface for firewall, traffic shaper, packet scheduler,
10in-kernel NAT.
11.Sh SYNOPSIS
12.Ss FIREWALL CONFIGURATION
13.Nm
14.Op Fl cq
15.Cm add
16.Ar rule
17.Nm
18.Op Fl acdefnNStT
19.Op Cm set Ar N
20.Brq Cm list | show
21.Op Ar rule | first-last ...
22.Nm
23.Op Fl f | q
24.Op Cm set Ar N
25.Cm flush
26.Nm
27.Op Fl q
28.Op Cm set Ar N
29.Brq Cm delete | zero | resetlog
30.Op Ar number ...
31.Pp
32.Nm
33.Cm set Oo Cm disable Ar number ... Oc Op Cm enable Ar number ...
34.Nm
35.Cm set move
36.Op Cm rule
37.Ar number Cm to Ar number
38.Nm
39.Cm set swap Ar number number
40.Nm
41.Cm set show
42.Ss SYSCTL SHORTCUTS
43.Nm
44.Cm enable
45.Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
46.Nm
47.Cm disable
48.Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
49.Ss LOOKUP TABLES
50.Nm
51.Oo Cm set Ar N Oc Cm table Ar name Cm create Ar create-options
52.Nm
53.Oo Cm set Ar N Oc Cm table Ar name Cm destroy
54.Nm
55.Oo Cm set Ar N Oc Cm table Ar name Cm modify Ar modify-options
56.Nm
57.Oo Cm set Ar N Oc Cm table Ar name Cm swap Ar name
58.Nm
59.Oo Cm set Ar N Oc Cm table Ar name Cm add Ar table-key Op Ar value
60.Nm
61.Oo Cm set Ar N Oc Cm table Ar name Cm add Op Ar table-key Ar value ...
62.Nm
63.Oo Cm set Ar N Oc Cm table Ar name Cm atomic add Op Ar table-key Ar value ...
64.Nm
65.Oo Cm set Ar N Oc Cm table Ar name Cm delete Op Ar table-key ...
66.Nm
67.Oo Cm set Ar N Oc Cm table Ar name Cm lookup Ar addr
68.Nm
69.Oo Cm set Ar N Oc Cm table Ar name Cm lock
70.Nm
71.Oo Cm set Ar N Oc Cm table Ar name Cm unlock
72.Nm
73.Oo Cm set Ar N Oc Cm table
74.Brq Ar name | all
75.Cm list
76.Nm
77.Oo Cm set Ar N Oc Cm table
78.Brq Ar name | all
79.Cm info
80.Nm
81.Oo Cm set Ar N Oc Cm table
82.Brq Ar name | all
83.Cm detail
84.Nm
85.Oo Cm set Ar N Oc Cm table
86.Brq Ar name | all
87.Cm flush
88.Ss DUMMYNET CONFIGURATION (TRAFFIC SHAPER AND PACKET SCHEDULER)
89.Nm
90.Brq Cm pipe | queue | sched
91.Ar number
92.Cm config
93.Ar config-options
94.Nm
95.Op Fl s Op Ar field
96.Brq Cm pipe | queue | sched
97.Brq Cm delete | list | show
98.Op Ar number ...
99.Ss IN-KERNEL NAT
100.Nm
101.Op Fl q
102.Cm nat
103.Ar number
104.Cm config
105.Ar config-options
106.Pp
107.Nm
108.Op Fl cfnNqS
109.Oo
110.Fl p Ar preproc
111.Oo
112.Ar preproc-flags
113.Oc
114.Oc
115.Ar pathname
116.Ss STATEFUL IPv6/IPv4 NETWORK ADDRESS AND PROTOCOL TRANSLATION
117.Nm
118.Oo Cm set Ar N Oc Cm nat64lsn Ar name Cm create Ar create-options
119.Nm
120.Oo Cm set Ar N Oc Cm nat64lsn Ar name Cm config Ar config-options
121.Nm
122.Oo Cm set Ar N Oc Cm nat64lsn
123.Brq Ar name | all
124.Brq Cm list | show
125.Op Cm states
126.Nm
127.Oo Cm set Ar N Oc Cm nat64lsn
128.Brq Ar name | all
129.Cm destroy
130.Nm
131.Oo Cm set Ar N Oc Cm nat64lsn Ar name Cm stats Op Cm reset
132.Ss STATELESS IPv6/IPv4 NETWORK ADDRESS AND PROTOCOL TRANSLATION
133.Nm
134.Oo Cm set Ar N Oc Cm nat64stl Ar name Cm create Ar create-options
135.Nm
136.Oo Cm set Ar N Oc Cm nat64stl Ar name Cm config Ar config-options
137.Nm
138.Oo Cm set Ar N Oc Cm nat64stl
139.Brq Ar name | all
140.Brq Cm list | show
141.Nm
142.Oo Cm set Ar N Oc Cm nat64stl
143.Brq Ar name | all
144.Cm destroy
145.Nm
146.Oo Cm set Ar N Oc Cm nat64stl Ar name Cm stats Op Cm reset
147.Ss IPv6-to-IPv6 NETWORK PREFIX TRANSLATION
148.Nm
149.Oo Cm set Ar N Oc Cm nptv6 Ar name Cm create Ar create-options
150.Nm
151.Oo Cm set Ar N Oc Cm nptv6
152.Brq Ar name | all
153.Brq Cm list | show
154.Nm
155.Oo Cm set Ar N Oc Cm nptv6
156.Brq Ar name | all
157.Cm destroy
158.Nm
159.Oo Cm set Ar N Oc Cm nptv6 Ar name Cm stats Op Cm reset
160.Ss INTERNAL DIAGNOSTICS
161.Nm
162.Cm internal iflist
163.Nm
164.Cm internal talist
165.Nm
166.Cm internal vlist
167.Sh DESCRIPTION
168The
169.Nm
170utility is the user interface for controlling the
171.Xr ipfw 4
172firewall, the
173.Xr dummynet 4
174traffic shaper/packet scheduler, and the
175in-kernel NAT services.
176.Pp
177A firewall configuration, or
178.Em ruleset ,
179is made of a list of
180.Em rules
181numbered from 1 to 65535.
182Packets are passed to the firewall
183from a number of different places in the protocol stack
184(depending on the source and destination of the packet,
185it is possible for the firewall to be
186invoked multiple times on the same packet).
187The packet passed to the firewall is compared
188against each of the rules in the
189.Em ruleset ,
190in rule-number order
191(multiple rules with the same number are permitted, in which case
192they are processed in order of insertion).
193When a match is found, the action corresponding to the
194matching rule is performed.
195.Pp
196Depending on the action and certain system settings, packets
197can be reinjected into the firewall at some rule after the
198matching one for further processing.
199.Pp
200A ruleset always includes a
201.Em default
202rule (numbered 65535) which cannot be modified or deleted,
203and matches all packets.
204The action associated with the
205.Em default
206rule can be either
207.Cm deny
208or
209.Cm allow
210depending on how the kernel is configured.
211.Pp
212If the ruleset includes one or more rules with the
213.Cm keep-state
214or
215.Cm limit
216option,
217the firewall will have a
218.Em stateful
219behaviour, i.e., upon a match it will create
220.Em dynamic rules ,
221i.e., rules that match packets with the same 5-tuple
222(protocol, source and destination addresses and ports)
223as the packet which caused their creation.
224Dynamic rules, which have a limited lifetime, are checked
225at the first occurrence of a
226.Cm check-state ,
227.Cm keep-state
228or
229.Cm limit
230rule, and are typically used to open the firewall on-demand to
231legitimate traffic only.
232See the
233.Sx STATEFUL FIREWALL
234and
235.Sx EXAMPLES
236Sections below for more information on the stateful behaviour of
237.Nm .
238.Pp
239All rules (including dynamic ones) have a few associated counters:
240a packet count, a byte count, a log count and a timestamp
241indicating the time of the last match.
242Counters can be displayed or reset with
243.Nm
244commands.
245.Pp
246Each rule belongs to one of 32 different
247.Em sets
248, and there are
249.Nm
250commands to atomically manipulate sets, such as enable,
251disable, swap sets, move all rules in a set to another
252one, delete all rules in a set.
253These can be useful to
254install temporary configurations, or to test them.
255See Section
256.Sx SETS OF RULES
257for more information on
258.Em sets .
259.Pp
260Rules can be added with the
261.Cm add
262command; deleted individually or in groups with the
263.Cm delete
264command, and globally (except those in set 31) with the
265.Cm flush
266command; displayed, optionally with the content of the
267counters, using the
268.Cm show
269and
270.Cm list
271commands.
272Finally, counters can be reset with the
273.Cm zero
274and
275.Cm resetlog
276commands.
277.Pp
278.Ss COMMAND OPTIONS
279The following general options are available when invoking
280.Nm :
281.Bl -tag -width indent
282.It Fl a
283Show counter values when listing rules.
284The
285.Cm show
286command implies this option.
287.It Fl b
288Only show the action and the comment, not the body of a rule.
289Implies
290.Fl c .
291.It Fl c
292When entering or showing rules, print them in compact form,
293i.e., omitting the "ip from any to any" string
294when this does not carry any additional information.
295.It Fl d
296When listing, show dynamic rules in addition to static ones.
297.It Fl e
298When listing and
299.Fl d
300is specified, also show expired dynamic rules.
301.It Fl f
302Do not ask for confirmation for commands that can cause problems
303if misused, i.e.,
304.Cm flush .
305If there is no tty associated with the process, this is implied.
306.It Fl i
307When listing a table (see the
308.Sx LOOKUP TABLES
309section below for more information on lookup tables), format values
310as IP addresses.
311By default, values are shown as integers.
312.It Fl n
313Only check syntax of the command strings, without actually passing
314them to the kernel.
315.It Fl N
316Try to resolve addresses and service names in output.
317.It Fl q
318Be quiet when executing the
319.Cm add ,
320.Cm nat ,
321.Cm zero ,
322.Cm resetlog
323or
324.Cm flush
325commands;
326(implies
327.Fl f ) .
328This is useful when updating rulesets by executing multiple
329.Nm
330commands in a script
331(e.g.,
332.Ql sh\ /etc/rc.firewall ) ,
333or by processing a file with many
334.Nm
335rules across a remote login session.
336It also stops a table add or delete
337from failing if the entry already exists or is not present.
338.Pp
339The reason why this option may be important is that
340for some of these actions,
341.Nm
342may print a message; if the action results in blocking the
343traffic to the remote client,
344the remote login session will be closed
345and the rest of the ruleset will not be processed.
346Access to the console would then be required to recover.
347.It Fl S
348When listing rules, show the
349.Em set
350each rule belongs to.
351If this flag is not specified, disabled rules will not be
352listed.
353.It Fl s Op Ar field
354When listing pipes, sort according to one of the four
355counters (total or current packets or bytes).
356.It Fl t
357When listing, show last match timestamp converted with ctime().
358.It Fl T
359When listing, show last match timestamp as seconds from the epoch.
360This form can be more convenient for postprocessing by scripts.
361.El
362.Ss LIST OF RULES AND PREPROCESSING
363To ease configuration, rules can be put into a file which is
364processed using
365.Nm
366as shown in the last synopsis line.
367An absolute
368.Ar pathname
369must be used.
370The file will be read line by line and applied as arguments to the
371.Nm
372utility.
373.Pp
374Optionally, a preprocessor can be specified using
375.Fl p Ar preproc
376where
377.Ar pathname
378is to be piped through.
379Useful preprocessors include
380.Xr cpp 1
381and
382.Xr m4 1 .
383If
384.Ar preproc
385does not start with a slash
386.Pq Ql /
387as its first character, the usual
388.Ev PATH
389name search is performed.
390Care should be taken with this in environments where not all
391file systems are mounted (yet) by the time
392.Nm
393is being run (e.g.\& when they are mounted over NFS).
394Once
395.Fl p
396has been specified, any additional arguments are passed on to the preprocessor
397for interpretation.
398This allows for flexible configuration files (like conditionalizing
399them on the local hostname) and the use of macros to centralize
400frequently required arguments like IP addresses.
401.Ss TRAFFIC SHAPER CONFIGURATION
402The
403.Nm
404.Cm pipe , queue
405and
406.Cm sched
407commands are used to configure the traffic shaper and packet scheduler.
408See the
409.Sx TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
410Section below for details.
411.Pp
412If the world and the kernel get out of sync the
413.Nm
414ABI may break, preventing you from being able to add any rules.
415This can adversely affect the booting process.
416You can use
417.Nm
418.Cm disable
419.Cm firewall
420to temporarily disable the firewall to regain access to the network,
421allowing you to fix the problem.
422.Sh PACKET FLOW
423A packet is checked against the active ruleset in multiple places
424in the protocol stack, under control of several sysctl variables.
425These places and variables are shown below, and it is important to
426have this picture in mind in order to design a correct ruleset.
427.Bd -literal -offset indent
428       ^    to upper layers    V
429       |                       |
430       +----------->-----------+
431       ^                       V
432 [ip(6)_input]           [ip(6)_output]     net.inet(6).ip(6).fw.enable=1
433       |                       |
434       ^                       V
435 [ether_demux]        [ether_output_frame]  net.link.ether.ipfw=1
436       |                       |
437       +-->--[bdg_forward]-->--+            net.link.bridge.ipfw=1
438       ^                       V
439       |      to devices       |
440.Ed
441.Pp
442The number of
443times the same packet goes through the firewall can
444vary between 0 and 4 depending on packet source and
445destination, and system configuration.
446.Pp
447Note that as packets flow through the stack, headers can be
448stripped or added to it, and so they may or may not be available
449for inspection.
450E.g., incoming packets will include the MAC header when
451.Nm
452is invoked from
453.Cm ether_demux() ,
454but the same packets will have the MAC header stripped off when
455.Nm
456is invoked from
457.Cm ip_input()
458or
459.Cm ip6_input() .
460.Pp
461Also note that each packet is always checked against the complete ruleset,
462irrespective of the place where the check occurs, or the source of the packet.
463If a rule contains some match patterns or actions which are not valid
464for the place of invocation (e.g.\& trying to match a MAC header within
465.Cm ip_input
466or
467.Cm ip6_input ),
468the match pattern will not match, but a
469.Cm not
470operator in front of such patterns
471.Em will
472cause the pattern to
473.Em always
474match on those packets.
475It is thus the responsibility of
476the programmer, if necessary, to write a suitable ruleset to
477differentiate among the possible places.
478.Cm skipto
479rules can be useful here, as an example:
480.Bd -literal -offset indent
481# packets from ether_demux or bdg_forward
482ipfw add 10 skipto 1000 all from any to any layer2 in
483# packets from ip_input
484ipfw add 10 skipto 2000 all from any to any not layer2 in
485# packets from ip_output
486ipfw add 10 skipto 3000 all from any to any not layer2 out
487# packets from ether_output_frame
488ipfw add 10 skipto 4000 all from any to any layer2 out
489.Ed
490.Pp
491(yes, at the moment there is no way to differentiate between
492ether_demux and bdg_forward).
493.Sh SYNTAX
494In general, each keyword or argument must be provided as
495a separate command line argument, with no leading or trailing
496spaces.
497Keywords are case-sensitive, whereas arguments may
498or may not be case-sensitive depending on their nature
499(e.g.\& uid's are, hostnames are not).
500.Pp
501Some arguments (e.g., port or address lists) are comma-separated
502lists of values.
503In this case, spaces after commas ',' are allowed to make
504the line more readable.
505You can also put the entire
506command (including flags) into a single argument.
507E.g., the following forms are equivalent:
508.Bd -literal -offset indent
509ipfw -q add deny src-ip 10.0.0.0/24,127.0.0.1/8
510ipfw -q add deny src-ip 10.0.0.0/24, 127.0.0.1/8
511ipfw "-q add deny src-ip 10.0.0.0/24, 127.0.0.1/8"
512.Ed
513.Sh RULE FORMAT
514The format of firewall rules is the following:
515.Bd -ragged -offset indent
516.Bk -words
517.Op Ar rule_number
518.Op Cm set Ar set_number
519.Op Cm prob Ar match_probability
520.Ar action
521.Op Cm log Op Cm logamount Ar number
522.Op Cm altq Ar queue
523.Oo
524.Bro Cm tag | untag
525.Brc Ar number
526.Oc
527.Ar body
528.Ek
529.Ed
530.Pp
531where the body of the rule specifies which information is used
532for filtering packets, among the following:
533.Pp
534.Bl -tag -width "Source and dest. addresses and ports" -offset XXX -compact
535.It Layer-2 header fields
536When available
537.It IPv4 and IPv6 Protocol
538TCP, UDP, ICMP, etc.
539.It Source and dest. addresses and ports
540.It Direction
541See Section
542.Sx PACKET FLOW
543.It Transmit and receive interface
544By name or address
545.It Misc. IP header fields
546Version, type of service, datagram length, identification,
547fragment flag (non-zero IP offset),
548Time To Live
549.It IP options
550.It IPv6 Extension headers
551Fragmentation, Hop-by-Hop options,
552Routing Headers, Source routing rthdr0, Mobile IPv6 rthdr2, IPSec options.
553.It IPv6 Flow-ID
554.It Misc. TCP header fields
555TCP flags (SYN, FIN, ACK, RST, etc.),
556sequence number, acknowledgment number,
557window
558.It TCP options
559.It ICMP types
560for ICMP packets
561.It ICMP6 types
562for ICMP6 packets
563.It User/group ID
564When the packet can be associated with a local socket.
565.It Divert status
566Whether a packet came from a divert socket (e.g.,
567.Xr natd 8 ) .
568.It Fib annotation state
569Whether a packet has been tagged for using a specific FIB (routing table)
570in future forwarding decisions.
571.El
572.Pp
573Note that some of the above information, e.g.\& source MAC or IP addresses and
574TCP/UDP ports, can be easily spoofed, so filtering on those fields
575alone might not guarantee the desired results.
576.Bl -tag -width indent
577.It Ar rule_number
578Each rule is associated with a
579.Ar rule_number
580in the range 1..65535, with the latter reserved for the
581.Em default
582rule.
583Rules are checked sequentially by rule number.
584Multiple rules can have the same number, in which case they are
585checked (and listed) according to the order in which they have
586been added.
587If a rule is entered without specifying a number, the kernel will
588assign one in such a way that the rule becomes the last one
589before the
590.Em default
591rule.
592Automatic rule numbers are assigned by incrementing the last
593non-default rule number by the value of the sysctl variable
594.Ar net.inet.ip.fw.autoinc_step
595which defaults to 100.
596If this is not possible (e.g.\& because we would go beyond the
597maximum allowed rule number), the number of the last
598non-default value is used instead.
599.It Cm set Ar set_number
600Each rule is associated with a
601.Ar set_number
602in the range 0..31.
603Sets can be individually disabled and enabled, so this parameter
604is of fundamental importance for atomic ruleset manipulation.
605It can be also used to simplify deletion of groups of rules.
606If a rule is entered without specifying a set number,
607set 0 will be used.
608.br
609Set 31 is special in that it cannot be disabled,
610and rules in set 31 are not deleted by the
611.Nm ipfw flush
612command (but you can delete them with the
613.Nm ipfw delete set 31
614command).
615Set 31 is also used for the
616.Em default
617rule.
618.It Cm prob Ar match_probability
619A match is only declared with the specified probability
620(floating point number between 0 and 1).
621This can be useful for a number of applications such as
622random packet drop or
623(in conjunction with
624.Nm dummynet )
625to simulate the effect of multiple paths leading to out-of-order
626packet delivery.
627.Pp
628Note: this condition is checked before any other condition, including
629ones such as keep-state or check-state which might have side effects.
630.It Cm log Op Cm logamount Ar number
631Packets matching a rule with the
632.Cm log
633keyword will be made available for logging in two ways:
634if the sysctl variable
635.Va net.inet.ip.fw.verbose
636is set to 0 (default), one can use
637.Xr bpf 4
638attached to the
639.Li ipfw0
640pseudo interface.
641This pseudo interface can be created after a boot
642manually by using the following command:
643.Bd -literal -offset indent
644# ifconfig ipfw0 create
645.Ed
646.Pp
647Or, automatically at boot time by adding the following
648line to the
649.Xr rc.conf 5
650file:
651.Bd -literal -offset indent
652firewall_logif="YES"
653.Ed
654.Pp
655There is no overhead if no
656.Xr bpf 4
657is attached to the pseudo interface.
658.Pp
659If
660.Va net.inet.ip.fw.verbose
661is set to 1, packets will be logged to
662.Xr syslogd 8
663with a
664.Dv LOG_SECURITY
665facility up to a maximum of
666.Cm logamount
667packets.
668If no
669.Cm logamount
670is specified, the limit is taken from the sysctl variable
671.Va net.inet.ip.fw.verbose_limit .
672In both cases, a value of 0 means unlimited logging.
673.Pp
674Once the limit is reached, logging can be re-enabled by
675clearing the logging counter or the packet counter for that entry, see the
676.Cm resetlog
677command.
678.Pp
679Note: logging is done after all other packet matching conditions
680have been successfully verified, and before performing the final
681action (accept, deny, etc.) on the packet.
682.It Cm tag Ar number
683When a packet matches a rule with the
684.Cm tag
685keyword, the numeric tag for the given
686.Ar number
687in the range 1..65534 will be attached to the packet.
688The tag acts as an internal marker (it is not sent out over
689the wire) that can be used to identify these packets later on.
690This can be used, for example, to provide trust between interfaces
691and to start doing policy-based filtering.
692A packet can have multiple tags at the same time.
693Tags are "sticky", meaning once a tag is applied to a packet by a
694matching rule it exists until explicit removal.
695Tags are kept with the packet everywhere within the kernel, but are
696lost when packet leaves the kernel, for example, on transmitting
697packet out to the network or sending packet to a
698.Xr divert 4
699socket.
700.Pp
701To check for previously applied tags, use the
702.Cm tagged
703rule option.
704To delete previously applied tag, use the
705.Cm untag
706keyword.
707.Pp
708Note: since tags are kept with the packet everywhere in kernelspace,
709they can be set and unset anywhere in the kernel network subsystem
710(using the
711.Xr mbuf_tags 9
712facility), not only by means of the
713.Xr ipfw 4
714.Cm tag
715and
716.Cm untag
717keywords.
718For example, there can be a specialized
719.Xr netgraph 4
720node doing traffic analyzing and tagging for later inspecting
721in firewall.
722.It Cm untag Ar number
723When a packet matches a rule with the
724.Cm untag
725keyword, the tag with the number
726.Ar number
727is searched among the tags attached to this packet and,
728if found, removed from it.
729Other tags bound to packet, if present, are left untouched.
730.It Cm altq Ar queue
731When a packet matches a rule with the
732.Cm altq
733keyword, the ALTQ identifier for the given
734.Ar queue
735(see
736.Xr altq 4 )
737will be attached.
738Note that this ALTQ tag is only meaningful for packets going "out" of IPFW,
739and not being rejected or going to divert sockets.
740Note that if there is insufficient memory at the time the packet is
741processed, it will not be tagged, so it is wise to make your ALTQ
742"default" queue policy account for this.
743If multiple
744.Cm altq
745rules match a single packet, only the first one adds the ALTQ classification
746tag.
747In doing so, traffic may be shaped by using
748.Cm count Cm altq Ar queue
749rules for classification early in the ruleset, then later applying
750the filtering decision.
751For example,
752.Cm check-state
753and
754.Cm keep-state
755rules may come later and provide the actual filtering decisions in
756addition to the fallback ALTQ tag.
757.Pp
758You must run
759.Xr pfctl 8
760to set up the queues before IPFW will be able to look them up by name,
761and if the ALTQ disciplines are rearranged, the rules in containing the
762queue identifiers in the kernel will likely have gone stale and need
763to be reloaded.
764Stale queue identifiers will probably result in misclassification.
765.Pp
766All system ALTQ processing can be turned on or off via
767.Nm
768.Cm enable Ar altq
769and
770.Nm
771.Cm disable Ar altq .
772The usage of
773.Va net.inet.ip.fw.one_pass
774is irrelevant to ALTQ traffic shaping, as the actual rule action is followed
775always after adding an ALTQ tag.
776.El
777.Ss RULE ACTIONS
778A rule can be associated with one of the following actions, which
779will be executed when the packet matches the body of the rule.
780.Bl -tag -width indent
781.It Cm allow | accept | pass | permit
782Allow packets that match rule.
783The search terminates.
784.It Cm check-state Op Ar flowname | Cm any
785Checks the packet against the dynamic ruleset.
786If a match is found, execute the action associated with
787the rule which generated this dynamic rule, otherwise
788move to the next rule.
789.br
790.Cm Check-state
791rules do not have a body.
792If no
793.Cm check-state
794rule is found, the dynamic ruleset is checked at the first
795.Cm keep-state
796or
797.Cm limit
798rule.
799The
800.Ar flowname
801is symbolic name assigned to dynamic rule by
802.Cm keep-state
803opcode.
804The special flowname
805.Cm any
806can be used to ignore states flowname when matching.
807The
808.Cm default
809keyword is special name used for compatibility with old rulesets.
810.It Cm count
811Update counters for all packets that match rule.
812The search continues with the next rule.
813.It Cm deny | drop
814Discard packets that match this rule.
815The search terminates.
816.It Cm divert Ar port
817Divert packets that match this rule to the
818.Xr divert 4
819socket bound to port
820.Ar port .
821The search terminates.
822.It Cm fwd | forward Ar ipaddr | tablearg Ns Op , Ns Ar port
823Change the next-hop on matching packets to
824.Ar ipaddr ,
825which can be an IP address or a host name.
826For IPv4, the next hop can also be supplied by the last table
827looked up for the packet by using the
828.Cm tablearg
829keyword instead of an explicit address.
830The search terminates if this rule matches.
831.Pp
832If
833.Ar ipaddr
834is a local address, then matching packets will be forwarded to
835.Ar port
836(or the port number in the packet if one is not specified in the rule)
837on the local machine.
838.br
839If
840.Ar ipaddr
841is not a local address, then the port number
842(if specified) is ignored, and the packet will be
843forwarded to the remote address, using the route as found in
844the local routing table for that IP.
845.br
846A
847.Ar fwd
848rule will not match layer-2 packets (those received
849on ether_input, ether_output, or bridged).
850.br
851The
852.Cm fwd
853action does not change the contents of the packet at all.
854In particular, the destination address remains unmodified, so
855packets forwarded to another system will usually be rejected by that system
856unless there is a matching rule on that system to capture them.
857For packets forwarded locally,
858the local address of the socket will be
859set to the original destination address of the packet.
860This makes the
861.Xr netstat 1
862entry look rather weird but is intended for
863use with transparent proxy servers.
864.It Cm nat Ar nat_nr | tablearg
865Pass packet to a
866nat instance
867(for network address translation, address redirect, etc.):
868see the
869.Sx NETWORK ADDRESS TRANSLATION (NAT)
870Section for further information.
871.It Cm nat64lsn Ar name
872Pass packet to a stateful NAT64 instance (for IPv6/IPv4 network address and
873protocol translation): see the
874.Sx IPv6/IPv4 NETWORK ADDRESS AND PROTOCOL TRANSLATION
875Section for further information.
876.It Cm nat64stl Ar name
877Pass packet to a stateless NAT64 instance (for IPv6/IPv4 network address and
878protocol translation): see the
879.Sx IPv6/IPv4 NETWORK ADDRESS AND PROTOCOL TRANSLATION
880Section for further information.
881.It Cm nptv6 Ar name
882Pass packet to a NPTv6 instance (for IPv6-to-IPv6 network prefix translation):
883see the
884.Sx IPv6-to-IPv6 NETWORK PREFIX TRANSLATION (NPTv6)
885Section for further information.
886.It Cm pipe Ar pipe_nr
887Pass packet to a
888.Nm dummynet
889.Dq pipe
890(for bandwidth limitation, delay, etc.).
891See the
892.Sx TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
893Section for further information.
894The search terminates; however, on exit from the pipe and if
895the
896.Xr sysctl 8
897variable
898.Va net.inet.ip.fw.one_pass
899is not set, the packet is passed again to the firewall code
900starting from the next rule.
901.It Cm queue Ar queue_nr
902Pass packet to a
903.Nm dummynet
904.Dq queue
905(for bandwidth limitation using WF2Q+).
906.It Cm reject
907(Deprecated).
908Synonym for
909.Cm unreach host .
910.It Cm reset
911Discard packets that match this rule, and if the
912packet is a TCP packet, try to send a TCP reset (RST) notice.
913The search terminates.
914.It Cm reset6
915Discard packets that match this rule, and if the
916packet is a TCP packet, try to send a TCP reset (RST) notice.
917The search terminates.
918.It Cm skipto Ar number | tablearg
919Skip all subsequent rules numbered less than
920.Ar number .
921The search continues with the first rule numbered
922.Ar number
923or higher.
924It is possible to use the
925.Cm tablearg
926keyword with a skipto for a
927.Em computed
928skipto. Skipto may work either in O(log(N)) or in O(1) depending
929on amount of memory and/or sysctl variables.
930See the
931.Sx SYSCTL VARIABLES
932section for more details.
933.It Cm call Ar number | tablearg
934The current rule number is saved in the internal stack and
935ruleset processing continues with the first rule numbered
936.Ar number
937or higher.
938If later a rule with the
939.Cm return
940action is encountered, the processing returns to the first rule
941with number of this
942.Cm call
943rule plus one or higher
944(the same behaviour as with packets returning from
945.Xr divert 4
946socket after a
947.Cm divert
948action).
949This could be used to make somewhat like an assembly language
950.Dq subroutine
951calls to rules with common checks for different interfaces, etc.
952.Pp
953Rule with any number could be called, not just forward jumps as with
954.Cm skipto .
955So, to prevent endless loops in case of mistakes, both
956.Cm call
957and
958.Cm return
959actions don't do any jumps and simply go to the next rule if memory
960cannot be allocated or stack overflowed/underflowed.
961.Pp
962Internally stack for rule numbers is implemented using
963.Xr mbuf_tags 9
964facility and currently has size of 16 entries.
965As mbuf tags are lost when packet leaves the kernel,
966.Cm divert
967should not be used in subroutines to avoid endless loops
968and other undesired effects.
969.It Cm return
970Takes rule number saved to internal stack by the last
971.Cm call
972action and returns ruleset processing to the first rule
973with number greater than number of corresponding
974.Cm call
975rule.
976See description of the
977.Cm call
978action for more details.
979.Pp
980Note that
981.Cm return
982rules usually end a
983.Dq subroutine
984and thus are unconditional, but
985.Nm
986command-line utility currently requires every action except
987.Cm check-state
988to have body.
989While it is sometimes useful to return only on some packets,
990usually you want to print just
991.Dq return
992for readability.
993A workaround for this is to use new syntax and
994.Fl c
995switch:
996.Bd -literal -offset indent
997# Add a rule without actual body
998ipfw add 2999 return via any
999
1000# List rules without "from any to any" part
1001ipfw -c list
1002.Ed
1003.Pp
1004This cosmetic annoyance may be fixed in future releases.
1005.It Cm tee Ar port
1006Send a copy of packets matching this rule to the
1007.Xr divert 4
1008socket bound to port
1009.Ar port .
1010The search continues with the next rule.
1011.It Cm unreach Ar code
1012Discard packets that match this rule, and try to send an ICMP
1013unreachable notice with code
1014.Ar code ,
1015where
1016.Ar code
1017is a number from 0 to 255, or one of these aliases:
1018.Cm net , host , protocol , port ,
1019.Cm needfrag , srcfail , net-unknown , host-unknown ,
1020.Cm isolated , net-prohib , host-prohib , tosnet ,
1021.Cm toshost , filter-prohib , host-precedence
1022or
1023.Cm precedence-cutoff .
1024The search terminates.
1025.It Cm unreach6 Ar code
1026Discard packets that match this rule, and try to send an ICMPv6
1027unreachable notice with code
1028.Ar code ,
1029where
1030.Ar code
1031is a number from 0, 1, 3 or 4, or one of these aliases:
1032.Cm no-route, admin-prohib, address
1033or
1034.Cm port .
1035The search terminates.
1036.It Cm netgraph Ar cookie
1037Divert packet into netgraph with given
1038.Ar cookie .
1039The search terminates.
1040If packet is later returned from netgraph it is either
1041accepted or continues with the next rule, depending on
1042.Va net.inet.ip.fw.one_pass
1043sysctl variable.
1044.It Cm ngtee Ar cookie
1045A copy of packet is diverted into netgraph, original
1046packet continues with the next rule.
1047See
1048.Xr ng_ipfw 4
1049for more information on
1050.Cm netgraph
1051and
1052.Cm ngtee
1053actions.
1054.It Cm setfib Ar fibnum | tablearg
1055The packet is tagged so as to use the FIB (routing table)
1056.Ar fibnum
1057in any subsequent forwarding decisions.
1058In the current implementation, this is limited to the values 0 through 15, see
1059.Xr setfib 2 .
1060Processing continues at the next rule.
1061It is possible to use the
1062.Cm tablearg
1063keyword with setfib.
1064If the tablearg value is not within the compiled range of fibs,
1065the packet's fib is set to 0.
1066.It Cm setdscp Ar DSCP | number | tablearg
1067Set specified DiffServ codepoint for an IPv4/IPv6 packet.
1068Processing continues at the next rule.
1069Supported values are:
1070.Pp
1071.Cm CS0
1072.Pq Dv 000000 ,
1073.Cm CS1
1074.Pq Dv 001000 ,
1075.Cm CS2
1076.Pq Dv 010000 ,
1077.Cm CS3
1078.Pq Dv 011000 ,
1079.Cm CS4
1080.Pq Dv 100000 ,
1081.Cm CS5
1082.Pq Dv 101000 ,
1083.Cm CS6
1084.Pq Dv 110000 ,
1085.Cm CS7
1086.Pq Dv 111000 ,
1087.Cm AF11
1088.Pq Dv 001010 ,
1089.Cm AF12
1090.Pq Dv 001100 ,
1091.Cm AF13
1092.Pq Dv 001110 ,
1093.Cm AF21
1094.Pq Dv 010010 ,
1095.Cm AF22
1096.Pq Dv 010100 ,
1097.Cm AF23
1098.Pq Dv 010110 ,
1099.Cm AF31
1100.Pq Dv 011010 ,
1101.Cm AF32
1102.Pq Dv 011100 ,
1103.Cm AF33
1104.Pq Dv 011110 ,
1105.Cm AF41
1106.Pq Dv 100010 ,
1107.Cm AF42
1108.Pq Dv 100100 ,
1109.Cm AF43
1110.Pq Dv 100110 ,
1111.Cm EF
1112.Pq Dv 101110 ,
1113.Cm BE
1114.Pq Dv 000000 .
1115Additionally, DSCP value can be specified by number (0..64).
1116It is also possible to use the
1117.Cm tablearg
1118keyword with setdscp.
1119If the tablearg value is not within the 0..64 range, lower 6 bits of supplied
1120value are used.
1121.It Cm reass
1122Queue and reassemble IP fragments.
1123If the packet is not fragmented, counters are updated and
1124processing continues with the next rule.
1125If the packet is the last logical fragment, the packet is reassembled and, if
1126.Va net.inet.ip.fw.one_pass
1127is set to 0, processing continues with the next rule.
1128Otherwise, the packet is allowed to pass and the search terminates.
1129If the packet is a fragment in the middle of a logical group of fragments,
1130it is consumed and
1131processing stops immediately.
1132.Pp
1133Fragment handling can be tuned via
1134.Va net.inet.ip.maxfragpackets
1135and
1136.Va net.inet.ip.maxfragsperpacket
1137which limit, respectively, the maximum number of processable
1138fragments (default: 800) and
1139the maximum number of fragments per packet (default: 16).
1140.Pp
1141NOTA BENE: since fragments do not contain port numbers,
1142they should be avoided with the
1143.Nm reass
1144rule.
1145Alternatively, direction-based (like
1146.Nm in
1147/
1148.Nm out
1149) and source-based (like
1150.Nm via
1151) match patterns can be used to select fragments.
1152.Pp
1153Usually a simple rule like:
1154.Bd -literal -offset indent
1155# reassemble incoming fragments
1156ipfw add reass all from any to any in
1157.Ed
1158.Pp
1159is all you need at the beginning of your ruleset.
1160.El
1161.Ss RULE BODY
1162The body of a rule contains zero or more patterns (such as
1163specific source and destination addresses or ports,
1164protocol options, incoming or outgoing interfaces, etc.)
1165that the packet must match in order to be recognised.
1166In general, the patterns are connected by (implicit)
1167.Cm and
1168operators -- i.e., all must match in order for the
1169rule to match.
1170Individual patterns can be prefixed by the
1171.Cm not
1172operator to reverse the result of the match, as in
1173.Pp
1174.Dl "ipfw add 100 allow ip from not 1.2.3.4 to any"
1175.Pp
1176Additionally, sets of alternative match patterns
1177.Pq Em or-blocks
1178can be constructed by putting the patterns in
1179lists enclosed between parentheses ( ) or braces { }, and
1180using the
1181.Cm or
1182operator as follows:
1183.Pp
1184.Dl "ipfw add 100 allow ip from { x or not y or z } to any"
1185.Pp
1186Only one level of parentheses is allowed.
1187Beware that most shells have special meanings for parentheses
1188or braces, so it is advisable to put a backslash \\ in front of them
1189to prevent such interpretations.
1190.Pp
1191The body of a rule must in general include a source and destination
1192address specifier.
1193The keyword
1194.Ar any
1195can be used in various places to specify that the content of
1196a required field is irrelevant.
1197.Pp
1198The rule body has the following format:
1199.Bd -ragged -offset indent
1200.Op Ar proto Cm from Ar src Cm to Ar dst
1201.Op Ar options
1202.Ed
1203.Pp
1204The first part (proto from src to dst) is for backward
1205compatibility with earlier versions of
1206.Fx .
1207In modern
1208.Fx
1209any match pattern (including MAC headers, IP protocols,
1210addresses and ports) can be specified in the
1211.Ar options
1212section.
1213.Pp
1214Rule fields have the following meaning:
1215.Bl -tag -width indent
1216.It Ar proto : protocol | Cm { Ar protocol Cm or ... }
1217.It Ar protocol : Oo Cm not Oc Ar protocol-name | protocol-number
1218An IP protocol specified by number or name
1219(for a complete list see
1220.Pa /etc/protocols ) ,
1221or one of the following keywords:
1222.Bl -tag -width indent
1223.It Cm ip4 | ipv4
1224Matches IPv4 packets.
1225.It Cm ip6 | ipv6
1226Matches IPv6 packets.
1227.It Cm ip | all
1228Matches any packet.
1229.El
1230.Pp
1231The
1232.Cm ipv6
1233in
1234.Cm proto
1235option will be treated as inner protocol.
1236And, the
1237.Cm ipv4
1238is not available in
1239.Cm proto
1240option.
1241.Pp
1242The
1243.Cm { Ar protocol Cm or ... }
1244format (an
1245.Em or-block )
1246is provided for convenience only but its use is deprecated.
1247.It Ar src No and Ar dst : Bro Cm addr | Cm { Ar addr Cm or ... } Brc Op Oo Cm not Oc Ar ports
1248An address (or a list, see below)
1249optionally followed by
1250.Ar ports
1251specifiers.
1252.Pp
1253The second format
1254.Em ( or-block
1255with multiple addresses) is provided for convenience only and
1256its use is discouraged.
1257.It Ar addr : Oo Cm not Oc Bro
1258.Cm any | me | me6 |
1259.Cm table Ns Pq Ar name Ns Op , Ns Ar value
1260.Ar | addr-list | addr-set
1261.Brc
1262.Bl -tag -width indent
1263.It Cm any
1264matches any IP address.
1265.It Cm me
1266matches any IP address configured on an interface in the system.
1267.It Cm me6
1268matches any IPv6 address configured on an interface in the system.
1269The address list is evaluated at the time the packet is
1270analysed.
1271.It Cm table Ns Pq Ar name Ns Op , Ns Ar value
1272Matches any IPv4 or IPv6 address for which an entry exists in the lookup table
1273.Ar number .
1274If an optional 32-bit unsigned
1275.Ar value
1276is also specified, an entry will match only if it has this value.
1277See the
1278.Sx LOOKUP TABLES
1279section below for more information on lookup tables.
1280.El
1281.It Ar addr-list : ip-addr Ns Op Ns , Ns Ar addr-list
1282.It Ar ip-addr :
1283A host or subnet address specified in one of the following ways:
1284.Bl -tag -width indent
1285.It Ar numeric-ip | hostname
1286Matches a single IPv4 address, specified as dotted-quad or a hostname.
1287Hostnames are resolved at the time the rule is added to the firewall list.
1288.It Ar addr Ns / Ns Ar masklen
1289Matches all addresses with base
1290.Ar addr
1291(specified as an IP address, a network number, or a hostname)
1292and mask width of
1293.Cm masklen
1294bits.
1295As an example, 1.2.3.4/25 or 1.2.3.0/25 will match
1296all IP numbers from 1.2.3.0 to 1.2.3.127 .
1297.It Ar addr Ns : Ns Ar mask
1298Matches all addresses with base
1299.Ar addr
1300(specified as an IP address, a network number, or a hostname)
1301and the mask of
1302.Ar mask ,
1303specified as a dotted quad.
1304As an example, 1.2.3.4:255.0.255.0 or 1.0.3.0:255.0.255.0 will match
13051.*.3.*.
1306This form is advised only for non-contiguous
1307masks.
1308It is better to resort to the
1309.Ar addr Ns / Ns Ar masklen
1310format for contiguous masks, which is more compact and less
1311error-prone.
1312.El
1313.It Ar addr-set : addr Ns Oo Ns / Ns Ar masklen Oc Ns Cm { Ns Ar list Ns Cm }
1314.It Ar list : Bro Ar num | num-num Brc Ns Op Ns , Ns Ar list
1315Matches all addresses with base address
1316.Ar addr
1317(specified as an IP address, a network number, or a hostname)
1318and whose last byte is in the list between braces { } .
1319Note that there must be no spaces between braces and
1320numbers (spaces after commas are allowed).
1321Elements of the list can be specified as single entries
1322or ranges.
1323The
1324.Ar masklen
1325field is used to limit the size of the set of addresses,
1326and can have any value between 24 and 32.
1327If not specified,
1328it will be assumed as 24.
1329.br
1330This format is particularly useful to handle sparse address sets
1331within a single rule.
1332Because the matching occurs using a
1333bitmask, it takes constant time and dramatically reduces
1334the complexity of rulesets.
1335.br
1336As an example, an address specified as 1.2.3.4/24{128,35-55,89}
1337or 1.2.3.0/24{128,35-55,89}
1338will match the following IP addresses:
1339.br
13401.2.3.128, 1.2.3.35 to 1.2.3.55, 1.2.3.89 .
1341.It Ar addr6-list : ip6-addr Ns Op Ns , Ns Ar addr6-list
1342.It Ar ip6-addr :
1343A host or subnet specified one of the following ways:
1344.Bl -tag -width indent
1345.It Ar numeric-ip | hostname
1346Matches a single IPv6 address as allowed by
1347.Xr inet_pton 3
1348or a hostname.
1349Hostnames are resolved at the time the rule is added to the firewall
1350list.
1351.It Ar addr Ns / Ns Ar masklen
1352Matches all IPv6 addresses with base
1353.Ar addr
1354(specified as allowed by
1355.Xr inet_pton
1356or a hostname)
1357and mask width of
1358.Cm masklen
1359bits.
1360.El
1361.Pp
1362No support for sets of IPv6 addresses is provided because IPv6 addresses
1363are typically random past the initial prefix.
1364.It Ar ports : Bro Ar port | port Ns \&- Ns Ar port Ns Brc Ns Op , Ns Ar ports
1365For protocols which support port numbers (such as TCP and UDP), optional
1366.Cm ports
1367may be specified as one or more ports or port ranges, separated
1368by commas but no spaces, and an optional
1369.Cm not
1370operator.
1371The
1372.Ql \&-
1373notation specifies a range of ports (including boundaries).
1374.Pp
1375Service names (from
1376.Pa /etc/services )
1377may be used instead of numeric port values.
1378The length of the port list is limited to 30 ports or ranges,
1379though one can specify larger ranges by using an
1380.Em or-block
1381in the
1382.Cm options
1383section of the rule.
1384.Pp
1385A backslash
1386.Pq Ql \e
1387can be used to escape the dash
1388.Pq Ql -
1389character in a service name (from a shell, the backslash must be
1390typed twice to avoid the shell itself interpreting it as an escape
1391character).
1392.Pp
1393.Dl "ipfw add count tcp from any ftp\e\e-data-ftp to any"
1394.Pp
1395Fragmented packets which have a non-zero offset (i.e., not the first
1396fragment) will never match a rule which has one or more port
1397specifications.
1398See the
1399.Cm frag
1400option for details on matching fragmented packets.
1401.El
1402.Ss RULE OPTIONS (MATCH PATTERNS)
1403Additional match patterns can be used within
1404rules.
1405Zero or more of these so-called
1406.Em options
1407can be present in a rule, optionally prefixed by the
1408.Cm not
1409operand, and possibly grouped into
1410.Em or-blocks .
1411.Pp
1412The following match patterns can be used (listed in alphabetical order):
1413.Bl -tag -width indent
1414.It Cm // this is a comment.
1415Inserts the specified text as a comment in the rule.
1416Everything following // is considered as a comment and stored in the rule.
1417You can have comment-only rules, which are listed as having a
1418.Cm count
1419action followed by the comment.
1420.It Cm bridged
1421Alias for
1422.Cm layer2 .
1423.It Cm diverted
1424Matches only packets generated by a divert socket.
1425.It Cm diverted-loopback
1426Matches only packets coming from a divert socket back into the IP stack
1427input for delivery.
1428.It Cm diverted-output
1429Matches only packets going from a divert socket back outward to the IP
1430stack output for delivery.
1431.It Cm dst-ip Ar ip-address
1432Matches IPv4 packets whose destination IP is one of the address(es)
1433specified as argument.
1434.It Bro Cm dst-ip6 | dst-ipv6 Brc Ar ip6-address
1435Matches IPv6 packets whose destination IP is one of the address(es)
1436specified as argument.
1437.It Cm dst-port Ar ports
1438Matches IP packets whose destination port is one of the port(s)
1439specified as argument.
1440.It Cm established
1441Matches TCP packets that have the RST or ACK bits set.
1442.It Cm ext6hdr Ar header
1443Matches IPv6 packets containing the extended header given by
1444.Ar header .
1445Supported headers are:
1446.Pp
1447Fragment,
1448.Pq Cm frag ,
1449Hop-to-hop options
1450.Pq Cm hopopt ,
1451any type of Routing Header
1452.Pq Cm route ,
1453Source routing Routing Header Type 0
1454.Pq Cm rthdr0 ,
1455Mobile IPv6 Routing Header Type 2
1456.Pq Cm rthdr2 ,
1457Destination options
1458.Pq Cm dstopt ,
1459IPSec authentication headers
1460.Pq Cm ah ,
1461and IPsec encapsulated security payload headers
1462.Pq Cm esp .
1463.It Cm fib Ar fibnum
1464Matches a packet that has been tagged to use
1465the given FIB (routing table) number.
1466.It Cm flow Ar table Ns Pq Ar name Ns Op , Ns Ar value
1467Search for the flow entry in lookup table
1468.Ar name .
1469If not found, the match fails.
1470Otherwise, the match succeeds and
1471.Cm tablearg
1472is set to the value extracted from the table.
1473.Pp
1474This option can be useful to quickly dispatch traffic based on
1475certain packet fields.
1476See the
1477.Sx LOOKUP TABLES
1478section below for more information on lookup tables.
1479.It Cm flow-id Ar labels
1480Matches IPv6 packets containing any of the flow labels given in
1481.Ar labels .
1482.Ar labels
1483is a comma separated list of numeric flow labels.
1484.It Cm frag
1485Matches packets that are fragments and not the first
1486fragment of an IP datagram.
1487Note that these packets will not have
1488the next protocol header (e.g.\& TCP, UDP) so options that look into
1489these headers cannot match.
1490.It Cm gid Ar group
1491Matches all TCP or UDP packets sent by or received for a
1492.Ar group .
1493A
1494.Ar group
1495may be specified by name or number.
1496.It Cm jail Ar prisonID
1497Matches all TCP or UDP packets sent by or received for the
1498jail whos prison ID is
1499.Ar prisonID .
1500.It Cm icmptypes Ar types
1501Matches ICMP packets whose ICMP type is in the list
1502.Ar types .
1503The list may be specified as any combination of
1504individual types (numeric) separated by commas.
1505.Em Ranges are not allowed .
1506The supported ICMP types are:
1507.Pp
1508echo reply
1509.Pq Cm 0 ,
1510destination unreachable
1511.Pq Cm 3 ,
1512source quench
1513.Pq Cm 4 ,
1514redirect
1515.Pq Cm 5 ,
1516echo request
1517.Pq Cm 8 ,
1518router advertisement
1519.Pq Cm 9 ,
1520router solicitation
1521.Pq Cm 10 ,
1522time-to-live exceeded
1523.Pq Cm 11 ,
1524IP header bad
1525.Pq Cm 12 ,
1526timestamp request
1527.Pq Cm 13 ,
1528timestamp reply
1529.Pq Cm 14 ,
1530information request
1531.Pq Cm 15 ,
1532information reply
1533.Pq Cm 16 ,
1534address mask request
1535.Pq Cm 17
1536and address mask reply
1537.Pq Cm 18 .
1538.It Cm icmp6types Ar types
1539Matches ICMP6 packets whose ICMP6 type is in the list of
1540.Ar types .
1541The list may be specified as any combination of
1542individual types (numeric) separated by commas.
1543.Em Ranges are not allowed .
1544.It Cm in | out
1545Matches incoming or outgoing packets, respectively.
1546.Cm in
1547and
1548.Cm out
1549are mutually exclusive (in fact,
1550.Cm out
1551is implemented as
1552.Cm not in Ns No ).
1553.It Cm ipid Ar id-list
1554Matches IPv4 packets whose
1555.Cm ip_id
1556field has value included in
1557.Ar id-list ,
1558which is either a single value or a list of values or ranges
1559specified in the same way as
1560.Ar ports .
1561.It Cm iplen Ar len-list
1562Matches IP packets whose total length, including header and data, is
1563in the set
1564.Ar len-list ,
1565which is either a single value or a list of values or ranges
1566specified in the same way as
1567.Ar ports .
1568.It Cm ipoptions Ar spec
1569Matches packets whose IPv4 header contains the comma separated list of
1570options specified in
1571.Ar spec .
1572The supported IP options are:
1573.Pp
1574.Cm ssrr
1575(strict source route),
1576.Cm lsrr
1577(loose source route),
1578.Cm rr
1579(record packet route) and
1580.Cm ts
1581(timestamp).
1582The absence of a particular option may be denoted
1583with a
1584.Ql \&! .
1585.It Cm ipprecedence Ar precedence
1586Matches IPv4 packets whose precedence field is equal to
1587.Ar precedence .
1588.It Cm ipsec
1589Matches packets that have IPSEC history associated with them
1590(i.e., the packet comes encapsulated in IPSEC, the kernel
1591has IPSEC support, and can correctly decapsulate it).
1592.Pp
1593Note that specifying
1594.Cm ipsec
1595is different from specifying
1596.Cm proto Ar ipsec
1597as the latter will only look at the specific IP protocol field,
1598irrespective of IPSEC kernel support and the validity of the IPSEC data.
1599.Pp
1600Further note that this flag is silently ignored in kernels without
1601IPSEC support.
1602It does not affect rule processing when given and the
1603rules are handled as if with no
1604.Cm ipsec
1605flag.
1606.It Cm iptos Ar spec
1607Matches IPv4 packets whose
1608.Cm tos
1609field contains the comma separated list of
1610service types specified in
1611.Ar spec .
1612The supported IP types of service are:
1613.Pp
1614.Cm lowdelay
1615.Pq Dv IPTOS_LOWDELAY ,
1616.Cm throughput
1617.Pq Dv IPTOS_THROUGHPUT ,
1618.Cm reliability
1619.Pq Dv IPTOS_RELIABILITY ,
1620.Cm mincost
1621.Pq Dv IPTOS_MINCOST ,
1622.Cm congestion
1623.Pq Dv IPTOS_ECN_CE .
1624The absence of a particular type may be denoted
1625with a
1626.Ql \&! .
1627.It Cm dscp spec Ns Op , Ns Ar spec
1628Matches IPv4/IPv6 packets whose
1629.Cm DS
1630field value is contained in
1631.Ar spec
1632mask.
1633Multiple values can be specified via
1634the comma separated list.
1635Value can be one of keywords used in
1636.Cm setdscp
1637action or exact number.
1638.It Cm ipttl Ar ttl-list
1639Matches IPv4 packets whose time to live is included in
1640.Ar ttl-list ,
1641which is either a single value or a list of values or ranges
1642specified in the same way as
1643.Ar ports .
1644.It Cm ipversion Ar ver
1645Matches IP packets whose IP version field is
1646.Ar ver .
1647.It Cm keep-state Op Ar flowname
1648Upon a match, the firewall will create a dynamic rule, whose
1649default behaviour is to match bidirectional traffic between
1650source and destination IP/port using the same protocol.
1651The rule has a limited lifetime (controlled by a set of
1652.Xr sysctl 8
1653variables), and the lifetime is refreshed every time a matching
1654packet is found.
1655The
1656.Ar flowname
1657is used to assign additional to addresses, ports and protocol parameter
1658to dynamic rule. It can be used for more accurate matching by
1659.Cm check-state
1660rule.
1661The
1662.Cm default
1663keyword is special name used for compatibility with old rulesets.
1664.It Cm layer2
1665Matches only layer2 packets, i.e., those passed to
1666.Nm
1667from ether_demux() and ether_output_frame().
1668.It Cm limit Bro Cm src-addr | src-port | dst-addr | dst-port Brc Ar N Op Ar flowname
1669The firewall will only allow
1670.Ar N
1671connections with the same
1672set of parameters as specified in the rule.
1673One or more
1674of source and destination addresses and ports can be
1675specified.
1676.It Cm lookup Bro Cm dst-ip | dst-port | src-ip | src-port | uid | jail Brc Ar name
1677Search an entry in lookup table
1678.Ar name
1679that matches the field specified as argument.
1680If not found, the match fails.
1681Otherwise, the match succeeds and
1682.Cm tablearg
1683is set to the value extracted from the table.
1684.Pp
1685This option can be useful to quickly dispatch traffic based on
1686certain packet fields.
1687See the
1688.Sx LOOKUP TABLES
1689section below for more information on lookup tables.
1690.It Cm { MAC | mac } Ar dst-mac src-mac
1691Match packets with a given
1692.Ar dst-mac
1693and
1694.Ar src-mac
1695addresses, specified as the
1696.Cm any
1697keyword (matching any MAC address), or six groups of hex digits
1698separated by colons,
1699and optionally followed by a mask indicating the significant bits.
1700The mask may be specified using either of the following methods:
1701.Bl -enum -width indent
1702.It
1703A slash
1704.Pq /
1705followed by the number of significant bits.
1706For example, an address with 33 significant bits could be specified as:
1707.Pp
1708.Dl "MAC 10:20:30:40:50:60/33 any"
1709.It
1710An ampersand
1711.Pq &
1712followed by a bitmask specified as six groups of hex digits separated
1713by colons.
1714For example, an address in which the last 16 bits are significant could
1715be specified as:
1716.Pp
1717.Dl "MAC 10:20:30:40:50:60&00:00:00:00:ff:ff any"
1718.Pp
1719Note that the ampersand character has a special meaning in many shells
1720and should generally be escaped.
1721.El
1722Note that the order of MAC addresses (destination first,
1723source second) is
1724the same as on the wire, but the opposite of the one used for
1725IP addresses.
1726.It Cm mac-type Ar mac-type
1727Matches packets whose Ethernet Type field
1728corresponds to one of those specified as argument.
1729.Ar mac-type
1730is specified in the same way as
1731.Cm port numbers
1732(i.e., one or more comma-separated single values or ranges).
1733You can use symbolic names for known values such as
1734.Em vlan , ipv4, ipv6 .
1735Values can be entered as decimal or hexadecimal (if prefixed by 0x),
1736and they are always printed as hexadecimal (unless the
1737.Cm -N
1738option is used, in which case symbolic resolution will be attempted).
1739.It Cm proto Ar protocol
1740Matches packets with the corresponding IP protocol.
1741.It Cm recv | xmit | via Brq Ar ifX | Ar if Ns Cm * | Ar table Ns Po Ar name Ns Oo , Ns Ar value Oc Pc | Ar ipno | Ar any
1742Matches packets received, transmitted or going through,
1743respectively, the interface specified by exact name
1744.Po Ar ifX Pc ,
1745by device name
1746.Po Ar if* Pc ,
1747by IP address, or through some interface.
1748Table
1749.Ar name
1750may be used to match interface by its kernel ifindex.
1751See the
1752.Sx LOOKUP TABLES
1753section below for more information on lookup tables.
1754.Pp
1755The
1756.Cm via
1757keyword causes the interface to always be checked.
1758If
1759.Cm recv
1760or
1761.Cm xmit
1762is used instead of
1763.Cm via ,
1764then only the receive or transmit interface (respectively)
1765is checked.
1766By specifying both, it is possible to match packets based on
1767both receive and transmit interface, e.g.:
1768.Pp
1769.Dl "ipfw add deny ip from any to any out recv ed0 xmit ed1"
1770.Pp
1771The
1772.Cm recv
1773interface can be tested on either incoming or outgoing packets,
1774while the
1775.Cm xmit
1776interface can only be tested on outgoing packets.
1777So
1778.Cm out
1779is required (and
1780.Cm in
1781is invalid) whenever
1782.Cm xmit
1783is used.
1784.Pp
1785A packet might not have a receive or transmit interface: packets
1786originating from the local host have no receive interface,
1787while packets destined for the local host have no transmit
1788interface.
1789.It Cm setup
1790Matches TCP packets that have the SYN bit set but no ACK bit.
1791This is the short form of
1792.Dq Li tcpflags\ syn,!ack .
1793.It Cm sockarg
1794Matches packets that are associated to a local socket and
1795for which the SO_USER_COOKIE socket option has been set
1796to a non-zero value.
1797As a side effect, the value of the
1798option is made available as
1799.Cm tablearg
1800value, which in turn can be used as
1801.Cm skipto
1802or
1803.Cm pipe
1804number.
1805.It Cm src-ip Ar ip-address
1806Matches IPv4 packets whose source IP is one of the address(es)
1807specified as an argument.
1808.It Cm src-ip6 Ar ip6-address
1809Matches IPv6 packets whose source IP is one of the address(es)
1810specified as an argument.
1811.It Cm src-port Ar ports
1812Matches IP packets whose source port is one of the port(s)
1813specified as argument.
1814.It Cm tagged Ar tag-list
1815Matches packets whose tags are included in
1816.Ar tag-list ,
1817which is either a single value or a list of values or ranges
1818specified in the same way as
1819.Ar ports .
1820Tags can be applied to the packet using
1821.Cm tag
1822rule action parameter (see it's description for details on tags).
1823.It Cm tcpack Ar ack
1824TCP packets only.
1825Match if the TCP header acknowledgment number field is set to
1826.Ar ack .
1827.It Cm tcpdatalen Ar tcpdatalen-list
1828Matches TCP packets whose length of TCP data is
1829.Ar tcpdatalen-list ,
1830which is either a single value or a list of values or ranges
1831specified in the same way as
1832.Ar ports .
1833.It Cm tcpflags Ar spec
1834TCP packets only.
1835Match if the TCP header contains the comma separated list of
1836flags specified in
1837.Ar spec .
1838The supported TCP flags are:
1839.Pp
1840.Cm fin ,
1841.Cm syn ,
1842.Cm rst ,
1843.Cm psh ,
1844.Cm ack
1845and
1846.Cm urg .
1847The absence of a particular flag may be denoted
1848with a
1849.Ql \&! .
1850A rule which contains a
1851.Cm tcpflags
1852specification can never match a fragmented packet which has
1853a non-zero offset.
1854See the
1855.Cm frag
1856option for details on matching fragmented packets.
1857.It Cm tcpseq Ar seq
1858TCP packets only.
1859Match if the TCP header sequence number field is set to
1860.Ar seq .
1861.It Cm tcpwin Ar tcpwin-list
1862Matches TCP packets whose  header window field is set to
1863.Ar tcpwin-list ,
1864which is either a single value or a list of values or ranges
1865specified in the same way as
1866.Ar ports .
1867.It Cm tcpoptions Ar spec
1868TCP packets only.
1869Match if the TCP header contains the comma separated list of
1870options specified in
1871.Ar spec .
1872The supported TCP options are:
1873.Pp
1874.Cm mss
1875(maximum segment size),
1876.Cm window
1877(tcp window advertisement),
1878.Cm sack
1879(selective ack),
1880.Cm ts
1881(rfc1323 timestamp) and
1882.Cm cc
1883(rfc1644 t/tcp connection count).
1884The absence of a particular option may be denoted
1885with a
1886.Ql \&! .
1887.It Cm uid Ar user
1888Match all TCP or UDP packets sent by or received for a
1889.Ar user .
1890A
1891.Ar user
1892may be matched by name or identification number.
1893.It Cm verrevpath
1894For incoming packets,
1895a routing table lookup is done on the packet's source address.
1896If the interface on which the packet entered the system matches the
1897outgoing interface for the route,
1898the packet matches.
1899If the interfaces do not match up,
1900the packet does not match.
1901All outgoing packets or packets with no incoming interface match.
1902.Pp
1903The name and functionality of the option is intentionally similar to
1904the Cisco IOS command:
1905.Pp
1906.Dl ip verify unicast reverse-path
1907.Pp
1908This option can be used to make anti-spoofing rules to reject all
1909packets with source addresses not from this interface.
1910See also the option
1911.Cm antispoof .
1912.It Cm versrcreach
1913For incoming packets,
1914a routing table lookup is done on the packet's source address.
1915If a route to the source address exists, but not the default route
1916or a blackhole/reject route, the packet matches.
1917Otherwise, the packet does not match.
1918All outgoing packets match.
1919.Pp
1920The name and functionality of the option is intentionally similar to
1921the Cisco IOS command:
1922.Pp
1923.Dl ip verify unicast source reachable-via any
1924.Pp
1925This option can be used to make anti-spoofing rules to reject all
1926packets whose source address is unreachable.
1927.It Cm antispoof
1928For incoming packets, the packet's source address is checked if it
1929belongs to a directly connected network.
1930If the network is directly connected, then the interface the packet
1931came on in is compared to the interface the network is connected to.
1932When incoming interface and directly connected interface are not the
1933same, the packet does not match.
1934Otherwise, the packet does match.
1935All outgoing packets match.
1936.Pp
1937This option can be used to make anti-spoofing rules to reject all
1938packets that pretend to be from a directly connected network but do
1939not come in through that interface.
1940This option is similar to but more restricted than
1941.Cm verrevpath
1942because it engages only on packets with source addresses of directly
1943connected networks instead of all source addresses.
1944.El
1945.Sh LOOKUP TABLES
1946Lookup tables are useful to handle large sparse sets of
1947addresses or other search keys (e.g., ports, jail IDs, interface names).
1948In the rest of this section we will use the term ``key''.
1949Table name needs to match the following spec:
1950.Ar table-name .
1951Tables with the same name can be created in different
1952.Ar sets .
1953However, rule links to the tables in
1954.Ar set 0
1955by default.
1956This behavior can be controlled by
1957.Va net.inet.ip.fw.tables_sets
1958variable.
1959See the
1960.Sx SETS OF RULES
1961section for more information.
1962There may be up to 65535 different lookup tables.
1963.Pp
1964The following table types are supported:
1965.Bl -tag -width indent
1966.It Ar table-type : Ar addr | iface | number | flow
1967.It Ar table-key : Ar addr Ns Oo / Ns Ar masklen Oc | iface-name | number | flow-spec
1968.It Ar flow-spec : Ar flow-field Ns Op , Ns Ar flow-spec
1969.It Ar flow-field : src-ip | proto | src-port | dst-ip | dst-port
1970.It Cm addr
1971matches IPv4 or IPv6 address.
1972Each entry is represented by an
1973.Ar addr Ns Op / Ns Ar masklen
1974and will match all addresses with base
1975.Ar addr
1976(specified as an IPv4/IPv6 address, or a hostname) and mask width of
1977.Ar masklen
1978bits.
1979If
1980.Ar masklen
1981is not specified, it defaults to 32 for IPv4 and 128 for IPv6.
1982When looking up an IP address in a table, the most specific
1983entry will match.
1984.It Cm iface
1985matches interface names.
1986Each entry is represented by string treated as interface name.
1987Wildcards are not supported.
1988.It Cm number
1989maches protocol ports, uids/gids or jail IDs.
1990Each entry is represented by 32-bit unsigned integer.
1991Ranges are not supported.
1992.It Cm flow
1993Matches packet fields specified by
1994.Ar flow
1995type suboptions with table entries.
1996.El
1997.Pp
1998Tables require explicit creation via
1999.Cm create
2000before use.
2001.Pp
2002The following creation options are supported:
2003.Bl -tag -width indent
2004.It Ar create-options : Ar create-option | create-options
2005.It Ar create-option : Cm type Ar table-type | Cm valtype Ar value-mask | Cm algo Ar algo-desc |
2006.Cm limit Ar number | Cm locked
2007.It Cm type
2008Table key type.
2009.It Cm valtype
2010Table value mask.
2011.It Cm algo
2012Table algorithm to use (see below).
2013.It Cm limit
2014Maximum number of items that may be inserted into table.
2015.It Cm locked
2016Restrict any table modifications.
2017.El
2018.Pp
2019Some of these options may be modified later via
2020.Cm modify
2021keyword.
2022The following options can be changed:
2023.Bl -tag -width indent
2024.It Ar modify-options : Ar modify-option | modify-options
2025.It Ar modify-option : Cm limit Ar number
2026.It Cm limit
2027Alter maximum number of items that may be inserted into table.
2028.El
2029.Pp
2030Additionally, table can be locked or unlocked using
2031.Cm lock
2032or
2033.Cm unlock
2034commands.
2035.Pp
2036Tables of the same
2037.Ar type
2038can be swapped with each other using
2039.Cm swap Ar name
2040command.
2041Swap may fail if tables limits are set and data exchange
2042would result in limits hit.
2043Operation is performed atomically.
2044.Pp
2045One or more entries can be added to a table at once using
2046.Cm add
2047command.
2048Addition of all items are performed atomically.
2049By default, error in addition of one entry does not influence
2050addition of other entries. However, non-zero error code is returned
2051in that case.
2052Special
2053.Cm atomic
2054keyword may be specified before
2055.Cm add
2056to indicate all-or-none add request.
2057.Pp
2058One or more entries can be removed from a table at once using
2059.Cm delete
2060command.
2061By default, error in removal of one entry does not influence
2062removing of other entries. However, non-zero error code is returned
2063in that case.
2064.Pp
2065It may be possible to check what entry will be found on particular
2066.Ar table-key
2067using
2068.Cm lookup
2069.Ar table-key
2070command.
2071This functionality is optional and may be unsupported in some algorithms.
2072.Pp
2073The following operations can be performed on
2074.Ar one
2075or
2076.Cm all
2077tables:
2078.Bl -tag -width indent
2079.It Cm list
2080List all entries.
2081.It Cm flush
2082Removes all entries.
2083.It Cm info
2084Shows generic table information.
2085.It Cm detail
2086Shows generic table information and algo-specific data.
2087.El
2088.Pp
2089The following lookup algorithms are supported:
2090.Bl -tag -width indent
2091.It Ar algo-desc : algo-name | "algo-name algo-data"
2092.It Ar algo-name: Ar addr:radix | addr:hash | iface:array | number:array | flow:hash
2093.It Cm addr:radix
2094Separate Radix trees for IPv4 and IPv6, the same way as the routing table (see
2095.Xr route 4 ) .
2096Default choice for
2097.Ar addr
2098type.
2099.It Cm addr:hash
2100Separate auto-growing hashes for IPv4 and IPv6.
2101Accepts entries with the same mask length specified initially via
2102.Cm "addr:hash masks=/v4,/v6"
2103algorithm creation options.
2104Assume /32 and /128 masks by default.
2105Search removes host bits (according to mask) from supplied address and checks
2106resulting key in appropriate hash.
2107Mostly optimized for /64 and byte-ranged IPv6 masks.
2108.It Cm iface:array
2109Array storing sorted indexes for entries which are presented in the system.
2110Optimized for very fast lookup.
2111.It Cm number:array
2112Array storing sorted u32 numbers.
2113.It Cm flow:hash
2114Auto-growing hash storing flow entries.
2115Search calculates hash on required packet fields and searches for matching
2116entries in selected bucket.
2117.El
2118.Pp
2119The
2120.Cm tablearg
2121feature provides the ability to use a value, looked up in the table, as
2122the argument for a rule action, action parameter or rule option.
2123This can significantly reduce number of rules in some configurations.
2124If two tables are used in a rule, the result of the second (destination)
2125is used.
2126.Pp
2127Each record may hold one or more values according to
2128.Ar value-mask .
2129This mask is set on table creation via
2130.Cm valtype
2131option.
2132The following value types are supported:
2133.Bl -tag -width indent
2134.It Ar value-mask : Ar value-type Ns Op , Ns Ar value-mask
2135.It Ar value-type : Ar skipto | pipe | fib | nat | dscp | tag | divert |
2136.Ar netgraph | limit | ipv4
2137.It Cm skipto
2138rule number to jump to.
2139.It Cm pipe
2140Pipe number to use.
2141.It Cm fib
2142fib number to match/set.
2143.It Cm nat
2144nat number to jump to.
2145.It Cm dscp
2146dscp value to match/set.
2147.It Cm tag
2148tag number to match/set.
2149.It Cm divert
2150port number to divert traffic to.
2151.It Cm netgraph
2152hook number to move packet to.
2153.It Cm limit
2154maximum number of connections.
2155.It Cm ipv4
2156IPv4 nexthop to fwd packets to.
2157.It Cm ipv6
2158IPv6 nexthop to fwd packets to.
2159.El
2160.Pp
2161The
2162.Cm tablearg
2163argument can be used with the following actions:
2164.Cm nat, pipe , queue, divert, tee, netgraph, ngtee, fwd, skipto, setfib,
2165action parameters:
2166.Cm tag, untag,
2167rule options:
2168.Cm limit, tagged.
2169.Pp
2170When used with the
2171.Cm skipto
2172action, the user should be aware that the code will walk the ruleset
2173up to a rule equal to, or past, the given number.
2174.Pp
2175See the
2176.Sx EXAMPLES
2177Section for example usage of tables and the tablearg keyword.
2178.Sh SETS OF RULES
2179Each rule or table belongs to one of 32 different
2180.Em sets
2181, numbered 0 to 31.
2182Set 31 is reserved for the default rule.
2183.Pp
2184By default, rules or tables are put in set 0, unless you use the
2185.Cm set N
2186attribute when adding a new rule or table.
2187Sets can be individually and atomically enabled or disabled,
2188so this mechanism permits an easy way to store multiple configurations
2189of the firewall and quickly (and atomically) switch between them.
2190.Pp
2191By default, tables from set 0 are referenced when adding rule with
2192table opcodes regardless of rule set.
2193This behavior can be changed by setting
2194.Va net.inet.ip.fw.tables_set
2195variable to 1.
2196Rule's set will then be used for table references.
2197.Pp
2198The command to enable/disable sets is
2199.Bd -ragged -offset indent
2200.Nm
2201.Cm set Oo Cm disable Ar number ... Oc Op Cm enable Ar number ...
2202.Ed
2203.Pp
2204where multiple
2205.Cm enable
2206or
2207.Cm disable
2208sections can be specified.
2209Command execution is atomic on all the sets specified in the command.
2210By default, all sets are enabled.
2211.Pp
2212When you disable a set, its rules behave as if they do not exist
2213in the firewall configuration, with only one exception:
2214.Bd -ragged -offset indent
2215dynamic rules created from a rule before it had been disabled
2216will still be active until they expire.
2217In order to delete
2218dynamic rules you have to explicitly delete the parent rule
2219which generated them.
2220.Ed
2221.Pp
2222The set number of rules can be changed with the command
2223.Bd -ragged -offset indent
2224.Nm
2225.Cm set move
2226.Brq Cm rule Ar rule-number | old-set
2227.Cm to Ar new-set
2228.Ed
2229.Pp
2230Also, you can atomically swap two rulesets with the command
2231.Bd -ragged -offset indent
2232.Nm
2233.Cm set swap Ar first-set second-set
2234.Ed
2235.Pp
2236See the
2237.Sx EXAMPLES
2238Section on some possible uses of sets of rules.
2239.Sh STATEFUL FIREWALL
2240Stateful operation is a way for the firewall to dynamically
2241create rules for specific flows when packets that
2242match a given pattern are detected.
2243Support for stateful
2244operation comes through the
2245.Cm check-state , keep-state
2246and
2247.Cm limit
2248options of
2249.Nm rules .
2250.Pp
2251Dynamic rules are created when a packet matches a
2252.Cm keep-state
2253or
2254.Cm limit
2255rule, causing the creation of a
2256.Em dynamic
2257rule which will match all and only packets with
2258a given
2259.Em protocol
2260between a
2261.Em src-ip/src-port dst-ip/dst-port
2262pair of addresses
2263.Em ( src
2264and
2265.Em dst
2266are used here only to denote the initial match addresses, but they
2267are completely equivalent afterwards).
2268Rules created by
2269.Cm keep-state
2270option also have a
2271.Ar flowname
2272taken from it.
2273This name is used in matching together with addresses, ports and protocol.
2274Dynamic rules will be checked at the first
2275.Cm check-state, keep-state
2276or
2277.Cm limit
2278occurrence, and the action performed upon a match will be the same
2279as in the parent rule.
2280.Pp
2281Note that no additional attributes other than protocol and IP addresses
2282and ports and flowname are checked on dynamic rules.
2283.Pp
2284The typical use of dynamic rules is to keep a closed firewall configuration,
2285but let the first TCP SYN packet from the inside network install a
2286dynamic rule for the flow so that packets belonging to that session
2287will be allowed through the firewall:
2288.Pp
2289.Dl "ipfw add check-state OUTBOUND"
2290.Dl "ipfw add allow tcp from my-subnet to any setup keep-state OUTBOUND"
2291.Dl "ipfw add deny tcp from any to any"
2292.Pp
2293A similar approach can be used for UDP, where an UDP packet coming
2294from the inside will install a dynamic rule to let the response through
2295the firewall:
2296.Pp
2297.Dl "ipfw add check-state OUTBOUND"
2298.Dl "ipfw add allow udp from my-subnet to any keep-state OUTBOUND"
2299.Dl "ipfw add deny udp from any to any"
2300.Pp
2301Dynamic rules expire after some time, which depends on the status
2302of the flow and the setting of some
2303.Cm sysctl
2304variables.
2305See Section
2306.Sx SYSCTL VARIABLES
2307for more details.
2308For TCP sessions, dynamic rules can be instructed to periodically
2309send keepalive packets to refresh the state of the rule when it is
2310about to expire.
2311.Pp
2312See Section
2313.Sx EXAMPLES
2314for more examples on how to use dynamic rules.
2315.Sh TRAFFIC SHAPER (DUMMYNET) CONFIGURATION
2316.Nm
2317is also the user interface for the
2318.Nm dummynet
2319traffic shaper, packet scheduler and network emulator, a subsystem that
2320can artificially queue, delay or drop packets
2321emulating the behaviour of certain network links
2322or queueing systems.
2323.Pp
2324.Nm dummynet
2325operates by first using the firewall to select packets
2326using any match pattern that can be used in
2327.Nm
2328rules.
2329Matching packets are then passed to either of two
2330different objects, which implement the traffic regulation:
2331.Bl -hang -offset XXXX
2332.It Em pipe
2333A
2334.Em pipe
2335emulates a
2336.Em link
2337with given bandwidth and propagation delay,
2338driven by a FIFO scheduler and a single queue with programmable
2339queue size and packet loss rate.
2340Packets are appended to the queue as they come out from
2341.Nm ipfw ,
2342and then transferred in FIFO order to the link at the desired rate.
2343.It Em queue
2344A
2345.Em queue
2346is an abstraction used to implement packet scheduling
2347using one of several packet scheduling algorithms.
2348Packets sent to a
2349.Em queue
2350are first grouped into flows according to a mask on the 5-tuple.
2351Flows are then passed to the scheduler associated to the
2352.Em queue ,
2353and each flow uses scheduling parameters (weight and others)
2354as configured in the
2355.Em queue
2356itself.
2357A scheduler in turn is connected to an emulated link,
2358and arbitrates the link's bandwidth among backlogged flows according to
2359weights and to the features of the scheduling algorithm in use.
2360.El
2361.Pp
2362In practice,
2363.Em pipes
2364can be used to set hard limits to the bandwidth that a flow can use, whereas
2365.Em queues
2366can be used to determine how different flows share the available bandwidth.
2367.Pp
2368A graphical representation of the binding of queues,
2369flows, schedulers and links is below.
2370.Bd -literal -offset indent
2371                 (flow_mask|sched_mask)  sched_mask
2372         +---------+   weight Wx  +-------------+
2373         |         |->-[flow]-->--|             |-+
2374    -->--| QUEUE x |   ...        |             | |
2375         |         |->-[flow]-->--| SCHEDuler N | |
2376         +---------+              |             | |
2377             ...                  |             +--[LINK N]-->--
2378         +---------+   weight Wy  |             | +--[LINK N]-->--
2379         |         |->-[flow]-->--|             | |
2380    -->--| QUEUE y |   ...        |             | |
2381         |         |->-[flow]-->--|             | |
2382         +---------+              +-------------+ |
2383                                    +-------------+
2384.Ed
2385It is important to understand the role of the SCHED_MASK
2386and FLOW_MASK, which are configured through the commands
2387.Dl "ipfw sched N config mask SCHED_MASK ..."
2388and
2389.Dl "ipfw queue X config mask FLOW_MASK ..." .
2390.Pp
2391The SCHED_MASK is used to assign flows to one or more
2392scheduler instances, one for each
2393value of the packet's 5-tuple after applying SCHED_MASK.
2394As an example, using ``src-ip 0xffffff00'' creates one instance
2395for each /24 destination subnet.
2396.Pp
2397The FLOW_MASK, together with the SCHED_MASK, is used to split
2398packets into flows.
2399As an example, using
2400``src-ip 0x000000ff''
2401together with the previous SCHED_MASK makes a flow for
2402each individual source address.
2403In turn, flows for each /24
2404subnet will be sent to the same scheduler instance.
2405.Pp
2406The above diagram holds even for the
2407.Em pipe
2408case, with the only restriction that a
2409.Em pipe
2410only supports a SCHED_MASK, and forces the use of a FIFO
2411scheduler (these are for backward compatibility reasons;
2412in fact, internally, a
2413.Nm dummynet's
2414pipe is implemented exactly as above).
2415.Pp
2416There are two modes of
2417.Nm dummynet
2418operation:
2419.Dq normal
2420and
2421.Dq fast .
2422The
2423.Dq normal
2424mode tries to emulate a real link: the
2425.Nm dummynet
2426scheduler ensures that the packet will not leave the pipe faster than it
2427would on the real link with a given bandwidth.
2428The
2429.Dq fast
2430mode allows certain packets to bypass the
2431.Nm dummynet
2432scheduler (if packet flow does not exceed pipe's bandwidth).
2433This is the reason why the
2434.Dq fast
2435mode requires less CPU cycles per packet (on average) and packet latency
2436can be significantly lower in comparison to a real link with the same
2437bandwidth.
2438The default mode is
2439.Dq normal .
2440The
2441.Dq fast
2442mode can be enabled by setting the
2443.Va net.inet.ip.dummynet.io_fast
2444.Xr sysctl 8
2445variable to a non-zero value.
2446.Pp
2447.Ss PIPE, QUEUE AND SCHEDULER CONFIGURATION
2448The
2449.Em pipe ,
2450.Em queue
2451and
2452.Em scheduler
2453configuration commands are the following:
2454.Bd -ragged -offset indent
2455.Cm pipe Ar number Cm config Ar pipe-configuration
2456.Pp
2457.Cm queue Ar number Cm config Ar queue-configuration
2458.Pp
2459.Cm sched Ar number Cm config Ar sched-configuration
2460.Ed
2461.Pp
2462The following parameters can be configured for a pipe:
2463.Pp
2464.Bl -tag -width indent -compact
2465.It Cm bw Ar bandwidth | device
2466Bandwidth, measured in
2467.Sm off
2468.Op Cm K | M
2469.Brq Cm bit/s | Byte/s .
2470.Sm on
2471.Pp
2472A value of 0 (default) means unlimited bandwidth.
2473The unit must immediately follow the number, as in
2474.Pp
2475.Dl "ipfw pipe 1 config bw 300Kbit/s"
2476.Pp
2477If a device name is specified instead of a numeric value, as in
2478.Pp
2479.Dl "ipfw pipe 1 config bw tun0"
2480.Pp
2481then the transmit clock is supplied by the specified device.
2482At the moment only the
2483.Xr tun 4
2484device supports this
2485functionality, for use in conjunction with
2486.Xr ppp 8 .
2487.Pp
2488.It Cm delay Ar ms-delay
2489Propagation delay, measured in milliseconds.
2490The value is rounded to the next multiple of the clock tick
2491(typically 10ms, but it is a good practice to run kernels
2492with
2493.Dq "options HZ=1000"
2494to reduce
2495the granularity to 1ms or less).
2496The default value is 0, meaning no delay.
2497.Pp
2498.It Cm burst Ar size
2499If the data to be sent exceeds the pipe's bandwidth limit
2500(and the pipe was previously idle), up to
2501.Ar size
2502bytes of data are allowed to bypass the
2503.Nm dummynet
2504scheduler, and will be sent as fast as the physical link allows.
2505Any additional data will be transmitted at the rate specified
2506by the
2507.Nm pipe
2508bandwidth.
2509The burst size depends on how long the pipe has been idle;
2510the effective burst size is calculated as follows:
2511MAX(
2512.Ar size
2513,
2514.Nm bw
2515* pipe_idle_time).
2516.Pp
2517.It Cm profile Ar filename
2518A file specifying the additional overhead incurred in the transmission
2519of a packet on the link.
2520.Pp
2521Some link types introduce extra delays in the transmission
2522of a packet, e.g., because of MAC level framing, contention on
2523the use of the channel, MAC level retransmissions and so on.
2524From our point of view, the channel is effectively unavailable
2525for this extra time, which is constant or variable depending
2526on the link type.
2527Additionally, packets may be dropped after this
2528time (e.g., on a wireless link after too many retransmissions).
2529We can model the additional delay with an empirical curve
2530that represents its distribution.
2531.Bd -literal -offset indent
2532      cumulative probability
2533      1.0 ^
2534          |
2535      L   +-- loss-level          x
2536          |                 ******
2537          |                *
2538          |           *****
2539          |          *
2540          |        **
2541          |       *
2542          +-------*------------------->
2543                      delay
2544.Ed
2545The empirical curve may have both vertical and horizontal lines.
2546Vertical lines represent constant delay for a range of
2547probabilities.
2548Horizontal lines correspond to a discontinuity in the delay
2549distribution: the pipe will use the largest delay for a
2550given probability.
2551.Pp
2552The file format is the following, with whitespace acting as
2553a separator and '#' indicating the beginning a comment:
2554.Bl -tag -width indent
2555.It Cm name Ar identifier
2556optional name (listed by "ipfw pipe show")
2557to identify the delay distribution;
2558.It Cm bw Ar value
2559the bandwidth used for the pipe.
2560If not specified here, it must be present
2561explicitly as a configuration parameter for the pipe;
2562.It Cm loss-level Ar L
2563the probability above which packets are lost.
2564(0.0 <= L <= 1.0, default 1.0 i.e., no loss);
2565.It Cm samples Ar N
2566the number of samples used in the internal
2567representation of the curve (2..1024; default 100);
2568.It Cm "delay prob" | "prob delay"
2569One of these two lines is mandatory and defines
2570the format of the following lines with data points.
2571.It Ar XXX Ar YYY
25722 or more lines representing points in the curve,
2573with either delay or probability first, according
2574to the chosen format.
2575The unit for delay is milliseconds.
2576Data points do not need to be sorted.
2577Also, the number of actual lines can be different
2578from the value of the "samples" parameter:
2579.Nm
2580utility will sort and interpolate
2581the curve as needed.
2582.El
2583.Pp
2584Example of a profile file:
2585.Bd -literal -offset indent
2586name    bla_bla_bla
2587samples 100
2588loss-level    0.86
2589prob    delay
25900       200	# minimum overhead is 200ms
25910.5     200
25920.5     300
25930.8     1000
25940.9     1300
25951       1300
2596#configuration file end
2597.Ed
2598.El
2599.Pp
2600The following parameters can be configured for a queue:
2601.Pp
2602.Bl -tag -width indent -compact
2603.It Cm pipe Ar pipe_nr
2604Connects a queue to the specified pipe.
2605Multiple queues (with the same or different weights) can be connected to
2606the same pipe, which specifies the aggregate rate for the set of queues.
2607.Pp
2608.It Cm weight Ar weight
2609Specifies the weight to be used for flows matching this queue.
2610The weight must be in the range 1..100, and defaults to 1.
2611.El
2612.Pp
2613The following case-insensitive parameters can be configured for a
2614scheduler:
2615.Pp
2616.Bl -tag -width indent -compact
2617.It Cm type Ar {fifo | wf2q+ | rr | qfq}
2618specifies the scheduling algorithm to use.
2619.Bl -tag -width indent -compact
2620.It Cm fifo
2621is just a FIFO scheduler (which means that all packets
2622are stored in the same queue as they arrive to the scheduler).
2623FIFO has O(1) per-packet time complexity, with very low
2624constants (estimate 60-80ns on a 2GHz desktop machine)
2625but gives no service guarantees.
2626.It Cm wf2q+
2627implements the WF2Q+ algorithm, which is a Weighted Fair Queueing
2628algorithm which permits flows to share bandwidth according to
2629their weights.
2630Note that weights are not priorities; even a flow
2631with a minuscule weight will never starve.
2632WF2Q+ has O(log N) per-packet processing cost, where N is the number
2633of flows, and is the default algorithm used by previous versions
2634dummynet's queues.
2635.It Cm rr
2636implements the Deficit Round Robin algorithm, which has O(1) processing
2637costs (roughly, 100-150ns per packet)
2638and permits bandwidth allocation according to weights, but
2639with poor service guarantees.
2640.It Cm qfq
2641implements the QFQ algorithm, which is a very fast variant of
2642WF2Q+, with similar service guarantees and O(1) processing
2643costs (roughly, 200-250ns per packet).
2644.El
2645.El
2646.Pp
2647In addition to the type, all parameters allowed for a pipe can also
2648be specified for a scheduler.
2649.Pp
2650Finally, the following parameters can be configured for both
2651pipes and queues:
2652.Pp
2653.Bl -tag -width XXXX -compact
2654.It Cm buckets Ar hash-table-size
2655Specifies the size of the hash table used for storing the
2656various queues.
2657Default value is 64 controlled by the
2658.Xr sysctl 8
2659variable
2660.Va net.inet.ip.dummynet.hash_size ,
2661allowed range is 16 to 65536.
2662.Pp
2663.It Cm mask Ar mask-specifier
2664Packets sent to a given pipe or queue by an
2665.Nm
2666rule can be further classified into multiple flows, each of which is then
2667sent to a different
2668.Em dynamic
2669pipe or queue.
2670A flow identifier is constructed by masking the IP addresses,
2671ports and protocol types as specified with the
2672.Cm mask
2673options in the configuration of the pipe or queue.
2674For each different flow identifier, a new pipe or queue is created
2675with the same parameters as the original object, and matching packets
2676are sent to it.
2677.Pp
2678Thus, when
2679.Em dynamic pipes
2680are used, each flow will get the same bandwidth as defined by the pipe,
2681whereas when
2682.Em dynamic queues
2683are used, each flow will share the parent's pipe bandwidth evenly
2684with other flows generated by the same queue (note that other queues
2685with different weights might be connected to the same pipe).
2686.br
2687Available mask specifiers are a combination of one or more of the following:
2688.Pp
2689.Cm dst-ip Ar mask ,
2690.Cm dst-ip6 Ar mask ,
2691.Cm src-ip Ar mask ,
2692.Cm src-ip6 Ar mask ,
2693.Cm dst-port Ar mask ,
2694.Cm src-port Ar mask ,
2695.Cm flow-id Ar mask ,
2696.Cm proto Ar mask
2697or
2698.Cm all ,
2699.Pp
2700where the latter means all bits in all fields are significant.
2701.Pp
2702.It Cm noerror
2703When a packet is dropped by a
2704.Nm dummynet
2705queue or pipe, the error
2706is normally reported to the caller routine in the kernel, in the
2707same way as it happens when a device queue fills up.
2708Setting this
2709option reports the packet as successfully delivered, which can be
2710needed for some experimental setups where you want to simulate
2711loss or congestion at a remote router.
2712.Pp
2713.It Cm plr Ar packet-loss-rate
2714Packet loss rate.
2715Argument
2716.Ar packet-loss-rate
2717is a floating-point number between 0 and 1, with 0 meaning no
2718loss, 1 meaning 100% loss.
2719The loss rate is internally represented on 31 bits.
2720.Pp
2721.It Cm queue Brq Ar slots | size Ns Cm Kbytes
2722Queue size, in
2723.Ar slots
2724or
2725.Cm KBytes .
2726Default value is 50 slots, which
2727is the typical queue size for Ethernet devices.
2728Note that for slow speed links you should keep the queue
2729size short or your traffic might be affected by a significant
2730queueing delay.
2731E.g., 50 max-sized ethernet packets (1500 bytes) mean 600Kbit
2732or 20s of queue on a 30Kbit/s pipe.
2733Even worse effects can result if you get packets from an
2734interface with a much larger MTU, e.g.\& the loopback interface
2735with its 16KB packets.
2736The
2737.Xr sysctl 8
2738variables
2739.Em net.inet.ip.dummynet.pipe_byte_limit
2740and
2741.Em net.inet.ip.dummynet.pipe_slot_limit
2742control the maximum lengths that can be specified.
2743.Pp
2744.It Cm red | gred Ar w_q Ns / Ns Ar min_th Ns / Ns Ar max_th Ns / Ns Ar max_p
2745[ecn]
2746Make use of the RED (Random Early Detection) queue management algorithm.
2747.Ar w_q
2748and
2749.Ar max_p
2750are floating
2751point numbers between 0 and 1 (inclusive), while
2752.Ar min_th
2753and
2754.Ar max_th
2755are integer numbers specifying thresholds for queue management
2756(thresholds are computed in bytes if the queue has been defined
2757in bytes, in slots otherwise).
2758The two parameters can also be of the same value if needed. The
2759.Nm dummynet
2760also supports the gentle RED variant (gred) and ECN (Explicit Congestion
2761Notification) as optional. Three
2762.Xr sysctl 8
2763variables can be used to control the RED behaviour:
2764.Bl -tag -width indent
2765.It Va net.inet.ip.dummynet.red_lookup_depth
2766specifies the accuracy in computing the average queue
2767when the link is idle (defaults to 256, must be greater than zero)
2768.It Va net.inet.ip.dummynet.red_avg_pkt_size
2769specifies the expected average packet size (defaults to 512, must be
2770greater than zero)
2771.It Va net.inet.ip.dummynet.red_max_pkt_size
2772specifies the expected maximum packet size, only used when queue
2773thresholds are in bytes (defaults to 1500, must be greater than zero).
2774.El
2775.El
2776.Pp
2777When used with IPv6 data,
2778.Nm dummynet
2779currently has several limitations.
2780Information necessary to route link-local packets to an
2781interface is not available after processing by
2782.Nm dummynet
2783so those packets are dropped in the output path.
2784Care should be taken to ensure that link-local packets are not passed to
2785.Nm dummynet .
2786.Sh CHECKLIST
2787Here are some important points to consider when designing your
2788rules:
2789.Bl -bullet
2790.It
2791Remember that you filter both packets going
2792.Cm in
2793and
2794.Cm out .
2795Most connections need packets going in both directions.
2796.It
2797Remember to test very carefully.
2798It is a good idea to be near the console when doing this.
2799If you cannot be near the console,
2800use an auto-recovery script such as the one in
2801.Pa /usr/share/examples/ipfw/change_rules.sh .
2802.It
2803Do not forget the loopback interface.
2804.El
2805.Sh FINE POINTS
2806.Bl -bullet
2807.It
2808There are circumstances where fragmented datagrams are unconditionally
2809dropped.
2810TCP packets are dropped if they do not contain at least 20 bytes of
2811TCP header, UDP packets are dropped if they do not contain a full 8
2812byte UDP header, and ICMP packets are dropped if they do not contain
28134 bytes of ICMP header, enough to specify the ICMP type, code, and
2814checksum.
2815These packets are simply logged as
2816.Dq pullup failed
2817since there may not be enough good data in the packet to produce a
2818meaningful log entry.
2819.It
2820Another type of packet is unconditionally dropped, a TCP packet with a
2821fragment offset of one.
2822This is a valid packet, but it only has one use, to try
2823to circumvent firewalls.
2824When logging is enabled, these packets are
2825reported as being dropped by rule -1.
2826.It
2827If you are logged in over a network, loading the
2828.Xr kld 4
2829version of
2830.Nm
2831is probably not as straightforward as you would think.
2832The following command line is recommended:
2833.Bd -literal -offset indent
2834kldload ipfw && \e
2835ipfw add 32000 allow ip from any to any
2836.Ed
2837.Pp
2838Along the same lines, doing an
2839.Bd -literal -offset indent
2840ipfw flush
2841.Ed
2842.Pp
2843in similar surroundings is also a bad idea.
2844.It
2845The
2846.Nm
2847filter list may not be modified if the system security level
2848is set to 3 or higher
2849(see
2850.Xr init 8
2851for information on system security levels).
2852.El
2853.Sh PACKET DIVERSION
2854A
2855.Xr divert 4
2856socket bound to the specified port will receive all packets
2857diverted to that port.
2858If no socket is bound to the destination port, or if the divert module is
2859not loaded, or if the kernel was not compiled with divert socket support,
2860the packets are dropped.
2861.Sh NETWORK ADDRESS TRANSLATION (NAT)
2862.Nm
2863support in-kernel NAT using the kernel version of
2864.Xr libalias 3 .
2865.Pp
2866The nat configuration command is the following:
2867.Bd -ragged -offset indent
2868.Bk -words
2869.Cm nat
2870.Ar nat_number
2871.Cm config
2872.Ar nat-configuration
2873.Ek
2874.Ed
2875.Pp
2876The following parameters can be configured:
2877.Bl -tag -width indent
2878.It Cm ip Ar ip_address
2879Define an ip address to use for aliasing.
2880.It Cm if Ar nic
2881Use ip address of NIC for aliasing, dynamically changing
2882it if NIC's ip address changes.
2883.It Cm log
2884Enable logging on this nat instance.
2885.It Cm deny_in
2886Deny any incoming connection from outside world.
2887.It Cm same_ports
2888Try to leave the alias port numbers unchanged from
2889the actual local port numbers.
2890.It Cm unreg_only
2891Traffic on the local network not originating from an
2892unregistered address spaces will be ignored.
2893.It Cm reset
2894Reset table of the packet aliasing engine on address change.
2895.It Cm reverse
2896Reverse the way libalias handles aliasing.
2897.It Cm proxy_only
2898Obey transparent proxy rules only, packet aliasing is not performed.
2899.It Cm skip_global
2900Skip instance in case of global state lookup (see below).
2901.El
2902.Pp
2903Some specials value can be supplied instead of
2904.Va nat_number:
2905.Bl -tag -width indent
2906.It Cm global
2907Looks up translation state in all configured nat instances.
2908If an entry is found, packet is aliased according to that entry.
2909If no entry was found in any of the instances, packet is passed unchanged,
2910and no new entry will be created.
2911See section
2912.Sx MULTIPLE INSTANCES
2913in
2914.Xr natd 8
2915for more information.
2916.It Cm tablearg
2917Uses argument supplied in lookup table.
2918See
2919.Sx LOOKUP TABLES
2920section below for more information on lookup tables.
2921.El
2922.Pp
2923To let the packet continue after being (de)aliased, set the sysctl variable
2924.Va net.inet.ip.fw.one_pass
2925to 0.
2926For more information about aliasing modes, refer to
2927.Xr libalias 3 .
2928See Section
2929.Sx EXAMPLES
2930for some examples about nat usage.
2931.Ss REDIRECT AND LSNAT SUPPORT IN IPFW
2932Redirect and LSNAT support follow closely the syntax used in
2933.Xr natd 8 .
2934See Section
2935.Sx EXAMPLES
2936for some examples on how to do redirect and lsnat.
2937.Ss SCTP NAT SUPPORT
2938SCTP nat can be configured in a similar manner to TCP through the
2939.Nm
2940command line tool.
2941The main difference is that
2942.Nm sctp nat
2943does not do port translation.
2944Since the local and global side ports will be the same,
2945there is no need to specify both.
2946Ports are redirected as follows:
2947.Bd -ragged -offset indent
2948.Bk -words
2949.Cm nat
2950.Ar nat_number
2951.Cm config if
2952.Ar nic
2953.Cm redirect_port sctp
2954.Ar ip_address [,addr_list] {[port | port-port] [,ports]}
2955.Ek
2956.Ed
2957.Pp
2958Most
2959.Nm sctp nat
2960configuration can be done in real-time through the
2961.Xr sysctl 8
2962interface.
2963All may be changed dynamically, though the hash_table size will only
2964change for new
2965.Nm nat
2966instances.
2967See
2968.Sx SYSCTL VARIABLES
2969for more info.
2970.Sh IPv6/IPv4 NETWORK ADDRESS AND PROTOCOL TRANSLATION
2971.Nm
2972supports in-kernel IPv6/IPv4 network address and protocol translation.
2973Stateful NAT64 translation allows IPv6-only clients to contact IPv4 servers
2974using unicast TCP, UDP or ICMP protocols.
2975One or more IPv4 addresses assigned to a stateful NAT64 translator are shared
2976among serveral IPv6-only clients.
2977When stateful NAT64 is used in conjunction with DNS64, no changes are usually
2978required in the IPv6 client or the IPv4 server.
2979The kernel module
2980.Cm ipfw_nat64
2981should be loaded or kernel should have
2982.Cm options IPFIREWALL_NAT64
2983to be able use stateful NAT64 translator.
2984.Pp
2985Stateful NAT64 uses a bunch of memory for several types of objects.
2986When IPv6 client initiates connection, NAT64 translator creates a host entry
2987in the states table.
2988Each host entry has a number of ports group entries allocated on demand.
2989Ports group entries contains connection state entries.
2990There are several options to control limits and lifetime for these objects.
2991.Pp
2992NAT64 translator follows RFC7915 when does ICMPv6/ICMP translation,
2993unsupported message types will be silently dropped.
2994IPv6 needs several ICMPv6 message types to be explicitly allowed for correct
2995operation.
2996Make sure that ND6 neighbor solicitation (ICMPv6 type 135) and neighbor
2997advertisement (ICMPv6 type 136) messages will not be handled by translation
2998rules.
2999.Pp
3000After translation NAT64 translator sends packets through corresponding netisr
3001queue.
3002Thus translator host should be configured as IPv4 and IPv6 router.
3003.Pp
3004Currently both stateful and stateless NAT64 translators use Well-Known IPv6
3005Prefix
3006.Ar 64:ff9b::/96
3007to represent IPv4 addresses in the IPv6 address.
3008Thus DNS64 service and routing should be configured to use Well-Known IPv6
3009Prefix.
3010.Pp
3011The stateful NAT64 configuration command is the following:
3012.Bd -ragged -offset indent
3013.Bk -words
3014.Cm nat64lsn
3015.Ar name
3016.Cm create
3017.Ar create-options
3018.Ek
3019.Ed
3020.Pp
3021The following parameters can be configured:
3022.Bl -tag -width indent
3023.It Cm prefix4 Ar ipv4_prefix/mask
3024The IPv4 prefix with mask defines the pool of IPv4 addresses used as
3025source address after translation.
3026Stateful NAT64 module translates IPv6 source address of client to one
3027IPv4 address from this pool.
3028Note that incoming IPv4 packets that don't have corresponding state entry
3029in the states table will be dropped by translator.
3030Make sure that translation rules handle packets, destined to configured prefix.
3031.It Cm max_ports Ar number
3032Maximum number of ports reserved for upper level protocols to one IPv6 client.
3033All reserved ports are divided into chunks between supported protocols.
3034The number of connections from one IPv6 client is limited by this option.
3035Note that closed TCP connections still remain in the list of connections until
3036.Cm tcp_close_age
3037interval will not expire.
3038Default value is
3039.Ar 2048 .
3040.It Cm host_del_age Ar seconds
3041The number of seconds until the host entry for a IPv6 client will be deleted
3042and all its resources will be released due to inactivity.
3043Default value is
3044.Ar 3600 .
3045.It Cm pg_del_age Ar seconds
3046The number of seconds until a ports group with unused state entries will
3047be released.
3048Default value is
3049.Ar 900 .
3050.It Cm tcp_syn_age Ar seconds
3051The number of seconds while a state entry for TCP connection with only SYN
3052sent will be kept.
3053If TCP connection establishing will not be finished,
3054state entry will be deleted.
3055Default value is
3056.Ar 10 .
3057.It Cm tcp_est_age Ar seconds
3058The number of seconds while a state entry for established TCP connection
3059will be kept.
3060Default value is
3061.Ar 7200 .
3062.It Cm tcp_close_age Ar seconds
3063The number of seconds while a state entry for closed TCP connection
3064will be kept.
3065Keeping state entries for closed connections is needed, because IPv4 servers
3066typically keep closed connections in a TIME_WAIT state for a several minutes.
3067Since translator's IPv4 addresses are shared among all IPv6 clients,
3068new connections from the same addresses and ports may be rejected by server,
3069because these connections are still in a TIME_WAIT state.
3070Keeping them in translator's state table protects from such rejects.
3071Default value is
3072.Ar 180 .
3073.It Cm udp_age Ar seconds
3074The number of seconds while translator keeps state entry in a waiting for
3075reply to the sent UDP datagram.
3076Default value is
3077.Ar 120 .
3078.It Cm icmp_age Ar seconds
3079The number of seconds while translator keeps state entry in a waiting for
3080reply to the sent ICMP message.
3081Default value is
3082.Ar 60 .
3083.It Cm log
3084Turn on logging of all handled packets via BPF through
3085.Ar ipfwlog0
3086interface.
3087.Ar ipfwlog0
3088is a pseudo interface and can be created after a boot manually with
3089.Cm ifconfig
3090command.
3091Note that it has different purpose than
3092.Ar ipfw0
3093interface.
3094Translators sends to BPF an additional information with each packet.
3095With
3096.Cm tcpdump
3097you are able to see each handled packet before and after translation.
3098.It Cm -log
3099Turn off logging of all handled packets via BPF.
3100.El
3101.Pp
3102To inspect a states table of stateful NAT64 the following command can be used:
3103.Bd -ragged -offset indent
3104.Bk -words
3105.Cm nat64lsn
3106.Ar name
3107.Cm show Cm states
3108.Ek
3109.Ed
3110.Pp
3111.Pp
3112Stateless NAT64 translator doesn't use a states table for translation
3113and converts IPv4 addresses to IPv6 and vice versa solely based on the
3114mappings taken from configured lookup tables.
3115Since a states table doesn't used by stateless translator,
3116it can be configured to pass IPv4 clients to IPv6-only servers.
3117.Pp
3118The stateless NAT64 configuration command is the following:
3119.Bd -ragged -offset indent
3120.Bk -words
3121.Cm nat64stl
3122.Ar name
3123.Cm create
3124.Ar create-options
3125.Ek
3126.Ed
3127.Pp
3128The following parameters can be configured:
3129.Bl -tag -width indent
3130.It Cm table4 Ar table46
3131The lookup table
3132.Ar table46
3133contains mapping how IPv4 addresses should be translated to IPv6 addresses.
3134.It Cm table6 Ar table64
3135The lookup table
3136.Ar table64
3137contains mapping how IPv6 addresses should be translated to IPv4 addresses.
3138.It Cm log
3139Turn on logging of all handled packets via BPF through
3140.Ar ipfwlog0
3141interface.
3142.It Cm -log
3143Turn off logging of all handled packets via BPF.
3144.El
3145.Pp
3146Note that the behavior of stateless translator with respect to not matched
3147packets differs from stateful translator.
3148If corresponding addresses was not found in the lookup tables, the packet
3149will not be dropped and the search continues.
3150.Sh IPv6-to-IPv6 NETWORK PREFIX TRANSLATION (NPTv6)
3151.Nm
3152supports in-kernel IPv6-to-IPv6 network prefix translation as described
3153in RFC6296.
3154The kernel module
3155.Cm ipfw_nptv6
3156should be loaded or kernel should has
3157.Cm options IPFIREWALL_NPTV6
3158to be able use NPTv6 translator.
3159.Pp
3160The NPTv6 configuration command is the following:
3161.Bd -ragged -offset indent
3162.Bk -words
3163.Cm nptv6
3164.Ar name
3165.Cm create
3166.Ar create-options
3167.Ek
3168.Ed
3169.Pp
3170The following parameters can be configured:
3171.Bl -tag -width indent
3172.It Cm int_prefix Ar ipv6_prefix
3173IPv6 prefix used in internal network.
3174NPTv6 module translates source address when it matches this prefix.
3175.It Cm ext_prefix Ar ipv6_prefix
3176IPv6 prefix used in external network.
3177NPTv6 module translates destination address when it matches this prefix.
3178.It Cm prefixlen Ar length
3179The length of specified IPv6 prefixes. It must be in range from 8 to 64.
3180.El
3181.Pp
3182Note that the prefix translation rules are silently ignored when IPv6 packet
3183forwarding is disabled.
3184To enable the packet forwarding, set the sysctl variable
3185.Va net.inet6.ip6.forwarding
3186to 1.
3187.Pp
3188To let the packet continue after being translated, set the sysctl variable
3189.Va net.inet.ip.fw.one_pass
3190to 0.
3191.Sh LOADER TUNABLES
3192Tunables can be set in
3193.Xr loader 8
3194prompt,
3195.Xr loader.conf 5
3196or
3197.Xr kenv 1
3198before ipfw module gets loaded.
3199.Bl -tag -width indent
3200.It Va net.inet.ip.fw.default_to_accept: No 0
3201Defines ipfw last rule behavior.
3202This value overrides
3203.Cd "options IPFW_DEFAULT_TO_(ACCEPT|DENY)"
3204from kernel configuration file.
3205.It Va net.inet.ip.fw.tables_max: No 128
3206Defines number of tables available in ipfw.
3207Number cannot exceed 65534.
3208.El
3209.Sh SYSCTL VARIABLES
3210A set of
3211.Xr sysctl 8
3212variables controls the behaviour of the firewall and
3213associated modules
3214.Pq Nm dummynet , bridge , sctp nat .
3215These are shown below together with their default value
3216(but always check with the
3217.Xr sysctl 8
3218command what value is actually in use) and meaning:
3219.Bl -tag -width indent
3220.It Va net.inet.ip.alias.sctp.accept_global_ootb_addip: No 0
3221Defines how the
3222.Nm nat
3223responds to receipt of global OOTB ASCONF-AddIP:
3224.Bl -tag -width indent
3225.It Cm 0
3226No response (unless a partially matching association exists -
3227ports and vtags match but global address does not)
3228.It Cm 1
3229.Nm nat
3230will accept and process all OOTB global AddIP messages.
3231.El
3232.Pp
3233Option 1 should never be selected as this forms a security risk.
3234An attacker can
3235establish multiple fake associations by sending AddIP messages.
3236.It Va net.inet.ip.alias.sctp.chunk_proc_limit: No 5
3237Defines the maximum number of chunks in an SCTP packet that will be
3238parsed for a
3239packet that matches an existing association.
3240This value is enforced to be greater or equal than
3241.Cm net.inet.ip.alias.sctp.initialising_chunk_proc_limit .
3242A high value is
3243a DoS risk yet setting too low a value may result in
3244important control chunks in
3245the packet not being located and parsed.
3246.It Va net.inet.ip.alias.sctp.error_on_ootb: No 1
3247Defines when the
3248.Nm nat
3249responds to any Out-of-the-Blue (OOTB) packets with ErrorM packets.
3250An OOTB packet is a packet that arrives with no existing association
3251registered in the
3252.Nm nat
3253and is not an INIT or ASCONF-AddIP packet:
3254.Bl -tag -width indent
3255.It Cm 0
3256ErrorM is never sent in response to OOTB packets.
3257.It Cm 1
3258ErrorM is only sent to OOTB packets received on the local side.
3259.It Cm 2
3260ErrorM is sent to the local side and on the global side ONLY if there is a
3261partial match (ports and vtags match but the source global IP does not).
3262This value is only useful if the
3263.Nm nat
3264is tracking global IP addresses.
3265.It Cm 3
3266ErrorM is sent in response to all OOTB packets on both
3267the local and global side
3268(DoS risk).
3269.El
3270.Pp
3271At the moment the default is 0, since the ErrorM packet is not yet
3272supported by most SCTP stacks.
3273When it is supported, and if not tracking
3274global addresses, we recommend setting this value to 1 to allow
3275multi-homed local hosts to function with the
3276.Nm nat .
3277To track global addresses, we recommend setting this value to 2 to
3278allow global hosts to be informed when they need to (re)send an
3279ASCONF-AddIP.
3280Value 3 should never be chosen (except for debugging) as the
3281.Nm nat
3282will respond to all OOTB global packets (a DoS risk).
3283.It Va net.inet.ip.alias.sctp.hashtable_size: No 2003
3284Size of hash tables used for
3285.Nm nat
3286lookups (100 < prime_number > 1000001).
3287This value sets the
3288.Nm hash table
3289size for any future created
3290.Nm nat
3291instance and therefore must be set prior to creating a
3292.Nm nat
3293instance.
3294The table sizes may be changed to suit specific needs.
3295If there will be few
3296concurrent associations, and memory is scarce, you may make these smaller.
3297If there will be many thousands (or millions) of concurrent associations, you
3298should make these larger.
3299A prime number is best for the table size.
3300The sysctl
3301update function will adjust your input value to the next highest prime number.
3302.It Va net.inet.ip.alias.sctp.holddown_time:  No 0
3303Hold association in table for this many seconds after receiving a
3304SHUTDOWN-COMPLETE.
3305This allows endpoints to correct shutdown gracefully if a
3306shutdown_complete is lost and retransmissions are required.
3307.It Va net.inet.ip.alias.sctp.init_timer: No 15
3308Timeout value while waiting for (INIT-ACK|AddIP-ACK).
3309This value cannot be 0.
3310.It Va net.inet.ip.alias.sctp.initialising_chunk_proc_limit: No 2
3311Defines the maximum number of chunks in an SCTP packet that will be parsed when
3312no existing association exists that matches that packet.
3313Ideally this packet
3314will only be an INIT or ASCONF-AddIP packet.
3315A higher value may become a DoS
3316risk as malformed packets can consume processing resources.
3317.It Va net.inet.ip.alias.sctp.param_proc_limit: No 25
3318Defines the maximum number of parameters within a chunk that will be
3319parsed in a
3320packet.
3321As for other similar sysctl variables, larger values pose a DoS risk.
3322.It Va net.inet.ip.alias.sctp.log_level: No 0
3323Level of detail in the system log messages (0 \- minimal, 1 \- event,
33242 \- info, 3 \- detail, 4 \- debug, 5 \- max debug).
3325May be a good
3326option in high loss environments.
3327.It Va net.inet.ip.alias.sctp.shutdown_time: No 15
3328Timeout value while waiting for SHUTDOWN-COMPLETE.
3329This value cannot be 0.
3330.It Va net.inet.ip.alias.sctp.track_global_addresses: No 0
3331Enables/disables global IP address tracking within the
3332.Nm nat
3333and places an
3334upper limit on the number of addresses tracked for each association:
3335.Bl -tag -width indent
3336.It Cm 0
3337Global tracking is disabled
3338.It Cm >1
3339Enables tracking, the maximum number of addresses tracked for each
3340association is limited to this value
3341.El
3342.Pp
3343This variable is fully dynamic, the new value will be adopted for all newly
3344arriving associations, existing associations are treated
3345as they were previously.
3346Global tracking will decrease the number of collisions within the
3347.Nm nat
3348at a cost
3349of increased processing load, memory usage, complexity, and possible
3350.Nm nat
3351state
3352problems in complex networks with multiple
3353.Nm nats .
3354We recommend not tracking
3355global IP addresses, this will still result in a fully functional
3356.Nm nat .
3357.It Va net.inet.ip.alias.sctp.up_timer: No 300
3358Timeout value to keep an association up with no traffic.
3359This value cannot be 0.
3360.It Va net.inet.ip.dummynet.expire : No 1
3361Lazily delete dynamic pipes/queue once they have no pending traffic.
3362You can disable this by setting the variable to 0, in which case
3363the pipes/queues will only be deleted when the threshold is reached.
3364.It Va net.inet.ip.dummynet.hash_size : No 64
3365Default size of the hash table used for dynamic pipes/queues.
3366This value is used when no
3367.Cm buckets
3368option is specified when configuring a pipe/queue.
3369.It Va net.inet.ip.dummynet.io_fast : No 0
3370If set to a non-zero value,
3371the
3372.Dq fast
3373mode of
3374.Nm dummynet
3375operation (see above) is enabled.
3376.It Va net.inet.ip.dummynet.io_pkt
3377Number of packets passed to
3378.Nm dummynet .
3379.It Va net.inet.ip.dummynet.io_pkt_drop
3380Number of packets dropped by
3381.Nm dummynet .
3382.It Va net.inet.ip.dummynet.io_pkt_fast
3383Number of packets bypassed by the
3384.Nm dummynet
3385scheduler.
3386.It Va net.inet.ip.dummynet.max_chain_len : No 16
3387Target value for the maximum number of pipes/queues in a hash bucket.
3388The product
3389.Cm max_chain_len*hash_size
3390is used to determine the threshold over which empty pipes/queues
3391will be expired even when
3392.Cm net.inet.ip.dummynet.expire=0 .
3393.It Va net.inet.ip.dummynet.red_lookup_depth : No 256
3394.It Va net.inet.ip.dummynet.red_avg_pkt_size : No 512
3395.It Va net.inet.ip.dummynet.red_max_pkt_size : No 1500
3396Parameters used in the computations of the drop probability
3397for the RED algorithm.
3398.It Va net.inet.ip.dummynet.pipe_byte_limit : No 1048576
3399.It Va net.inet.ip.dummynet.pipe_slot_limit : No 100
3400The maximum queue size that can be specified in bytes or packets.
3401These limits prevent accidental exhaustion of resources such as mbufs.
3402If you raise these limits,
3403you should make sure the system is configured so that sufficient resources
3404are available.
3405.It Va net.inet.ip.fw.autoinc_step : No 100
3406Delta between rule numbers when auto-generating them.
3407The value must be in the range 1..1000.
3408.It Va net.inet.ip.fw.curr_dyn_buckets : Va net.inet.ip.fw.dyn_buckets
3409The current number of buckets in the hash table for dynamic rules
3410(readonly).
3411.It Va net.inet.ip.fw.debug : No 1
3412Controls debugging messages produced by
3413.Nm .
3414.It Va net.inet.ip.fw.default_rule : No 65535
3415The default rule number (read-only).
3416By the design of
3417.Nm , the default rule is the last one, so its number
3418can also serve as the highest number allowed for a rule.
3419.It Va net.inet.ip.fw.dyn_buckets : No 256
3420The number of buckets in the hash table for dynamic rules.
3421Must be a power of 2, up to 65536.
3422It only takes effect when all dynamic rules have expired, so you
3423are advised to use a
3424.Cm flush
3425command to make sure that the hash table is resized.
3426.It Va net.inet.ip.fw.dyn_count : No 3
3427Current number of dynamic rules
3428(read-only).
3429.It Va net.inet.ip.fw.dyn_keepalive : No 1
3430Enables generation of keepalive packets for
3431.Cm keep-state
3432rules on TCP sessions.
3433A keepalive is generated to both
3434sides of the connection every 5 seconds for the last 20
3435seconds of the lifetime of the rule.
3436.It Va net.inet.ip.fw.dyn_max : No 8192
3437Maximum number of dynamic rules.
3438When you hit this limit, no more dynamic rules can be
3439installed until old ones expire.
3440.It Va net.inet.ip.fw.dyn_ack_lifetime : No 300
3441.It Va net.inet.ip.fw.dyn_syn_lifetime : No 20
3442.It Va net.inet.ip.fw.dyn_fin_lifetime : No 1
3443.It Va net.inet.ip.fw.dyn_rst_lifetime : No 1
3444.It Va net.inet.ip.fw.dyn_udp_lifetime : No 5
3445.It Va net.inet.ip.fw.dyn_short_lifetime : No 30
3446These variables control the lifetime, in seconds, of dynamic
3447rules.
3448Upon the initial SYN exchange the lifetime is kept short,
3449then increased after both SYN have been seen, then decreased
3450again during the final FIN exchange or when a RST is received.
3451Both
3452.Em dyn_fin_lifetime
3453and
3454.Em dyn_rst_lifetime
3455must be strictly lower than 5 seconds, the period of
3456repetition of keepalives.
3457The firewall enforces that.
3458.It Va net.inet.ip.fw.dyn_keep_states: No 0
3459Keep dynamic states on rule/set deletion.
3460States are relinked to default rule (65535).
3461This can be handly for ruleset reload.
3462Turned off by default.
3463.It Va net.inet.ip.fw.enable : No 1
3464Enables the firewall.
3465Setting this variable to 0 lets you run your machine without
3466firewall even if compiled in.
3467.It Va net.inet6.ip6.fw.enable : No 1
3468provides the same functionality as above for the IPv6 case.
3469.It Va net.inet.ip.fw.one_pass : No 1
3470When set, the packet exiting from the
3471.Nm dummynet
3472pipe or from
3473.Xr ng_ipfw 4
3474node is not passed though the firewall again.
3475Otherwise, after an action, the packet is
3476reinjected into the firewall at the next rule.
3477.It Va net.inet.ip.fw.tables_max : No 128
3478Maximum number of tables.
3479.It Va net.inet.ip.fw.verbose : No 1
3480Enables verbose messages.
3481.It Va net.inet.ip.fw.verbose_limit : No 0
3482Limits the number of messages produced by a verbose firewall.
3483.It Va net.inet6.ip6.fw.deny_unknown_exthdrs : No 1
3484If enabled packets with unknown IPv6 Extension Headers will be denied.
3485.It Va net.link.ether.ipfw : No 0
3486Controls whether layer-2 packets are passed to
3487.Nm .
3488Default is no.
3489.It Va net.link.bridge.ipfw : No 0
3490Controls whether bridged packets are passed to
3491.Nm .
3492Default is no.
3493.El
3494.Sh INTERNAL DIAGNOSTICS
3495There are some commands that may be useful to understand current state
3496of certain subsystems inside kernel module.
3497These commands provide debugging output which may change without notice.
3498.Pp
3499Currently the following commands are available as
3500.Cm internal
3501sub-options:
3502.Bl -tag -width indent
3503.It Cm iflist
3504Lists all interface which are currently tracked by
3505.Nm
3506with their in-kernel status.
3507.It Cm talist
3508List all table lookup algorithms currently available.
3509.El
3510.Sh EXAMPLES
3511There are far too many possible uses of
3512.Nm
3513so this Section will only give a small set of examples.
3514.Pp
3515.Ss BASIC PACKET FILTERING
3516This command adds an entry which denies all tcp packets from
3517.Em cracker.evil.org
3518to the telnet port of
3519.Em wolf.tambov.su
3520from being forwarded by the host:
3521.Pp
3522.Dl "ipfw add deny tcp from cracker.evil.org to wolf.tambov.su telnet"
3523.Pp
3524This one disallows any connection from the entire cracker's
3525network to my host:
3526.Pp
3527.Dl "ipfw add deny ip from 123.45.67.0/24 to my.host.org"
3528.Pp
3529A first and efficient way to limit access (not using dynamic rules)
3530is the use of the following rules:
3531.Pp
3532.Dl "ipfw add allow tcp from any to any established"
3533.Dl "ipfw add allow tcp from net1 portlist1 to net2 portlist2 setup"
3534.Dl "ipfw add allow tcp from net3 portlist3 to net3 portlist3 setup"
3535.Dl "..."
3536.Dl "ipfw add deny tcp from any to any"
3537.Pp
3538The first rule will be a quick match for normal TCP packets,
3539but it will not match the initial SYN packet, which will be
3540matched by the
3541.Cm setup
3542rules only for selected source/destination pairs.
3543All other SYN packets will be rejected by the final
3544.Cm deny
3545rule.
3546.Pp
3547If you administer one or more subnets, you can take advantage
3548of the address sets and or-blocks and write extremely
3549compact rulesets which selectively enable services to blocks
3550of clients, as below:
3551.Pp
3552.Dl "goodguys=\*q{ 10.1.2.0/24{20,35,66,18} or 10.2.3.0/28{6,3,11} }\*q"
3553.Dl "badguys=\*q10.1.2.0/24{8,38,60}\*q"
3554.Dl ""
3555.Dl "ipfw add allow ip from ${goodguys} to any"
3556.Dl "ipfw add deny ip from ${badguys} to any"
3557.Dl "... normal policies ..."
3558.Pp
3559The
3560.Cm verrevpath
3561option could be used to do automated anti-spoofing by adding the
3562following to the top of a ruleset:
3563.Pp
3564.Dl "ipfw add deny ip from any to any not verrevpath in"
3565.Pp
3566This rule drops all incoming packets that appear to be coming to the
3567system on the wrong interface.
3568For example, a packet with a source
3569address belonging to a host on a protected internal network would be
3570dropped if it tried to enter the system from an external interface.
3571.Pp
3572The
3573.Cm antispoof
3574option could be used to do similar but more restricted anti-spoofing
3575by adding the following to the top of a ruleset:
3576.Pp
3577.Dl "ipfw add deny ip from any to any not antispoof in"
3578.Pp
3579This rule drops all incoming packets that appear to be coming from another
3580directly connected system but on the wrong interface.
3581For example, a packet with a source address of
3582.Li 192.168.0.0/24 ,
3583configured on
3584.Li fxp0 ,
3585but coming in on
3586.Li fxp1
3587would be dropped.
3588.Pp
3589The
3590.Cm setdscp
3591option could be used to (re)mark user traffic,
3592by adding the following to the appropriate place in ruleset:
3593.Pp
3594.Dl "ipfw add setdscp be ip from any to any dscp af11,af21"
3595.Ss DYNAMIC RULES
3596In order to protect a site from flood attacks involving fake
3597TCP packets, it is safer to use dynamic rules:
3598.Pp
3599.Dl "ipfw add check-state"
3600.Dl "ipfw add deny tcp from any to any established"
3601.Dl "ipfw add allow tcp from my-net to any setup keep-state"
3602.Pp
3603This will let the firewall install dynamic rules only for
3604those connection which start with a regular SYN packet coming
3605from the inside of our network.
3606Dynamic rules are checked when encountering the first
3607occurrence of a
3608.Cm check-state ,
3609.Cm keep-state
3610or
3611.Cm limit
3612rule.
3613A
3614.Cm check-state
3615rule should usually be placed near the beginning of the
3616ruleset to minimize the amount of work scanning the ruleset.
3617Your mileage may vary.
3618.Pp
3619To limit the number of connections a user can open
3620you can use the following type of rules:
3621.Pp
3622.Dl "ipfw add allow tcp from my-net/24 to any setup limit src-addr 10"
3623.Dl "ipfw add allow tcp from any to me setup limit src-addr 4"
3624.Pp
3625The former (assuming it runs on a gateway) will allow each host
3626on a /24 network to open at most 10 TCP connections.
3627The latter can be placed on a server to make sure that a single
3628client does not use more than 4 simultaneous connections.
3629.Pp
3630.Em BEWARE :
3631stateful rules can be subject to denial-of-service attacks
3632by a SYN-flood which opens a huge number of dynamic rules.
3633The effects of such attacks can be partially limited by
3634acting on a set of
3635.Xr sysctl 8
3636variables which control the operation of the firewall.
3637.Pp
3638Here is a good usage of the
3639.Cm list
3640command to see accounting records and timestamp information:
3641.Pp
3642.Dl ipfw -at list
3643.Pp
3644or in short form without timestamps:
3645.Pp
3646.Dl ipfw -a list
3647.Pp
3648which is equivalent to:
3649.Pp
3650.Dl ipfw show
3651.Pp
3652Next rule diverts all incoming packets from 192.168.2.0/24
3653to divert port 5000:
3654.Pp
3655.Dl ipfw divert 5000 ip from 192.168.2.0/24 to any in
3656.Ss TRAFFIC SHAPING
3657The following rules show some of the applications of
3658.Nm
3659and
3660.Nm dummynet
3661for simulations and the like.
3662.Pp
3663This rule drops random incoming packets with a probability
3664of 5%:
3665.Pp
3666.Dl "ipfw add prob 0.05 deny ip from any to any in"
3667.Pp
3668A similar effect can be achieved making use of
3669.Nm dummynet
3670pipes:
3671.Pp
3672.Dl "ipfw add pipe 10 ip from any to any"
3673.Dl "ipfw pipe 10 config plr 0.05"
3674.Pp
3675We can use pipes to artificially limit bandwidth, e.g.\& on a
3676machine acting as a router, if we want to limit traffic from
3677local clients on 192.168.2.0/24 we do:
3678.Pp
3679.Dl "ipfw add pipe 1 ip from 192.168.2.0/24 to any out"
3680.Dl "ipfw pipe 1 config bw 300Kbit/s queue 50KBytes"
3681.Pp
3682note that we use the
3683.Cm out
3684modifier so that the rule is not used twice.
3685Remember in fact that
3686.Nm
3687rules are checked both on incoming and outgoing packets.
3688.Pp
3689Should we want to simulate a bidirectional link with bandwidth
3690limitations, the correct way is the following:
3691.Pp
3692.Dl "ipfw add pipe 1 ip from any to any out"
3693.Dl "ipfw add pipe 2 ip from any to any in"
3694.Dl "ipfw pipe 1 config bw 64Kbit/s queue 10Kbytes"
3695.Dl "ipfw pipe 2 config bw 64Kbit/s queue 10Kbytes"
3696.Pp
3697The above can be very useful, e.g.\& if you want to see how
3698your fancy Web page will look for a residential user who
3699is connected only through a slow link.
3700You should not use only one pipe for both directions, unless
3701you want to simulate a half-duplex medium (e.g.\& AppleTalk,
3702Ethernet, IRDA).
3703It is not necessary that both pipes have the same configuration,
3704so we can also simulate asymmetric links.
3705.Pp
3706Should we want to verify network performance with the RED queue
3707management algorithm:
3708.Pp
3709.Dl "ipfw add pipe 1 ip from any to any"
3710.Dl "ipfw pipe 1 config bw 500Kbit/s queue 100 red 0.002/30/80/0.1"
3711.Pp
3712Another typical application of the traffic shaper is to
3713introduce some delay in the communication.
3714This can significantly affect applications which do a lot of Remote
3715Procedure Calls, and where the round-trip-time of the
3716connection often becomes a limiting factor much more than
3717bandwidth:
3718.Pp
3719.Dl "ipfw add pipe 1 ip from any to any out"
3720.Dl "ipfw add pipe 2 ip from any to any in"
3721.Dl "ipfw pipe 1 config delay 250ms bw 1Mbit/s"
3722.Dl "ipfw pipe 2 config delay 250ms bw 1Mbit/s"
3723.Pp
3724Per-flow queueing can be useful for a variety of purposes.
3725A very simple one is counting traffic:
3726.Pp
3727.Dl "ipfw add pipe 1 tcp from any to any"
3728.Dl "ipfw add pipe 1 udp from any to any"
3729.Dl "ipfw add pipe 1 ip from any to any"
3730.Dl "ipfw pipe 1 config mask all"
3731.Pp
3732The above set of rules will create queues (and collect
3733statistics) for all traffic.
3734Because the pipes have no limitations, the only effect is
3735collecting statistics.
3736Note that we need 3 rules, not just the last one, because
3737when
3738.Nm
3739tries to match IP packets it will not consider ports, so we
3740would not see connections on separate ports as different
3741ones.
3742.Pp
3743A more sophisticated example is limiting the outbound traffic
3744on a net with per-host limits, rather than per-network limits:
3745.Pp
3746.Dl "ipfw add pipe 1 ip from 192.168.2.0/24 to any out"
3747.Dl "ipfw add pipe 2 ip from any to 192.168.2.0/24 in"
3748.Dl "ipfw pipe 1 config mask src-ip 0x000000ff bw 200Kbit/s queue 20Kbytes"
3749.Dl "ipfw pipe 2 config mask dst-ip 0x000000ff bw 200Kbit/s queue 20Kbytes"
3750.Ss LOOKUP TABLES
3751In the following example, we need to create several traffic bandwidth
3752classes and we need different hosts/networks to fall into different classes.
3753We create one pipe for each class and configure them accordingly.
3754Then we create a single table and fill it with IP subnets and addresses.
3755For each subnet/host we set the argument equal to the number of the pipe
3756that it should use.
3757Then we classify traffic using a single rule:
3758.Pp
3759.Dl "ipfw pipe 1 config bw 1000Kbyte/s"
3760.Dl "ipfw pipe 4 config bw 4000Kbyte/s"
3761.Dl "..."
3762.Dl "ipfw table T1 create type addr"
3763.Dl "ipfw table T1 add 192.168.2.0/24 1"
3764.Dl "ipfw table T1 add 192.168.0.0/27 4"
3765.Dl "ipfw table T1 add 192.168.0.2 1"
3766.Dl "..."
3767.Dl "ipfw add pipe tablearg ip from 'table(T1)' to any"
3768.Pp
3769Using the
3770.Cm fwd
3771action, the table entries may include hostnames and IP addresses.
3772.Pp
3773.Dl "ipfw table T2 create type addr ftype ip"
3774.Dl "ipfw table T2 add 192.168.2.0/24 10.23.2.1"
3775.Dl "ipfw table T21 add 192.168.0.0/27 router1.dmz"
3776.Dl "..."
3777.Dl "ipfw add 100 fwd tablearg ip from any to table(1)"
3778.Pp
3779In the following example per-interface firewall is created:
3780.Pp
3781.Dl "ipfw table IN create type iface valtype skipto,fib"
3782.Dl "ipfw table IN add vlan20 12000,12"
3783.Dl "ipfw table IN add vlan30 13000,13"
3784.Dl "ipfw table OUT create type iface valtype skipto"
3785.Dl "ipfw table OUT add vlan20 22000"
3786.Dl "ipfw table OUT add vlan30 23000"
3787.Dl ".."
3788.Dl "ipfw add 100 ipfw setfib tablearg ip from any to any recv 'table(IN)' in"
3789.Dl "ipfw add 200 ipfw skipto tablearg ip from any to any recv 'table(IN)' in"
3790.Dl "ipfw add 300 ipfw skipto tablearg ip from any to any xmit 'table(OUT)' out"
3791.Pp
3792The following example illustrate usage of flow tables:
3793.Pp
3794.Dl "ipfw table fl create type flow:flow:src-ip,proto,dst-ip,dst-port"
3795.Dl "ipfw table fl add 2a02:6b8:77::88,tcp,2a02:6b8:77::99,80 11"
3796.Dl "ipfw table fl add 10.0.0.1,udp,10.0.0.2,53 12"
3797.Dl ".."
3798.Dl "ipfw add 100 allow ip from any to any flow 'table(fl,11)' recv ix0"
3799.Ss SETS OF RULES
3800To add a set of rules atomically, e.g.\& set 18:
3801.Pp
3802.Dl "ipfw set disable 18"
3803.Dl "ipfw add NN set 18 ...         # repeat as needed"
3804.Dl "ipfw set enable 18"
3805.Pp
3806To delete a set of rules atomically the command is simply:
3807.Pp
3808.Dl "ipfw delete set 18"
3809.Pp
3810To test a ruleset and disable it and regain control if something goes wrong:
3811.Pp
3812.Dl "ipfw set disable 18"
3813.Dl "ipfw add NN set 18 ...         # repeat as needed"
3814.Dl "ipfw set enable 18; echo done; sleep 30 && ipfw set disable 18"
3815.Pp
3816Here if everything goes well, you press control-C before the "sleep"
3817terminates, and your ruleset will be left active.
3818Otherwise, e.g.\& if
3819you cannot access your box, the ruleset will be disabled after
3820the sleep terminates thus restoring the previous situation.
3821.Pp
3822To show rules of the specific set:
3823.Pp
3824.Dl "ipfw set 18 show"
3825.Pp
3826To show rules of the disabled set:
3827.Pp
3828.Dl "ipfw -S set 18 show"
3829.Pp
3830To clear a specific rule counters of the specific set:
3831.Pp
3832.Dl "ipfw set 18 zero NN"
3833.Pp
3834To delete a specific rule of the specific set:
3835.Pp
3836.Dl "ipfw set 18 delete NN"
3837.Ss NAT, REDIRECT AND LSNAT
3838First redirect all the traffic to nat instance 123:
3839.Pp
3840.Dl "ipfw add nat 123 all from any to any"
3841.Pp
3842Then to configure nat instance 123 to alias all the outgoing traffic with ip
3843192.168.0.123, blocking all incoming connections, trying to keep
3844same ports on both sides, clearing aliasing table on address change
3845and keeping a log of traffic/link statistics:
3846.Pp
3847.Dl "ipfw nat 123 config ip 192.168.0.123 log deny_in reset same_ports"
3848.Pp
3849Or to change address of instance 123, aliasing table will be cleared (see
3850reset option):
3851.Pp
3852.Dl "ipfw nat 123 config ip 10.0.0.1"
3853.Pp
3854To see configuration of nat instance 123:
3855.Pp
3856.Dl "ipfw nat 123 show config"
3857.Pp
3858To show logs of all the instances in range 111-999:
3859.Pp
3860.Dl "ipfw nat 111-999 show"
3861.Pp
3862To see configurations of all instances:
3863.Pp
3864.Dl "ipfw nat show config"
3865.Pp
3866Or a redirect rule with mixed modes could looks like:
3867.Pp
3868.Dl "ipfw nat 123 config redirect_addr 10.0.0.1 10.0.0.66"
3869.Dl "			 redirect_port tcp 192.168.0.1:80 500"
3870.Dl "			 redirect_proto udp 192.168.1.43 192.168.1.1"
3871.Dl "			 redirect_addr 192.168.0.10,192.168.0.11"
3872.Dl "			 	    10.0.0.100	# LSNAT"
3873.Dl "			 redirect_port tcp 192.168.0.1:80,192.168.0.10:22"
3874.Dl "			 	    500		# LSNAT"
3875.Pp
3876or it could be split in:
3877.Pp
3878.Dl "ipfw nat 1 config redirect_addr 10.0.0.1 10.0.0.66"
3879.Dl "ipfw nat 2 config redirect_port tcp 192.168.0.1:80 500"
3880.Dl "ipfw nat 3 config redirect_proto udp 192.168.1.43 192.168.1.1"
3881.Dl "ipfw nat 4 config redirect_addr 192.168.0.10,192.168.0.11,192.168.0.12"
3882.Dl "				         10.0.0.100"
3883.Dl "ipfw nat 5 config redirect_port tcp"
3884.Dl "			192.168.0.1:80,192.168.0.10:22,192.168.0.20:25 500"
3885.Sh SEE ALSO
3886.Xr cpp 1 ,
3887.Xr m4 1 ,
3888.Xr altq 4 ,
3889.Xr divert 4 ,
3890.Xr dummynet 4 ,
3891.Xr if_bridge 4 ,
3892.Xr ip 4 ,
3893.Xr ipfirewall 4 ,
3894.Xr ng_ipfw 4 ,
3895.Xr protocols 5 ,
3896.Xr services 5 ,
3897.Xr init 8 ,
3898.Xr kldload 8 ,
3899.Xr reboot 8 ,
3900.Xr sysctl 8 ,
3901.Xr syslogd 8
3902.Sh HISTORY
3903The
3904.Nm
3905utility first appeared in
3906.Fx 2.0 .
3907.Nm dummynet
3908was introduced in
3909.Fx 2.2.8 .
3910Stateful extensions were introduced in
3911.Fx 4.0 .
3912.Nm ipfw2
3913was introduced in Summer 2002.
3914.Sh AUTHORS
3915.An Ugen J. S. Antsilevich ,
3916.An Poul-Henning Kamp ,
3917.An Alex Nash ,
3918.An Archie Cobbs ,
3919.An Luigi Rizzo .
3920.Pp
3921.An -nosplit
3922API based upon code written by
3923.An Daniel Boulet
3924for BSDI.
3925.Pp
3926Dummynet has been introduced by Luigi Rizzo in 1997-1998.
3927.Pp
3928Some early work (1999-2000) on the
3929.Nm dummynet
3930traffic shaper supported by Akamba Corp.
3931.Pp
3932The ipfw core (ipfw2) has been completely redesigned and
3933reimplemented by Luigi Rizzo in summer 2002.
3934Further
3935actions and
3936options have been added by various developer over the years.
3937.Pp
3938.An -nosplit
3939In-kernel NAT support written by
3940.An Paolo Pisati Aq Mt piso@FreeBSD.org
3941as part of a Summer of Code 2005 project.
3942.Pp
3943SCTP
3944.Nm nat
3945support has been developed by
3946.An The Centre for Advanced Internet Architectures (CAIA) Aq http://www.caia.swin.edu.au .
3947The primary developers and maintainers are David Hayes and Jason But.
3948For further information visit:
3949.Aq http://www.caia.swin.edu.au/urp/SONATA
3950.Pp
3951Delay profiles have been developed by Alessandro Cerri and
3952Luigi Rizzo, supported by the
3953European Commission within Projects Onelab and Onelab2.
3954.Sh BUGS
3955The syntax has grown over the years and sometimes it might be confusing.
3956Unfortunately, backward compatibility prevents cleaning up mistakes
3957made in the definition of the syntax.
3958.Pp
3959.Em !!! WARNING !!!
3960.Pp
3961Misconfiguring the firewall can put your computer in an unusable state,
3962possibly shutting down network services and requiring console access to
3963regain control of it.
3964.Pp
3965Incoming packet fragments diverted by
3966.Cm divert
3967are reassembled before delivery to the socket.
3968The action used on those packet is the one from the
3969rule which matches the first fragment of the packet.
3970.Pp
3971Packets diverted to userland, and then reinserted by a userland process
3972may lose various packet attributes.
3973The packet source interface name
3974will be preserved if it is shorter than 8 bytes and the userland process
3975saves and reuses the sockaddr_in
3976(as does
3977.Xr natd 8 ) ;
3978otherwise, it may be lost.
3979If a packet is reinserted in this manner, later rules may be incorrectly
3980applied, making the order of
3981.Cm divert
3982rules in the rule sequence very important.
3983.Pp
3984Dummynet drops all packets with IPv6 link-local addresses.
3985.Pp
3986Rules using
3987.Cm uid
3988or
3989.Cm gid
3990may not behave as expected.
3991In particular, incoming SYN packets may
3992have no uid or gid associated with them since they do not yet belong
3993to a TCP connection, and the uid/gid associated with a packet may not
3994be as expected if the associated process calls
3995.Xr setuid 2
3996or similar system calls.
3997.Pp
3998Rule syntax is subject to the command line environment and some patterns
3999may need to be escaped with the backslash character
4000or quoted appropriately.
4001.Pp
4002Due to the architecture of
4003.Xr libalias 3 ,
4004ipfw nat is not compatible with the TCP segmentation offloading (TSO).
4005Thus, to reliably nat your network traffic, please disable TSO
4006on your NICs using
4007.Xr ifconfig 8 .
4008.Pp
4009ICMP error messages are not implicitly matched by dynamic rules
4010for the respective conversations.
4011To avoid failures of network error detection and path MTU discovery,
4012ICMP error messages may need to be allowed explicitly through static
4013rules.
4014.Pp
4015Rules using
4016.Cm call
4017and
4018.Cm return
4019actions may lead to confusing behaviour if ruleset has mistakes,
4020and/or interaction with other subsystems (netgraph, dummynet, etc.) is used.
4021One possible case for this is packet leaving
4022.Nm
4023in subroutine on the input pass, while later on output encountering unpaired
4024.Cm return
4025first.
4026As the call stack is kept intact after input pass, packet will suddenly
4027return to the rule number used on input pass, not on output one.
4028Order of processing should be checked carefully to avoid such mistakes.
4029