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