Merge branch 'vendor/FILE'
[dragonfly.git] / usr.sbin / pfctl / pf.conf.5
1 .\"     $OpenBSD: pf.conf.5,v 1.402 2008/06/11 07:21:00 jmc Exp $
2 .\"
3 .\" Copyright (c) 2002, Daniel Hartmeier
4 .\" All rights reserved.
5 .\"
6 .\" Redistribution and use in source and binary forms, with or without
7 .\" modification, are permitted provided that the following conditions
8 .\" are met:
9 .\"
10 .\"    - Redistributions of source code must retain the above copyright
11 .\"      notice, this list of conditions and the following disclaimer.
12 .\"    - Redistributions in binary form must reproduce the above
13 .\"      copyright notice, this list of conditions and the following
14 .\"      disclaimer in the documentation and/or other materials provided
15 .\"      with the distribution.
16 .\"
17 .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 .\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 .\" LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 .\" FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 .\" COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 .\" BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 .\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 .\" CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 .\" POSSIBILITY OF SUCH DAMAGE.
29 .\"
30 .Dd January 2, 2011
31 .Dt PF.CONF 5
32 .Os
33 .Sh NAME
34 .Nm pf.conf
35 .Nd packet filter configuration file
36 .Sh DESCRIPTION
37 The
38 .Xr pf 4
39 packet filter modifies, drops or passes packets according to rules or
40 definitions specified in
41 .Nm .
42 .Sh STATEMENT ORDER
43 There are seven types of statements in
44 .Nm :
45 .Bl -tag -width xxxx
46 .It Cm Macros
47 User-defined variables may be defined and used later, simplifying
48 the configuration file.
49 Macros must be defined before they are referenced in
50 .Nm .
51 .It Cm Tables
52 Tables provide a mechanism for increasing the performance and flexibility of
53 rules with large numbers of source or destination addresses.
54 .It Cm Options
55 Options tune the behaviour of the packet filtering engine.
56 .It Cm Traffic Normalization Li (e.g.\& Em scrub )
57 Traffic normalization protects internal machines against inconsistencies
58 in Internet protocols and implementations.
59 .It Cm Queueing
60 Queueing provides rule-based bandwidth control.
61 .It Cm Translation Li (Various forms of NAT)
62 Translation rules specify how addresses are to be mapped or redirected to
63 other addresses.
64 .It Cm Packet Filtering
65 Packet filtering provides rule-based blocking or passing of packets.
66 .El
67 .Pp
68 With the exception of
69 .Cm macros
70 and
71 .Cm tables ,
72 the types of statements should be grouped and appear in
73 .Nm
74 in the order shown above, as this matches the operation of the underlying
75 packet filtering engine.
76 By default
77 .Xr pfctl 8
78 enforces this order (see
79 .Ar set require-order
80 below).
81 .Pp
82 Comments can be put anywhere in the file using a hash mark
83 .Pq Sq # ,
84 and extend to the end of the current line.
85 .Pp
86 Additional configuration files can be included with the
87 .Ic include
88 keyword, for example:
89 .Bd -literal -offset indent
90 include "/etc/pf/sub.filter.conf"
91 .Ed
92 .Sh MACROS
93 Macros can be defined that will later be expanded in context.
94 Macro names must start with a letter, and may contain letters, digits
95 and underscores.
96 Macro names may not be reserved words (for example
97 .Ar pass ,
98 .Ar in ,
99 .Ar out ) .
100 Macros are not expanded inside quotes.
101 .Pp
102 For example,
103 .Bd -literal -offset indent
104 ext_if = \&"kue0\&"
105 all_ifs = \&"{\&" $ext_if lo0 \&"}\&"
106 pass out on $ext_if from any to any
107 pass in  on $ext_if proto tcp from any to any port 25
108 .Ed
109 .Sh TABLES
110 Tables are named structures which can hold a collection of addresses and
111 networks.
112 Lookups against tables in
113 .Xr pf 4
114 are relatively fast, making a single rule with tables much more efficient,
115 in terms of
116 processor usage and memory consumption, than a large number of rules which
117 differ only in IP address (either created explicitly or automatically by rule
118 expansion).
119 .Pp
120 Tables can be used as the source or destination of filter rules,
121 .Ar scrub
122 rules
123 or
124 translation rules such as
125 .Ar nat
126 or
127 .Ar rdr
128 (see below for details on the various rule types).
129 Tables can also be used for the redirect address of
130 .Ar nat
131 and
132 .Ar rdr
133 rules and in the routing options of filter rules, but only for
134 .Ar round-robin
135 pools.
136 .Pp
137 Tables can be defined with any of the following
138 .Xr pfctl 8
139 mechanisms.
140 As with macros, reserved words may not be used as table names.
141 .Bl -tag -width "manually"
142 .It Ar manually
143 Persistent tables can be manually created with the
144 .Ar add
145 or
146 .Ar replace
147 option of
148 .Xr pfctl 8 ,
149 before or after the ruleset has been loaded.
150 .It Pa pf.conf
151 Table definitions can be placed directly in this file, and loaded at the
152 same time as other rules are loaded, atomically.
153 Table definitions inside
154 .Nm
155 use the
156 .Ar table
157 statement, and are especially useful to define non-persistent tables.
158 The contents of a pre-existing table defined without a list of addresses
159 to initialize it is not altered when
160 .Nm
161 is loaded.
162 A table initialized with the empty list,
163 .Li { } ,
164 will be cleared on load.
165 .El
166 .Pp
167 Tables may be defined with the following two attributes:
168 .Bl -tag -width persist
169 .It Ar persist
170 The
171 .Ar persist
172 flag forces the kernel to keep the table even when no rules refer to it.
173 If the flag is not set, the kernel will automatically remove the table
174 when the last rule referring to it is flushed.
175 .It Ar const
176 The
177 .Ar const
178 flag prevents the user from altering the contents of the table once it
179 has been created.
180 Without that flag,
181 .Xr pfctl 8
182 can be used to add or remove addresses from the table at any time, even
183 when running with
184 .Xr securelevel 8
185 = 2.
186 .It Ar counters
187 The
188 .Ar counters
189 flag enables per-address packet and byte counters which can be displayed with
190 .Xr pfctl 8 .
191 .El
192 .Pp
193 For example,
194 .Bd -literal -offset indent
195 table \*(Ltprivate\*(Gt const { 10/8, 172.16/12, 192.168/16 }
196 table \*(Ltbadhosts\*(Gt persist
197 block on fxp0 from { \*(Ltprivate\*(Gt, \*(Ltbadhosts\*(Gt } to any
198 .Ed
199 .Pp
200 creates a table called private, to hold RFC 1918 private network
201 blocks, and a table called badhosts, which is initially empty.
202 A filter rule is set up to block all traffic coming from addresses listed in
203 either table.
204 The private table cannot have its contents changed and the badhosts table
205 will exist even when no active filter rules reference it.
206 Addresses may later be added to the badhosts table, so that traffic from
207 these hosts can be blocked by using
208 .Bd -literal -offset indent
209 # pfctl -t badhosts -Tadd 204.92.77.111
210 .Ed
211 .Pp
212 A table can also be initialized with an address list specified in one or more
213 external files, using the following syntax:
214 .Bd -literal -offset indent
215 table \*(Ltspam\*(Gt persist file \&"/etc/spammers\&" file \&"/etc/openrelays\&"
216 block on fxp0 from \*(Ltspam\*(Gt to any
217 .Ed
218 .Pp
219 The files
220 .Pa /etc/spammers
221 and
222 .Pa /etc/openrelays
223 list IP addresses, one per line.
224 Any lines beginning with a # are treated as comments and ignored.
225 In addition to being specified by IP address, hosts may also be
226 specified by their hostname.
227 When the resolver is called to add a hostname to a table,
228 .Em all
229 resulting IPv4 and IPv6 addresses are placed into the table.
230 IP addresses can also be entered in a table by specifying a valid interface
231 name or the
232 .Em self
233 keyword, in which case all addresses assigned to the interface will be
234 added to the table.
235 .Sh OPTIONS
236 .Xr pf 4
237 may be tuned for various situations using the
238 .Ar set
239 command.
240 .Bl -tag -width xxxx
241 .It Ar set timeout
242 .Pp
243 .Bl -tag -width "src.track" -compact
244 .It Ar interval
245 Interval between purging expired states and fragments.
246 .It Ar frag
247 Seconds before an unassembled fragment is expired.
248 .It Ar src.track
249 Length of time to retain a source tracking entry after the last state
250 expires.
251 .El
252 .Pp
253 When a packet matches a stateful connection, the seconds to live for the
254 connection will be updated to that of the
255 .Ar proto.modifier
256 which corresponds to the connection state.
257 Each packet which matches this state will reset the TTL.
258 Tuning these values may improve the performance of the
259 firewall at the risk of dropping valid idle connections.
260 .Pp
261 .Bl -tag -width xxxx -compact
262 .It Ar tcp.first
263 The state after the first packet.
264 .It Ar tcp.opening
265 The state before the destination host ever sends a packet.
266 .It Ar tcp.established
267 The fully established state.
268 .It Ar tcp.closing
269 The state after the first FIN has been sent.
270 .It Ar tcp.finwait
271 The state after both FINs have been exchanged and the connection is closed.
272 Some hosts (notably web servers on Solaris) send TCP packets even after closing
273 the connection.
274 Increasing
275 .Ar tcp.finwait
276 (and possibly
277 .Ar tcp.closing )
278 can prevent blocking of such packets.
279 .It Ar tcp.closed
280 The state after one endpoint sends an RST.
281 .El
282 .Pp
283 ICMP and UDP are handled in a fashion similar to TCP, but with a much more
284 limited set of states:
285 .Pp
286 .Bl -tag -width xxxx -compact
287 .It Ar udp.first
288 The state after the first packet.
289 .It Ar udp.single
290 The state if the source host sends more than one packet but the destination
291 host has never sent one back.
292 .It Ar udp.multiple
293 The state if both hosts have sent packets.
294 .It Ar icmp.first
295 The state after the first packet.
296 .It Ar icmp.error
297 The state after an ICMP error came back in response to an ICMP packet.
298 .El
299 .Pp
300 Other protocols are handled similarly to UDP:
301 .Pp
302 .Bl -tag -width xxxx -compact
303 .It Ar other.first
304 .It Ar other.single
305 .It Ar other.multiple
306 .El
307 .Pp
308 Timeout values can be reduced adaptively as the number of state table
309 entries grows.
310 .Pp
311 .Bl -tag -width xxxx -compact
312 .It Ar adaptive.start
313 When the number of state entries exceeds this value, adaptive scaling
314 begins.
315 All timeout values are scaled linearly with factor
316 (adaptive.end - number of states) / (adaptive.end - adaptive.start).
317 .It Ar adaptive.end
318 When reaching this number of state entries, all timeout values become
319 zero, effectively purging all state entries immediately.
320 This value is used to define the scale factor, it should not actually
321 be reached (set a lower state limit, see below).
322 .El
323 .Pp
324 Adaptive timeouts are enabled by default, with an adaptive.start value
325 equal to 60% of the state limit, and an adaptive.end value equal to
326 120% of the state limit.
327 They can be disabled by setting both adaptive.start and adaptive.end to 0.
328 .Pp
329 The adaptive timeout values can be defined both globally and for each rule.
330 When used on a per-rule basis, the values relate to the number of
331 states created by the rule, otherwise to the total number of
332 states.
333 .Pp
334 For example:
335 .Bd -literal -offset indent
336 set timeout tcp.first 120
337 set timeout tcp.established 86400
338 set timeout { adaptive.start 6000, adaptive.end 12000 }
339 set limit states 10000
340 .Ed
341 .Pp
342 With 9000 state table entries, the timeout values are scaled to 50%
343 (tcp.first 60, tcp.established 43200).
344 .Pp
345 .It Ar set loginterface
346 Enable collection of packet and byte count statistics for the given interface.
347 These statistics can be viewed using
348 .Bd -literal -offset indent
349 # pfctl -s info
350 .Ed
351 .Pp
352 In this example
353 .Xr pf 4
354 collects statistics on the interface named dc0:
355 .Bd -literal -offset indent
356 set loginterface dc0
357 .Ed
358 .Pp
359 One can disable the loginterface using:
360 .Bd -literal -offset indent
361 set loginterface none
362 .Ed
363 .Pp
364 .It Ar set limit
365 Sets hard limits on the memory zones used by the packet filter.
366 See
367 .Xr zone 9
368 for an explanation of memory zones.
369 .Pp
370 For example,
371 .Bd -literal -offset indent
372 set limit states 20000
373 .Ed
374 .Pp
375 sets the maximum number of entries in the memory pool used by state table
376 entries (generated by
377 .Ar pass
378 rules which do not specify
379 .Ar no state )
380 to 20000.
381 Using
382 .Bd -literal -offset indent
383 set limit frags 20000
384 .Ed
385 .Pp
386 sets the maximum number of entries in the memory pool used for fragment
387 reassembly (generated by
388 .Ar scrub
389 rules) to 20000.
390 Using
391 .Bd -literal -offset indent
392 set limit src-nodes 2000
393 .Ed
394 .Pp
395 sets the maximum number of entries in the memory pool used for tracking
396 source IP addresses (generated by the
397 .Ar sticky-address
398 and
399 .Ar src.track
400 options) to 2000.
401 .Pp
402 sets limits on the memory pools used by tables.
403 The first limits the number of tables that can exist to 1000.
404 The second limits the overall number of addresses that can be stored
405 in tables to 100000.
406 .Pp
407 Various limits can be combined on a single line:
408 .Bd -literal -offset indent
409 set limit { states 20000, frags 20000, src-nodes 2000 }
410 .Ed
411 .Pp
412 .It Ar set ruleset-optimization
413 .Bl -tag -width xxxxxxxx -compact
414 .It Ar none
415 Disable the ruleset optimizer.
416 .It Ar basic
417 Enable basic ruleset optimization.
418 This is the default behaviour.
419 Basic ruleset optimization does four things to improve the
420 performance of ruleset evaluations:
421 .Pp
422 .Bl -enum -compact
423 .It
424 remove duplicate rules
425 .It
426 remove rules that are a subset of another rule
427 .It
428 combine multiple rules into a table when advantageous
429 .It
430 re-order the rules to improve evaluation performance
431 .El
432 .Pp
433 .It Ar profile
434 Uses the currently loaded ruleset as a feedback profile to tailor the
435 ordering of quick rules to actual network traffic.
436 .El
437 .Pp
438 It is important to note that the ruleset optimizer will modify the ruleset
439 to improve performance.
440 A side effect of the ruleset modification is that per-rule accounting
441 statistics will have different meanings than before.
442 If per-rule accounting is important for billing purposes or whatnot,
443 either the ruleset optimizer should not be used or a label field should
444 be added to all of the accounting rules to act as optimization barriers.
445 .Pp
446 Optimization can also be set as a command-line argument to
447 .Xr pfctl 8 ,
448 overriding the settings in
449 .Nm .
450 .It Ar set optimization
451 Optimize state timeouts for one of the following network environments:
452 .Pp
453 .Bl -tag -width xxxx -compact
454 .It Ar normal
455 A normal network environment.
456 Suitable for almost all networks.
457 .It Ar high-latency
458 A high-latency environment (such as a satellite connection).
459 .It Ar satellite
460 Alias for
461 .Ar high-latency .
462 .It Ar aggressive
463 Aggressively expire connections.
464 This can greatly reduce the memory usage of the firewall at the cost of
465 dropping idle connections early.
466 .It Ar conservative
467 Extremely conservative settings.
468 Avoid dropping legitimate connections at the
469 expense of greater memory utilization (possibly much greater on a busy
470 network) and slightly increased processor utilization.
471 .El
472 .Pp
473 For example:
474 .Bd -literal -offset indent
475 set optimization aggressive
476 .Ed
477 .Pp
478 .It Ar set keep-policy keep_rule
479 The
480 .Ar keep-policy
481 option sets the default state retention policy for all
482 .Ar pass
483 rules.
484 See
485 .Sx STATEFUL TRACKING OPTIONS
486 or
487 .Sx GRAMMAR
488 (keep) for format of
489 .Ar keep_rule .
490 Any
491 .Ar no Ns / Ns Ar keep Ns / Ns Ar modulate Ns / Ns Ar synproxy state
492 directives in a
493 .Ar pass
494 rule will override the default.
495 For example:
496 .Bd -literal -offset indent
497 set keep-policy keep state (pickups)
498 .Ed
499 .Pp
500 .It Ar set block-policy
501 The
502 .Ar block-policy
503 option sets the default behaviour for the packet
504 .Ar block
505 action:
506 .Pp
507 .Bl -tag -width xxxxxxxx -compact
508 .It Ar drop
509 Packet is silently dropped.
510 .It Ar return
511 A TCP RST is returned for blocked TCP packets,
512 an ICMP UNREACHABLE is returned for blocked UDP packets,
513 and all other packets are silently dropped.
514 .El
515 .Pp
516 For example:
517 .Bd -literal -offset indent
518 set block-policy return
519 .Ed
520 .It Ar set state-policy
521 The
522 .Ar state-policy
523 option sets the default behaviour for states:
524 .Pp
525 .Bl -tag -width if-bound -compact
526 .It Ar if-bound
527 States are bound to interface.
528 .It Ar floating
529 States can match packets on any interfaces (the default).
530 .El
531 .Pp
532 For example:
533 .Bd -literal -offset indent
534 set state-policy if-bound
535 .Ed
536 .It Ar set hostid
537 The 32-bit
538 .Ar hostid
539 identifies this firewall's state table entries to other firewalls
540 in a
541 .Xr pfsync 4
542 failover cluster.
543 By default the hostid is set to a pseudo-random value, however it may be
544 desirable to manually configure it, for example to more easily identify the
545 source of state table entries.
546 .Bd -literal -offset indent
547 set hostid 1
548 .Ed
549 .Pp
550 The hostid may be specified in either decimal or hexadecimal.
551 .It Ar set require-order
552 By default
553 .Xr pfctl 8
554 enforces an ordering of the statement types in the ruleset to:
555 .Em options ,
556 .Em normalization ,
557 .Em queueing ,
558 .Em translation ,
559 .Em filtering .
560 Setting this option to
561 .Ar no
562 disables this enforcement.
563 There may be non-trivial and non-obvious implications to an out of
564 order ruleset.
565 Consider carefully before disabling the order enforcement.
566 .It Ar set fingerprints
567 Load fingerprints of known operating systems from the given filename.
568 By default fingerprints of known operating systems are automatically
569 loaded from
570 .Xr pf.os 5
571 in
572 .Pa /etc
573 but can be overridden via this option.
574 Setting this option may leave a small period of time where the fingerprints
575 referenced by the currently active ruleset are inconsistent until the new
576 ruleset finishes loading.
577 .Pp
578 For example:
579 .Pp
580 .Dl set fingerprints \&"/etc/pf.os.devel\&"
581 .Pp
582 .It Ar set skip on Aq Ar ifspec
583 List interfaces for which packets should not be filtered.
584 Packets passing in or out on such interfaces are passed as if pf was
585 disabled, i.e. pf does not process them in any way.
586 This can be useful on loopback and other virtual interfaces, when
587 packet filtering is not desired and can have unexpected effects.
588 For example:
589 .Pp
590 .Dl set skip on lo0
591 .Pp
592 .It Ar set debug
593 Set the debug
594 .Ar level
595 to one of the following:
596 .Pp
597 .Bl -tag -width xxxxxxxxxxxx -compact
598 .It Ar none
599 Don't generate debug messages.
600 .It Ar urgent
601 Generate debug messages only for serious errors.
602 .It Ar misc
603 Generate debug messages for various errors.
604 .It Ar loud
605 Generate debug messages for common conditions.
606 .El
607 .El
608 .Sh TRAFFIC NORMALIZATION
609 Traffic normalization is used to sanitize packet content in such
610 a way that there are no ambiguities in packet interpretation on
611 the receiving side.
612 The normalizer does IP fragment reassembly to prevent attacks
613 that confuse intrusion detection systems by sending overlapping
614 IP fragments.
615 Packet normalization is invoked with the
616 .Ar scrub
617 directive.
618 .Pp
619 .Ar scrub
620 has the following options:
621 .Bl -tag -width xxxx
622 .It Ar no-df
623 Clears the
624 .Ar dont-fragment
625 bit from a matching IP packet.
626 Some operating systems are known to generate fragmented packets with the
627 .Ar dont-fragment
628 bit set.
629 This is particularly true with NFS.
630 .Ar Scrub
631 will drop such fragmented
632 .Ar dont-fragment
633 packets unless
634 .Ar no-df
635 is specified.
636 .Pp
637 Unfortunately some operating systems also generate their
638 .Ar dont-fragment
639 packets with a zero IP identification field.
640 Clearing the
641 .Ar dont-fragment
642 bit on packets with a zero IP ID may cause deleterious results if an
643 upstream router later fragments the packet.
644 Using the
645 .Ar random-id
646 modifier (see below) is recommended in combination with the
647 .Ar no-df
648 modifier to ensure unique IP identifiers.
649 .It Ar min-ttl Aq Ar number
650 Enforces a minimum TTL for matching IP packets.
651 .It Ar max-mss Aq Ar number
652 Enforces a maximum MSS for matching TCP packets.
653 .It Xo Ar set-tos Aq Ar string
654 .No \*(Ba Aq Ar number
655 .Xc
656 Enforces a
657 .Em TOS
658 for matching IP packets.
659 .Em TOS
660 may be
661 given as one of
662 .Ar lowdelay ,
663 .Ar throughput ,
664 .Ar reliability ,
665 or as either hex or decimal.
666 .It Ar random-id
667 Replaces the IP identification field with random values to compensate
668 for predictable values generated by many hosts.
669 This option only applies to packets that are not fragmented
670 after the optional fragment reassembly.
671 .It Ar fragment reassemble
672 Using
673 .Ar scrub
674 rules, fragments can be reassembled by normalization.
675 In this case, fragments are buffered until they form a complete
676 packet, and only the completed packet is passed on to the filter.
677 The advantage is that filter rules have to deal only with complete
678 packets, and can ignore fragments.
679 The drawback of caching fragments is the additional memory cost.
680 But the full reassembly method is the only method that currently works
681 with NAT.
682 This is the default behavior of a
683 .Ar scrub
684 rule if no fragmentation modifier is supplied.
685 .It Ar fragment crop
686 The default fragment reassembly method is expensive, hence the option
687 to crop is provided.
688 In this case,
689 .Xr pf 4
690 will track the fragments and cache a small range descriptor.
691 Duplicate fragments are dropped and overlaps are cropped.
692 Thus data will only occur once on the wire with ambiguities resolving to
693 the first occurrence.
694 Unlike the
695 .Ar fragment reassemble
696 modifier, fragments are not buffered, they are passed as soon as they
697 are received.
698 The
699 .Ar fragment crop
700 reassembly mechanism does not yet work with NAT.
701 .Pp
702 .It Ar fragment drop-ovl
703 This option is similar to the
704 .Ar fragment crop
705 modifier except that all overlapping or duplicate fragments will be
706 dropped, and all further corresponding fragments will be
707 dropped as well.
708 .It Ar reassemble tcp
709 Statefully normalizes TCP connections.
710 .Ar scrub reassemble tcp
711 rules may not have the direction (in/out) specified.
712 .Ar reassemble tcp
713 performs the following normalizations:
714 .Pp
715 .Bl -tag -width timeout -compact
716 .It ttl
717 Neither side of the connection is allowed to reduce their IP TTL.
718 An attacker may send a packet such that it reaches the firewall, affects
719 the firewall state, and expires before reaching the destination host.
720 .Ar reassemble tcp
721 will raise the TTL of all packets back up to the highest value seen on
722 the connection.
723 .It timestamp modulation
724 Modern TCP stacks will send a timestamp on every TCP packet and echo
725 the other endpoint's timestamp back to them.
726 Many operating systems will merely start the timestamp at zero when
727 first booted, and increment it several times a second.
728 The uptime of the host can be deduced by reading the timestamp and multiplying
729 by a constant.
730 Also observing several different timestamps can be used to count hosts
731 behind a NAT device.
732 And spoofing TCP packets into a connection requires knowing or guessing
733 valid timestamps.
734 Timestamps merely need to be monotonically increasing and not derived off a
735 guessable base time.
736 .Ar reassemble tcp
737 will cause
738 .Ar scrub
739 to modulate the TCP timestamps with a random number.
740 .It extended PAWS checks
741 There is a problem with TCP on long fat pipes, in that a packet might get
742 delayed for longer than it takes the connection to wrap its 32-bit sequence
743 space.
744 In such an occurrence, the old packet would be indistinguishable from a
745 new packet and would be accepted as such.
746 The solution to this is called PAWS: Protection Against Wrapped Sequence
747 numbers.
748 It protects against it by making sure the timestamp on each packet does
749 not go backwards.
750 .Ar reassemble tcp
751 also makes sure the timestamp on the packet does not go forward more
752 than the RFC allows.
753 By doing this,
754 .Xr pf 4
755 artificially extends the security of TCP sequence numbers by 10 to 18
756 bits when the host uses appropriately randomized timestamps, since a
757 blind attacker would have to guess the timestamp as well.
758 .El
759 .El
760 .Pp
761 For example,
762 .Bd -literal -offset indent
763 scrub in on $ext_if all fragment reassemble
764 .Ed
765 .Pp
766 The
767 .Ar no
768 option prefixed to a scrub rule causes matching packets to remain unscrubbed,
769 much in the same way as
770 .Ar drop quick
771 works in the packet filter (see below).
772 This mechanism should be used when it is necessary to exclude specific packets
773 from broader scrub rules.
774 .Sh QUEUEING
775 Packets can be assigned to queues for the purpose of bandwidth
776 control.
777 At least two declarations are required to configure queues, and later
778 any packet filtering rule can reference the defined queues by name.
779 During the filtering component of
780 .Nm ,
781 the last referenced
782 .Ar queue
783 name is where any packets from
784 .Ar pass
785 rules will be queued, while for
786 .Ar block
787 rules it specifies where any resulting ICMP or TCP RST
788 packets should be queued.
789 The
790 .Ar scheduler
791 defines the algorithm used to decide which packets get delayed, dropped, or
792 sent out immediately.
793 There are four
794 .Ar schedulers
795 currently supported.
796 .Bl -tag -width ".Ar fairq"
797 .It Ar cbq
798 Class Based Queueing.
799 .Ar Queues
800 attached to an interface build a tree, thus each
801 .Ar queue
802 can have further child
803 .Ar queues .
804 Each queue can have a
805 .Ar priority
806 and a
807 .Ar bandwidth
808 assigned.
809 .Ar Priority
810 mainly controls the time packets take to get sent out, while
811 .Ar bandwidth
812 has primarily effects on throughput.
813 .Ar cbq
814 achieves both partitioning and sharing of link bandwidth
815 by hierarchically structured classes.
816 Each class has its own
817 .Ar queue
818 and is assigned its share of
819 .Ar bandwidth .
820 A child class can borrow bandwidth from its parent class
821 as long as excess bandwidth is available
822 (see the option
823 .Ar borrow ,
824 below).
825 .It Ar priq
826 Priority Queueing.
827 .Ar Queues
828 are flat attached to the interface, thus,
829 .Ar queues
830 cannot have further child
831 .Ar queues .
832 Each
833 .Ar queue
834 has a unique
835 .Ar priority
836 assigned, ranging from 0 to 15.
837 Packets in the
838 .Ar queue
839 with the highest
840 .Ar priority
841 are processed first.
842 .It Ar hfsc
843 Hierarchical Fair Service Curve.
844 .Ar Queues
845 attached to an interface build a tree, thus each
846 .Ar queue
847 can have further child
848 .Ar queues .
849 Each queue can have a
850 .Ar priority
851 and a
852 .Ar bandwidth
853 assigned.
854 .Ar Priority
855 mainly controls the time packets take to get sent out, while
856 .Ar bandwidth
857 primarily affects throughput.
858 .Ar hfsc
859 supports both link-sharing and guaranteed real-time services.
860 It employs a service curve based QoS model,
861 and its unique feature is an ability to decouple
862 .Ar delay
863 and
864 .Ar bandwidth
865 allocation.
866 .It Ar fairq
867 Fair Queue.
868 .Ar Queues
869 are flat attached to the interface, thus,
870 .Ar queues
871 cannot have further child
872 .Ar queues .
873 Each queue must be given a unique
874 .Ar priority
875 and one must be marked
876 as the default queue.
877 Each queue implements a number of
878 .Ar buckets
879 (default 256) which sorts the
880 traffic based on a hash key generated by the
881 .Ar keep state
882 facility in your
883 .Ar pass
884 rules.
885 Each bucket contains a list of packets controlled by
886 .Ar qlimit .
887 In order for
888 .Ar fairq
889 to function properly,
890 .Ar keep state
891 must be enabled on most of the rule sets that route packets to the queue.
892 Any rules for which keep state is not enabled are added to the end of the
893 queue.
894 If you do not wish keep state to do TCP sequence space checks use
895 .Ar "keep state (no-pickups)"
896 or
897 .Ar "keep state (hash-only)" .
898 .Pp
899 Packet selection operates as follows:
900 The queues are scanned from highest priority to lowest priority.
901 If a queue has pending packets and has not reached its bandwidth limit the
902 scan stops and a packet is selected from that queue.
903 If a queue has reached its bandwidth limit the scan continues searching for
904 other, lower priority queues which have not.
905 If no queue is found to be
906 suitable then the highest priority queue with pending packets is used
907 regardless of whether it has reached its bandwidth limit or not.
908 .Pp
909 A
910 .Ar fairq
911 round robins between its
912 .Ar buckets ,
913 extracting one packet from each bucket.
914 This essentially prevents large backlogs of packets from high volume
915 connections from destroying the interactive response of other connections.
916 .Pp
917 The
918 .Ar bandwidth
919 parameter for a
920 .Ar fairq
921 is guaranteed minimum and more will be used if no higher priority traffic is
922 present.
923 Creating a queue with one bucket as a catch-all for
924 .Ar pass
925 rules not characterized by
926 .Ar keep state
927 is supported.
928 Such a queue serves as a basic priority queue with a bandwidth specification.
929 .El
930 .Pp
931 The interfaces on which queueing should be activated are declared using
932 the
933 .Ar altq on
934 declaration.
935 .Ar altq on
936 has the following keywords:
937 .Bl -tag -width xxxx
938 .It Aq Ar interface
939 Queueing is enabled on the named interface.
940 .It Aq Ar scheduler
941 Specifies which queueing scheduler to use.
942 Currently supported values
943 are
944 .Ar cbq
945 for Class Based Queueing,
946 .Ar priq
947 for Priority Queueing,
948 .Ar hfsc
949 for the Hierarchical Fair Service Curve scheduler, and
950 .Ar fairq
951 for the Fair Queueing.
952 .It Ar bandwidth <bw>
953 The maximum bitrate for all queues on an
954 interface may be specified using the
955 .Ar bandwidth
956 keyword.
957 The value can be specified as an absolute value or as a
958 percentage of the interface bandwidth.
959 When using an absolute value, the suffixes
960 .Ar b ,
961 .Ar Kb ,
962 .Ar Mb ,
963 and
964 .Ar Gb
965 are used to represent bits, kilobits, megabits, and
966 gigabits per second, respectively.
967 The value must not exceed the interface bandwidth.
968 If
969 .Ar bandwidth
970 is not specified, the interface bandwidth is used
971 (but take note that some interfaces do not know their bandwidth,
972 or can adapt their bandwidth rates).
973 .Pp
974 When used with
975 .Ar fairq ,
976 .Ar bandwidth
977 specifies a guaranteed minimum but the fairq is allowed to exceed it.
978 .It Ar qlimit <limit>
979 The maximum number of packets held in the queue.
980 The default is 50.
981 .It Ar tbrsize Aq Ar size
982 Adjusts the size, in bytes, of the token bucket regulator.
983 If not specified, heuristics based on the
984 interface bandwidth are used to determine the size.
985 .It Ar queue Aq Ar list
986 Defines a list of subqueues to create on an interface.
987 .El
988 .Pp
989 In the following example, the interface dc0
990 should queue up to 5 Mbit/s in four second-level queues using
991 Class Based Queueing.
992 Those four queues will be shown in a later example.
993 .Bd -literal -offset indent
994 altq on dc0 cbq bandwidth 5Mb queue { std, http, mail, ssh }
995 .Ed
996 .Pp
997 Once interfaces are activated for queueing using the
998 .Ar altq
999 directive, a sequence of
1000 .Ar queue
1001 directives may be defined.
1002 The name associated with a
1003 .Ar queue
1004 must match a queue defined in the
1005 .Ar altq
1006 directive (e.g.\& mail), or, except for the
1007 .Ar priq
1008 and
1009 .Ar fairq
1010 .Ar schedulers ,
1011 in a parent
1012 .Ar queue
1013 declaration.
1014 The following keywords can be used:
1015 .Bl -tag -width xxxx
1016 .It Ar on Aq Ar interface
1017 Specifies the interface the queue operates on.
1018 If not given, it operates on all matching interfaces.
1019 .It Ar bandwidth Aq Ar bw
1020 Specifies the maximum bitrate to be processed by the queue.
1021 This value must not exceed the value of the parent
1022 .Ar queue
1023 and can be specified as an absolute value or a percentage of the parent
1024 queue's bandwidth.
1025 If not specified, defaults to 100% of the parent queue's bandwidth.
1026 The
1027 .Ar priq
1028 scheduler does not support bandwidth specification.
1029 The
1030 .Ar fairq
1031 scheduler uses the bandwidth specification as a guaranteed minimum and
1032 may exceed it.
1033 .It Ar priority Aq Ar level
1034 Between queues a priority level can be set.
1035 For
1036 .Ar cbq ,
1037 .Ar hfsc ,
1038 and
1039 .Ar fairq
1040 the range is 0 to 7 and for
1041 .Ar priq ,
1042 the range is 0 to 15.
1043 The default for all is 1.
1044 .Ar Priq
1045 queues with a higher priority are always served first.
1046 .Ar Fairq
1047 queues with a higher priority are served first unless they exceed their
1048 bandwidth specification.
1049 .Ar Cbq
1050 and
1051 .Ar hfsc
1052 queues with a higher priority are preferred in the case of overload.
1053 .It Ar qlimit Aq Ar limit
1054 The maximum number of packets held in the queue.
1055 The default is 50.
1056 When used with a
1057 .Ar fairq
1058 this specified the maximum number of packets held per bucket.
1059 .El
1060 .Pp
1061 The
1062 .Ar scheduler
1063 can get additional parameters with
1064 .Xo Aq Ar scheduler
1065 .Pf ( Aq Ar parameters ) .
1066 .Xc
1067 Parameters are as follows:
1068 .Bl -tag -width Fl
1069 .It Ar default
1070 Packets not matched by another queue are assigned to this one.
1071 Exactly one default queue is required.
1072 .It Ar red
1073 Enable RED (Random Early Detection) on this queue.
1074 RED drops packets with a probability proportional to the average
1075 queue length.
1076 .It Ar rio
1077 Enables RIO on this queue.
1078 RIO is RED with IN/OUT, thus running
1079 RED two times more than RIO would achieve the same effect.
1080 .It Ar ecn
1081 Enables ECN (Explicit Congestion Notification) on this queue.
1082 ECN implies RED.
1083 .El
1084 .Pp
1085 The
1086 .Ar fairq
1087 .Ar scheduler
1088 supports the following additional options:
1089 .Bl -tag -width Fl
1090 .It Ar buckets <number>
1091 Specify the number of buckets, from 1 to 2048 in powers of 2.
1092 A bucket size of 1 causes a
1093 .Ar fairq
1094 to essentially degenerate into a priority queue.
1095 .It Ar linkshare <sc>
1096 The bandwidth share of a backlogged queue.
1097 This option is parsed but not yet supported.
1098 .It Ar hogs <bandwidth>
1099 This option allows low bandwidth connections to burst up to the specified
1100 bandwidth by not advancing the round robin when taking packets out of
1101 the related queue.
1102 When using this option a small value no greater than 1/20 available interface
1103 bandwidth is recommended.
1104 .El
1105 .Pp
1106 The
1107 .Ar cbq
1108 .Ar scheduler
1109 supports an additional option:
1110 .Bl -tag -width Fl
1111 .It Ar borrow
1112 The queue can borrow bandwidth from the parent.
1113 .El
1114 .Pp
1115 The
1116 .Ar hfsc
1117 .Ar scheduler
1118 supports some additional options:
1119 .Bl -tag -width Fl
1120 .It Ar realtime Aq Ar sc
1121 The minimum required bandwidth for the queue.
1122 .It Ar upperlimit Aq Ar sc
1123 The maximum allowed bandwidth for the queue.
1124 .It Ar linkshare Aq Ar sc
1125 The bandwidth share of a backlogged queue.
1126 .El
1127 .Pp
1128 .Aq Ar sc
1129 is an acronym for
1130 .Ar service curve .
1131 .Pp
1132 The format for service curve specifications is
1133 .Ar m2
1134 or
1135 .Ar "(m1 d m2)" .
1136 .Ar m2
1137 controls the bandwidth assigned to the queue.
1138 .Ar m1
1139 and
1140 .Ar d
1141 are optional and can be used to control the initial bandwidth assignment.
1142 For the first
1143 .Ar d
1144 milliseconds the queue gets the bandwidth given as
1145 .Ar m1 ,
1146 afterwards the value given in
1147 .Ar m2 .
1148 .Pp
1149 Furthermore, with
1150 .Ar cbq
1151 and
1152 .Ar hfsc ,
1153 child queues can be specified as in an
1154 .Ar altq
1155 declaration, thus building a tree of queues using a part of
1156 their parent's bandwidth.
1157 .Pp
1158 Packets can be assigned to queues based on filter rules by using the
1159 .Ar queue
1160 keyword.
1161 Normally only one
1162 .Ar queue
1163 is specified; when a second one is specified it will instead be used for
1164 packets which have a
1165 .Em TOS
1166 of
1167 .Em lowdelay
1168 and for TCP ACKs with no data payload.
1169 .Pp
1170 To continue the previous example, the examples below would specify the
1171 four referenced
1172 queues, plus a few child queues.
1173 Interactive
1174 .Xr ssh 1
1175 sessions get priority over bulk transfers like
1176 .Xr scp 1
1177 and
1178 .Xr sftp 1 .
1179 The queues may then be referenced by filtering rules (see
1180 .Sx PACKET FILTERING
1181 below).
1182 .Bd -literal
1183 queue std bandwidth 10% cbq(default)
1184 queue http bandwidth 60% priority 2 cbq(borrow red) \e
1185       { employees, developers }
1186 queue  developers bandwidth 75% cbq(borrow)
1187 queue  employees bandwidth 15%
1188 queue mail bandwidth 10% priority 0 cbq(borrow ecn)
1189 queue ssh bandwidth 20% cbq(borrow) { ssh_interactive, ssh_bulk }
1190 queue  ssh_interactive bandwidth 50% priority 7 cbq(borrow)
1191 queue  ssh_bulk bandwidth 50% priority 0 cbq(borrow)
1192
1193 block return out on dc0 inet all queue std
1194 pass out on dc0 inet proto tcp from $developerhosts to any port 80 \e
1195       queue developers
1196 pass out on dc0 inet proto tcp from $employeehosts to any port 80 \e
1197       queue employees
1198 pass out on dc0 inet proto tcp from any to any port 22 \e
1199       queue(ssh_bulk, ssh_interactive)
1200 pass out on dc0 inet proto tcp from any to any port 25 \e
1201       queue mail
1202 .Ed
1203 .Sh TRANSLATION
1204 Translation rules modify either the source or destination address of the
1205 packets associated with a stateful connection.
1206 A stateful connection is automatically created to track packets matching
1207 such a rule as long as they are not blocked by the filtering section of
1208 .Nm .
1209 The translation engine modifies the specified address and/or port in the
1210 packet, recalculates IP, TCP and UDP checksums as necessary, and passes it to
1211 the packet filter for evaluation.
1212 .Pp
1213 Since translation occurs before filtering the filter
1214 engine will see packets as they look after any
1215 addresses and ports have been translated.
1216 Filter rules will therefore have to filter based on the translated
1217 address and port number.
1218 Packets that match a translation rule are only automatically passed if
1219 the
1220 .Ar pass
1221 modifier is given, otherwise they are
1222 still subject to
1223 .Ar block
1224 and
1225 .Ar pass
1226 rules.
1227 .Pp
1228 The state entry created permits
1229 .Xr pf 4
1230 to keep track of the original address for traffic associated with that state
1231 and correctly direct return traffic for that connection.
1232 .Pp
1233 Various types of translation are possible with pf:
1234 .Bl -tag -width xxxx
1235 .It Ar binat
1236 A
1237 .Ar binat
1238 rule specifies a bidirectional mapping between an external IP netblock
1239 and an internal IP netblock.
1240 .It Ar nat
1241 A
1242 .Ar nat
1243 rule specifies that IP addresses are to be changed as the packet
1244 traverses the given interface.
1245 This technique allows one or more IP addresses
1246 on the translating host to support network traffic for a larger range of
1247 machines on an "inside" network.
1248 Although in theory any IP address can be used on the inside, it is strongly
1249 recommended that one of the address ranges defined by RFC 1918 be used.
1250 These netblocks are:
1251 .Bd -literal
1252 10.0.0.0 - 10.255.255.255 (all of net 10, i.e., 10/8)
1253 172.16.0.0 - 172.31.255.255 (i.e., 172.16/12)
1254 192.168.0.0 - 192.168.255.255 (i.e., 192.168/16)
1255 .Ed
1256 .It Pa rdr
1257 The packet is redirected to another destination and possibly a
1258 different port.
1259 .Ar rdr
1260 rules can optionally specify port ranges instead of single ports.
1261 rdr ... port 2000:2999 -\*(Gt ... port 4000
1262 redirects ports 2000 to 2999 (inclusive) to port 4000.
1263 rdr ... port 2000:2999 -\*(Gt ... port 4000:*
1264 redirects port 2000 to 4000, 2001 to 4001, ..., 2999 to 4999.
1265 .El
1266 .Pp
1267 In addition to modifying the address, some translation rules may modify
1268 source or destination ports for
1269 .Xr tcp 4
1270 or
1271 .Xr udp 4
1272 connections; implicitly in the case of
1273 .Ar nat
1274 rules and explicitly in the case of
1275 .Ar rdr
1276 rules.
1277 Port numbers are never translated with a
1278 .Ar binat
1279 rule.
1280 .Pp
1281 Evaluation order of the translation rules is dependent on the type
1282 of the translation rules and of the direction of a packet.
1283 .Ar binat
1284 rules are always evaluated first.
1285 Then either the
1286 .Ar rdr
1287 rules are evaluated on an inbound packet or the
1288 .Ar nat
1289 rules on an outbound packet.
1290 Rules of the same type are evaluated in the same order in which they
1291 appear in the ruleset.
1292 The first matching rule decides what action is taken.
1293 .Pp
1294 The
1295 .Ar no
1296 option prefixed to a translation rule causes packets to remain untranslated,
1297 much in the same way as
1298 .Ar drop quick
1299 works in the packet filter (see below).
1300 If no rule matches the packet it is passed to the filter engine unmodified.
1301 .Pp
1302 Translation rules apply only to packets that pass through
1303 the specified interface, and if no interface is specified,
1304 translation is applied to packets on all interfaces.
1305 For instance, redirecting port 80 on an external interface to an internal
1306 web server will only work for connections originating from the outside.
1307 Connections to the address of the external interface from local hosts will
1308 not be redirected, since such packets do not actually pass through the
1309 external interface.
1310 Redirections cannot reflect packets back through the interface they arrive
1311 on, they can only be redirected to hosts connected to different interfaces
1312 or to the firewall itself.
1313 .Pp
1314 Note that redirecting external incoming connections to the loopback
1315 address, as in
1316 .Bd -literal -offset indent
1317 rdr on ne3 inet proto tcp to port smtp -\*(Gt 127.0.0.1 port spamd
1318 .Ed
1319 .Pp
1320 will effectively allow an external host to connect to daemons
1321 bound solely to the loopback address, circumventing the traditional
1322 blocking of such connections on a real interface.
1323 Unless this effect is desired, any of the local non-loopback addresses
1324 should be used as redirection target instead, which allows external
1325 connections only to daemons bound to this address or not bound to
1326 any address.
1327 .Pp
1328 See
1329 .Sx TRANSLATION EXAMPLES
1330 below.
1331 .Sh PACKET FILTERING
1332 .Xr pf 4
1333 has the ability to
1334 .Ar block
1335 and
1336 .Ar pass
1337 packets based on attributes of their layer 3 (see
1338 .Xr ip 4
1339 and
1340 .Xr ip6 4 )
1341 and layer 4 (see
1342 .Xr icmp 4 ,
1343 .Xr icmp6 4 ,
1344 .Xr tcp 4 ,
1345 .Xr udp 4 )
1346 headers.
1347 In addition, packets may also be
1348 assigned to queues for the purpose of bandwidth control.
1349 .Pp
1350 For each packet processed by the packet filter, the filter rules are
1351 evaluated in sequential order, from first to last.
1352 The last matching rule decides what action is taken.
1353 If no rule matches the packet, the default action is to pass
1354 the packet.
1355 .Pp
1356 The following actions can be used in the filter:
1357 .Bl -tag -width xxxx
1358 .It Ar block
1359 The packet is blocked.
1360 There are a number of ways in which a
1361 .Ar block
1362 rule can behave when blocking a packet.
1363 The default behaviour is to
1364 .Ar drop
1365 packets silently, however this can be overridden or made
1366 explicit either globally, by setting the
1367 .Ar block-policy
1368 option, or on a per-rule basis with one of the following options:
1369 .Pp
1370 .Bl -tag -width xxxx -compact
1371 .It Ar drop
1372 The packet is silently dropped.
1373 .It Ar return-rst
1374 This applies only to
1375 .Xr tcp 4
1376 packets, and issues a TCP RST which closes the
1377 connection.
1378 .It Ar return-icmp
1379 .It Ar return-icmp6
1380 This causes ICMP messages to be returned for packets which match the rule.
1381 By default this is an ICMP UNREACHABLE message, however this
1382 can be overridden by specifying a message as a code or number.
1383 .It Ar return
1384 This causes a TCP RST to be returned for
1385 .Xr tcp 4
1386 packets and an ICMP UNREACHABLE for UDP and other packets.
1387 .El
1388 .Pp
1389 Options returning ICMP packets currently have no effect if
1390 .Xr pf 4
1391 operates on a
1392 .Xr bridge 4 ,
1393 as the code to support this feature has not yet been implemented.
1394 .Pp
1395 The simplest mechanism to block everything by default and only pass
1396 packets that match explicit rules is specify a first filter rule of:
1397 .Bd -literal -offset indent
1398 block all
1399 .Ed
1400 .It Ar pass
1401 The packet is passed;
1402 state is created unless the
1403 .Ar no state
1404 option is specified.
1405 .El
1406 .Pp
1407 By default
1408 .Xr pf 4
1409 filters packets statefully; the first time a packet matches a
1410 .Ar pass
1411 rule, a state entry is created; for subsequent packets the filter checks
1412 whether the packet matches any state.
1413 If it does, the packet is passed without evaluation of any rules.
1414 After the connection is closed or times out, the state entry is automatically
1415 removed.
1416 .Pp
1417 This has several advantages.
1418 For TCP connections, comparing a packet to a state involves checking
1419 its sequence numbers, as well as TCP timestamps if a
1420 .Ar scrub reassemble tcp
1421 rule applies to the connection.
1422 If these values are outside the narrow windows of expected
1423 values, the packet is dropped.
1424 This prevents spoofing attacks, such as when an attacker sends packets with
1425 a fake source address/port but does not know the connection's sequence
1426 numbers.
1427 Similarly,
1428 .Xr pf 4
1429 knows how to match ICMP replies to states.
1430 For example,
1431 .Bd -literal -offset indent
1432 pass out inet proto icmp all icmp-type echoreq
1433 .Ed
1434 .Pp
1435 allows echo requests (such as those created by
1436 .Xr ping 8 )
1437 out statefully, and matches incoming echo replies correctly to states.
1438 .Pp
1439 Also, looking up states is usually faster than evaluating rules.
1440 If there are 50 rules, all of them are evaluated sequentially in O(n).
1441 Even with 50000 states, only 16 comparisons are needed to match a
1442 state, since states are stored in a binary search tree that allows
1443 searches in O(log2 n).
1444 .Pp
1445 Furthermore, correct handling of ICMP error messages is critical to
1446 many protocols, particularly TCP.
1447 .Xr pf 4
1448 matches ICMP error messages to the correct connection, checks them against
1449 connection parameters, and passes them if appropriate.
1450 For example if an ICMP source quench message referring to a stateful TCP
1451 connection arrives, it will be matched to the state and get passed.
1452 .Pp
1453 Finally, state tracking is required for
1454 .Ar nat , binat No and Ar rdr
1455 rules, in order to track address and port translations and reverse the
1456 translation on returning packets.
1457 .Pp
1458 .Xr pf 4
1459 will also create state for other protocols which are effectively stateless by
1460 nature.
1461 UDP packets are matched to states using only host addresses and ports,
1462 and other protocols are matched to states using only the host addresses.
1463 .Pp
1464 If stateless filtering of individual packets is desired,
1465 the
1466 .Ar no state
1467 keyword can be used to specify that state will not be created
1468 if this is the last matching rule.
1469 A number of parameters can also be set to affect how
1470 .Xr pf 4
1471 handles state tracking.
1472 See
1473 .Sx STATEFUL TRACKING OPTIONS
1474 below for further details.
1475 .Sh PARAMETERS
1476 The rule parameters specify the packets to which a rule applies.
1477 A packet always comes in on, or goes out through, one interface.
1478 Most parameters are optional.
1479 If a parameter is specified, the rule only applies to packets with
1480 matching attributes.
1481 Certain parameters can be expressed as lists, in which case
1482 .Xr pfctl 8
1483 generates all needed rule combinations.
1484 .Bl -tag -width xxxx
1485 .It Ar in No or Ar out
1486 This rule applies to incoming or outgoing packets.
1487 If neither
1488 .Ar in
1489 nor
1490 .Ar out
1491 are specified, the rule will match packets in both directions.
1492 .It Ar log
1493 In addition to the action specified, a log message is generated.
1494 Only the packet that establishes the state is logged,
1495 unless the
1496 .Ar no state
1497 option is specified.
1498 The logged packets are sent to a
1499 .Xr pflog 4
1500 interface, by default
1501 .Ar pflog0 .
1502 This interface is monitored by the
1503 .Xr pflogd 8
1504 logging daemon, which dumps the logged packets to the file
1505 .Pa /var/log/pflog
1506 in
1507 .Xr pcap 3
1508 binary format.
1509 .It Ar log (all)
1510 Used to force logging of all packets for a connection.
1511 This is not necessary when
1512 .Ar no state
1513 is explicitly specified.
1514 As with
1515 .Ar log ,
1516 packets are logged to
1517 .Xr pflog 4 .
1518 .It Ar log (user)
1519 Logs the
1520 .Ux
1521 user ID of the user that owns the socket and the PID of the process that
1522 has the socket open where the packet is sourced from or destined to
1523 (depending on which socket is local).
1524 This is in addition to the normal information logged.
1525 .It Ar log (to Aq Ar interface )
1526 Send logs to the specified
1527 .Xr pflog 4
1528 interface instead of
1529 .Ar pflog0 .
1530 .It Ar quick
1531 If a packet matches a rule which has the
1532 .Ar quick
1533 option set, this rule
1534 is considered the last matching rule, and evaluation of subsequent rules
1535 is skipped.
1536 .It Ar on Aq Ar interface
1537 This rule applies only to packets coming in on, or going out through, this
1538 particular interface.
1539 .It Aq Ar af
1540 This rule applies only to packets of this address family.
1541 Supported values are
1542 .Ar inet
1543 and
1544 .Ar inet6 .
1545 .It Ar proto Aq Ar protocol
1546 This rule applies only to packets of this protocol.
1547 Common protocols are
1548 .Xr icmp 4 ,
1549 .Xr icmp6 4 ,
1550 .Xr tcp 4 ,
1551 and
1552 .Xr udp 4 .
1553 For a list of all the protocol name to number mappings used by
1554 .Xr pfctl 8 ,
1555 see the file
1556 .Pa /etc/protocols .
1557 .It Xo
1558 .Ar from Aq Ar source
1559 .Ar port Aq Ar source
1560 .Ar os Aq Ar source
1561 .Ar to Aq Ar dest
1562 .Ar port Aq Ar dest
1563 .Xc
1564 This rule applies only to packets with the specified source and destination
1565 addresses and ports.
1566 .Pp
1567 Addresses can be specified in CIDR notation (matching netblocks), as
1568 symbolic host names or interface names, or as any of the following keywords:
1569 .Pp
1570 .Bl -tag -width xxxxxxxxxxxxxx -compact
1571 .It Ar any
1572 Any address.
1573 .It Ar route Aq Ar label
1574 Any address whose associated route has label
1575 .Aq Ar label .
1576 See
1577 .Xr route 4
1578 and
1579 .Xr route 8 .
1580 .It Ar no-route
1581 Any address which is not currently routable.
1582 .It Ar urpf-failed
1583 Any source address that fails a unicast reverse path forwarding (URPF)
1584 check, i.e. packets coming in on an interface other than that which holds
1585 the route back to the packet's source address.
1586 .It Aq Ar table
1587 Any address that matches the given table.
1588 .El
1589 .Pp
1590 Ranges of addresses are specified by using the
1591 .Sq -
1592 operator.
1593 For instance:
1594 .Dq 10.1.1.10 - 10.1.1.12
1595 means all addresses from 10.1.1.10 to 10.1.1.12,
1596 hence addresses 10.1.1.10, 10.1.1.11, and 10.1.1.12.
1597 .Pp
1598 Interface names can have modifiers appended:
1599 .Pp
1600 .Bl -tag -width xxxxxxxxxxxx -compact
1601 .It Ar :network
1602 Translates to the network(s) attached to the interface.
1603 .It Ar :broadcast
1604 Translates to the interface's broadcast address(es).
1605 .It Ar :peer
1606 Translates to the point to point interface's peer address(es).
1607 .It Ar :0
1608 Do not include interface aliases.
1609 .El
1610 .Pp
1611 Host names may also have the
1612 .Ar :0
1613 option appended to restrict the name resolution to the first of each
1614 v4 and v6 address found.
1615 .Pp
1616 Host name resolution and interface to address translation are done at
1617 ruleset load-time.
1618 When the address of an interface (or host name) changes (under DHCP or PPP,
1619 for instance), the ruleset must be reloaded for the change to be reflected
1620 in the kernel.
1621 Surrounding the interface name (and optional modifiers) in parentheses
1622 changes this behaviour.
1623 When the interface name is surrounded by parentheses, the rule is
1624 automatically updated whenever the interface changes its address.
1625 The ruleset does not need to be reloaded.
1626 This is especially useful with
1627 .Ar nat .
1628 .Pp
1629 Ports can be specified either by number or by name.
1630 For example, port 80 can be specified as
1631 .Em www .
1632 For a list of all port name to number mappings used by
1633 .Xr pfctl 8 ,
1634 see the file
1635 .Pa /etc/services .
1636 .Pp
1637 Ports and ranges of ports are specified by using these operators:
1638 .Bd -literal -offset indent
1639 =       (equal)
1640 !=      (unequal)
1641 \*(Lt   (less than)
1642 \*(Le   (less than or equal)
1643 \*(Gt   (greater than)
1644 \*(Ge   (greater than or equal)
1645 :       (range including boundaries)
1646 \*(Gt\*(Lt      (range excluding boundaries)
1647 \*(Lt\*(Gt      (except range)
1648 .Ed
1649 .Pp
1650 .Sq \*(Gt\*(Lt ,
1651 .Sq \*(Lt\*(Gt
1652 and
1653 .Sq \&:
1654 are binary operators (they take two arguments).
1655 For instance:
1656 .Bl -tag -width Fl
1657 .It Ar port 2000:2004
1658 means
1659 .Sq all ports \*(Ge 2000 and \*(Le 2004 ,
1660 hence ports 2000, 2001, 2002, 2003 and 2004.
1661 .It Ar port 2000 \*(Gt\*(Lt 2004
1662 means
1663 .Sq all ports \*(Gt 2000 and \*(Lt 2004 ,
1664 hence ports 2001, 2002 and 2003.
1665 .It Ar port 2000 \*(Lt\*(Gt 2004
1666 means
1667 .Sq all ports \*(Lt 2000 or \*(Gt 2004 ,
1668 hence ports 1-1999 and 2005-65535.
1669 .El
1670 .Pp
1671 The operating system of the source host can be specified in the case of TCP
1672 rules with the
1673 .Ar OS
1674 modifier.
1675 See the
1676 .Sx OPERATING SYSTEM FINGERPRINTING
1677 section for more information.
1678 .Pp
1679 The host, port and OS specifications are optional, as in the following examples:
1680 .Bd -literal -offset indent
1681 pass in all
1682 pass in from any to any
1683 pass in proto tcp from any port \*(Le 1024 to any
1684 pass in proto tcp from any to any port 25
1685 pass in proto tcp from 10.0.0.0/8 port \*(Gt 1024 \e
1686       to ! 10.1.2.3 port != ssh
1687 pass in proto tcp from any os "OpenBSD"
1688 pass in proto tcp from route "DTAG"
1689 .Ed
1690 .It Ar all
1691 This is equivalent to "from any to any".
1692 .It Ar group Aq Ar group
1693 Similar to
1694 .Ar user ,
1695 this rule only applies to packets of sockets owned by the specified group.
1696 .It Ar user Aq Ar user
1697 This rule only applies to packets of sockets owned by the specified user.
1698 For outgoing connections initiated from the firewall, this is the user
1699 that opened the connection.
1700 For incoming connections to the firewall itself, this is the user that
1701 listens on the destination port.
1702 For forwarded connections, where the firewall is not a connection endpoint,
1703 the user and group are
1704 .Em unknown .
1705 .Pp
1706 All packets, both outgoing and incoming, of one connection are associated
1707 with the same user and group.
1708 Only TCP and UDP packets can be associated with users; for other protocols
1709 these parameters are ignored.
1710 .Pp
1711 User and group refer to the effective (as opposed to the real) IDs, in
1712 case the socket is created by a setuid/setgid process.
1713 User and group IDs are stored when a socket is created;
1714 when a process creates a listening socket as root (for instance, by
1715 binding to a privileged port) and subsequently changes to another
1716 user ID (to drop privileges), the credentials will remain root.
1717 .Pp
1718 User and group IDs can be specified as either numbers or names.
1719 The syntax is similar to the one for ports.
1720 The value
1721 .Em unknown
1722 matches packets of forwarded connections.
1723 .Em unknown
1724 can only be used with the operators
1725 .Cm =
1726 and
1727 .Cm != .
1728 Other constructs like
1729 .Cm user \*(Ge unknown
1730 are invalid.
1731 Forwarded packets with unknown user and group ID match only rules
1732 that explicitly compare against
1733 .Em unknown
1734 with the operators
1735 .Cm =
1736 or
1737 .Cm != .
1738 For instance
1739 .Cm user \*(Ge 0
1740 does not match forwarded packets.
1741 The following example allows only selected users to open outgoing
1742 connections:
1743 .Bd -literal -offset indent
1744 block out proto { tcp, udp } all
1745 pass  out proto { tcp, udp } all user { \*(Lt 1000, dhartmei }
1746 .Ed
1747 .It Xo Ar flags Aq Ar a
1748 .Pf / Ns Aq Ar b
1749 .No \*(Ba / Ns Aq Ar b
1750 .No \*(Ba any
1751 .Xc
1752 This rule only applies to TCP packets that have the flags
1753 .Aq Ar a
1754 set out of set
1755 .Aq Ar b .
1756 Flags not specified in
1757 .Aq Ar b
1758 are ignored.
1759 For stateful connections, the default is
1760 .Ar flags S/SA .
1761 To indicate that flags should not be checked at all, specify
1762 .Ar flags any .
1763 The flags are: (F)IN, (S)YN, (R)ST, (P)USH, (A)CK, (U)RG, (E)CE, and C(W)R.
1764 .Bl -tag -width Fl
1765 .It Ar flags S/S
1766 Flag SYN is set.
1767 The other flags are ignored.
1768 .It Ar flags S/SA
1769 This is the default setting for stateful connections.
1770 Out of SYN and ACK, exactly SYN may be set.
1771 SYN, SYN+PSH and SYN+RST match, but SYN+ACK, ACK and ACK+RST do not.
1772 This is more restrictive than the previous example.
1773 .It Ar flags /SFRA
1774 If the first set is not specified, it defaults to none.
1775 All of SYN, FIN, RST and ACK must be unset.
1776 .El
1777 .Pp
1778 Because
1779 .Ar flags S/SA
1780 is applied by default (unless
1781 .Ar no state
1782 is specified), only the initial SYN packet of a TCP handshake will create
1783 a state for a TCP connection.
1784 It is possible to be less restrictive, and allow state creation from
1785 intermediate
1786 .Pq non-SYN
1787 packets, by specifying
1788 .Ar flags any .
1789 This will cause
1790 .Xr pf 4
1791 to synchronize to existing connections, for instance
1792 if one flushes the state table.
1793 However, states created from such intermediate packets may be missing
1794 connection details such as the TCP window scaling factor.
1795 States which modify the packet flow, such as those affected by
1796 .Ar nat , binat No or Ar rdr
1797 rules,
1798 .Ar modulate No or Ar synproxy state
1799 options, or scrubbed with
1800 .Ar reassemble tcp
1801 will also not be recoverable from intermediate packets.
1802 Such connections will stall and time out.
1803 .It Xo Ar icmp-type Aq Ar type
1804 .Ar code Aq Ar code
1805 .Xc
1806 .It Xo Ar icmp6-type Aq Ar type
1807 .Ar code Aq Ar code
1808 .Xc
1809 This rule only applies to ICMP or ICMPv6 packets with the specified type
1810 and code.
1811 Text names for ICMP types and codes are listed in
1812 .Xr icmp 4
1813 and
1814 .Xr icmp6 4 .
1815 This parameter is only valid for rules that cover protocols ICMP or
1816 ICMP6.
1817 The protocol and the ICMP type indicator
1818 .Po
1819 .Ar icmp-type
1820 or
1821 .Ar icmp6-type
1822 .Pc
1823 must match.
1824 .It Xo Ar tos Aq Ar string
1825 .No \*(Ba Aq Ar number
1826 .Xc
1827 This rule applies to packets with the specified
1828 .Em TOS
1829 bits set.
1830 .Em TOS
1831 may be
1832 given as one of
1833 .Ar lowdelay ,
1834 .Ar throughput ,
1835 .Ar reliability ,
1836 or as either hex or decimal.
1837 .Pp
1838 For example, the following rules are identical:
1839 .Bd -literal -offset indent
1840 pass all tos lowdelay
1841 pass all tos 0x10
1842 pass all tos 16
1843 .Ed
1844 .It Ar allow-opts
1845 By default, IPv4 packets with IP options or IPv6 packets with routing
1846 extension headers are blocked.
1847 When
1848 .Ar allow-opts
1849 is specified for a
1850 .Ar pass
1851 rule, packets that pass the filter based on that rule (last matching)
1852 do so even if they contain IP options or routing extension headers.
1853 For packets that match state, the rule that initially created the
1854 state is used.
1855 The implicit
1856 .Ar pass
1857 rule that is used when a packet does not match any rules does not
1858 allow IP options.
1859 .It Ar label Aq Ar string
1860 Adds a label (name) to the rule, which can be used to identify the rule.
1861 For instance,
1862 pfctl -s labels
1863 shows per-rule statistics for rules that have labels.
1864 .Pp
1865 The following macros can be used in labels:
1866 .Pp
1867 .Bl -tag -width $srcaddr -compact -offset indent
1868 .It Ar $if
1869 The interface.
1870 .It Ar $srcaddr
1871 The source IP address.
1872 .It Ar $dstaddr
1873 The destination IP address.
1874 .It Ar $srcport
1875 The source port specification.
1876 .It Ar $dstport
1877 The destination port specification.
1878 .It Ar $proto
1879 The protocol name.
1880 .It Ar $nr
1881 The rule number.
1882 .El
1883 .Pp
1884 For example:
1885 .Bd -literal -offset indent
1886 ips = \&"{ 1.2.3.4, 1.2.3.5 }\&"
1887 pass in proto tcp from any to $ips \e
1888       port \*(Gt 1023 label \&"$dstaddr:$dstport\&"
1889 .Ed
1890 .Pp
1891 expands to
1892 .Bd -literal -offset indent
1893 pass in inet proto tcp from any to 1.2.3.4 \e
1894       port \*(Gt 1023 label \&"1.2.3.4:\*(Gt1023\&"
1895 pass in inet proto tcp from any to 1.2.3.5 \e
1896       port \*(Gt 1023 label \&"1.2.3.5:\*(Gt1023\&"
1897 .Ed
1898 .Pp
1899 The macro expansion for the
1900 .Ar label
1901 directive occurs only at configuration file parse time, not during runtime.
1902 .It Xo Ar queue Aq Ar queue
1903 .No \*(Ba ( Aq Ar queue ,
1904 .Aq Ar queue )
1905 .Xc
1906 Packets matching this rule will be assigned to the specified queue.
1907 If two queues are given, packets which have a
1908 .Em TOS
1909 of
1910 .Em lowdelay
1911 and TCP ACKs with no data payload will be assigned to the second one.
1912 See
1913 .Sx QUEUEING
1914 for setup details.
1915 .Pp
1916 For example:
1917 .Bd -literal -offset indent
1918 pass in proto tcp to port 25 queue mail
1919 pass in proto tcp to port 22 queue(ssh_bulk, ssh_prio)
1920 .Ed
1921 .It Ar tag Aq Ar string
1922 Packets matching this rule will be tagged with the
1923 specified string.
1924 The tag acts as an internal marker that can be used to
1925 identify these packets later on.
1926 This can be used, for example, to provide trust between
1927 interfaces and to determine if packets have been
1928 processed by translation rules.
1929 Tags are
1930 .Qq sticky ,
1931 meaning that the packet will be tagged even if the rule
1932 is not the last matching rule.
1933 Further matching rules can replace the tag with a
1934 new one but will not remove a previously applied tag.
1935 A packet is only ever assigned one tag at a time.
1936 Packet tagging can be done during
1937 .Ar nat ,
1938 .Ar rdr ,
1939 or
1940 .Ar binat
1941 rules in addition to filter rules.
1942 Tags take the same macros as labels (see above).
1943 .It Ar tagged Aq Ar string
1944 Used with filter, translation or scrub rules
1945 to specify that packets must already
1946 be tagged with the given tag in order to match the rule.
1947 Inverse tag matching can also be done
1948 by specifying the
1949 .Cm !\&
1950 operator before the
1951 .Ar tagged
1952 keyword.
1953 .It Ar rtable Aq Ar number
1954 Used to select an alternate routing table for the routing lookup.
1955 Only effective before the route lookup happened, i.e. when filtering inbound.
1956 .It Xo Ar divert-to Aq Ar host
1957 .Ar port Aq Ar port
1958 .Xc
1959 Used to redirect packets to a local socket bound to
1960 .Ar host
1961 and
1962 .Ar port .
1963 The packets will not be modified, so
1964 .Xr getsockname 2
1965 on the socket will return the original destination address of the packet.
1966 .It Ar divert-reply
1967 Used to receive replies for sockets that are bound to addresses
1968 which are not local to the machine.
1969 See
1970 .Xr setsockopt 2
1971 for information on how to bind these sockets.
1972 .It Ar probability Aq Ar number
1973 A probability attribute can be attached to a rule, with a value set between
1974 0 and 1, bounds not included.
1975 In that case, the rule will be honoured using the given probability value
1976 only.
1977 For example, the following rule will drop 20% of incoming ICMP packets:
1978 .Bd -literal -offset indent
1979 block in proto icmp probability 20%
1980 .Ed
1981 .El
1982 .Sh ROUTING
1983 If a packet matches a rule with a route option set, the packet filter will
1984 route the packet according to the type of route option.
1985 When such a rule creates state, the route option is also applied to all
1986 packets matching the same connection.
1987 .Bl -tag -width xxxx
1988 .It Ar fastroute
1989 The
1990 .Ar fastroute
1991 option does a normal route lookup to find the next hop for the packet.
1992 .It Ar route-to
1993 The
1994 .Ar route-to
1995 option routes the packet to the specified interface with an optional address
1996 for the next hop.
1997 When a
1998 .Ar route-to
1999 rule creates state, only packets that pass in the same direction as the
2000 filter rule specifies will be routed in this way.
2001 Packets passing in the opposite direction (replies) are not affected
2002 and are routed normally.
2003 .It Ar reply-to
2004 The
2005 .Ar reply-to
2006 option is similar to
2007 .Ar route-to ,
2008 but routes packets that pass in the opposite direction (replies) to the
2009 specified interface.
2010 Opposite direction is only defined in the context of a state entry, and
2011 .Ar reply-to
2012 is useful only in rules that create state.
2013 It can be used on systems with multiple external connections to
2014 route all outgoing packets of a connection through the interface
2015 the incoming connection arrived through (symmetric routing enforcement).
2016 .It Ar dup-to
2017 The
2018 .Ar dup-to
2019 option creates a duplicate of the packet and routes it like
2020 .Ar route-to .
2021 The original packet gets routed as it normally would.
2022 .El
2023 .Sh POOL OPTIONS
2024 For
2025 .Ar nat
2026 and
2027 .Ar rdr
2028 rules, (as well as for the
2029 .Ar route-to ,
2030 .Ar reply-to
2031 and
2032 .Ar dup-to
2033 rule options) for which there is a single redirection address which has a
2034 subnet mask smaller than 32 for IPv4 or 128 for IPv6 (more than one IP
2035 address), a variety of different methods for assigning this address can be
2036 used:
2037 .Bl -tag -width xxxx
2038 .It Ar bitmask
2039 The
2040 .Ar bitmask
2041 option applies the network portion of the redirection address to the address
2042 to be modified (source with
2043 .Ar nat ,
2044 destination with
2045 .Ar rdr ) .
2046 .It Ar random
2047 The
2048 .Ar random
2049 option selects an address at random within the defined block of addresses.
2050 .It Ar source-hash
2051 The
2052 .Ar source-hash
2053 option uses a hash of the source address to determine the redirection address,
2054 ensuring that the redirection address is always the same for a given source.
2055 An optional key can be specified after this keyword either in hex or as a
2056 string; by default
2057 .Xr pfctl 8
2058 randomly generates a key for source-hash every time the
2059 ruleset is reloaded.
2060 .It Ar round-robin
2061 The
2062 .Ar round-robin
2063 option loops through the redirection address(es).
2064 .Pp
2065 When more than one redirection address is specified,
2066 .Ar round-robin
2067 is the only permitted pool type.
2068 .It Ar static-port
2069 With
2070 .Ar nat
2071 rules, the
2072 .Ar static-port
2073 option prevents
2074 .Xr pf 4
2075 from modifying the source port on TCP and UDP packets.
2076 .El
2077 .Pp
2078 Additionally, the
2079 .Ar sticky-address
2080 option can be specified to help ensure that multiple connections from the
2081 same source are mapped to the same redirection address.
2082 This option can be used with the
2083 .Ar random
2084 and
2085 .Ar round-robin
2086 pool options.
2087 Note that by default these associations are destroyed as soon as there are
2088 no longer states which refer to them; in order to make the mappings last
2089 beyond the lifetime of the states, increase the global options with
2090 .Ar set timeout src.track .
2091 See
2092 .Sx STATEFUL TRACKING OPTIONS
2093 for more ways to control the source tracking.
2094 .Sh STATE MODULATION
2095 Much of the security derived from TCP is attributable to how well the
2096 initial sequence numbers (ISNs) are chosen.
2097 Some popular stack implementations choose
2098 .Em very
2099 poor ISNs and thus are normally susceptible to ISN prediction exploits.
2100 By applying a
2101 .Ar modulate state
2102 rule to a TCP connection,
2103 .Xr pf 4
2104 will create a high quality random sequence number for each connection
2105 endpoint.
2106 .Pp
2107 The
2108 .Ar modulate state
2109 directive implicitly keeps state on the rule and is
2110 only applicable to TCP connections.
2111 .Pp
2112 For instance:
2113 .Bd -literal -offset indent
2114 block all
2115 pass out proto tcp from any to any modulate state
2116 pass in  proto tcp from any to any port 25 flags S/SFRA modulate state
2117 .Ed
2118 .Pp
2119 Note that modulated connections will not recover when the state table
2120 is lost (firewall reboot, flushing the state table, etc...).
2121 .Xr pf 4
2122 will not be able to infer a connection again after the state table flushes
2123 the connection's modulator.
2124 When the state is lost, the connection may be left dangling until the
2125 respective endpoints time out the connection.
2126 It is possible on a fast local network for the endpoints to start an ACK
2127 storm while trying to resynchronize after the loss of the modulator.
2128 The default
2129 .Ar flags
2130 settings (or a more strict equivalent) should be used on
2131 .Ar modulate state
2132 rules to prevent ACK storms.
2133 .Pp
2134 Note that alternative methods are available
2135 to prevent loss of the state table
2136 and allow for firewall failover.
2137 See
2138 .Xr carp 4
2139 and
2140 .Xr pfsync 4
2141 for further information.
2142 .Sh SYN PROXY
2143 By default,
2144 .Xr pf 4
2145 passes packets that are part of a
2146 .Xr tcp 4
2147 handshake between the endpoints.
2148 The
2149 .Ar synproxy state
2150 option can be used to cause
2151 .Xr pf 4
2152 itself to complete the handshake with the active endpoint, perform a handshake
2153 with the passive endpoint, and then forward packets between the endpoints.
2154 .Pp
2155 No packets are sent to the passive endpoint before the active endpoint has
2156 completed the handshake, hence so-called SYN floods with spoofed source
2157 addresses will not reach the passive endpoint, as the sender can't complete the
2158 handshake.
2159 .Pp
2160 The proxy is transparent to both endpoints, they each see a single
2161 connection from/to the other endpoint.
2162 .Xr pf 4
2163 chooses random initial sequence numbers for both handshakes.
2164 Once the handshakes are completed, the sequence number modulators
2165 (see previous section) are used to translate further packets of the
2166 connection.
2167 .Ar synproxy state
2168 includes
2169 .Ar modulate state .
2170 .Pp
2171 Rules with
2172 .Ar synproxy
2173 will not work if
2174 .Xr pf 4
2175 operates on a
2176 .Xr bridge 4 .
2177 .Pp
2178 Example:
2179 .Bd -literal -offset indent
2180 pass in proto tcp from any to any port www synproxy state
2181 .Ed
2182 .Sh STATEFUL TRACKING OPTIONS
2183 A number of options related to stateful tracking can be applied on a
2184 per-rule basis.
2185 .Ar keep state ,
2186 .Ar modulate state
2187 and
2188 .Ar synproxy state
2189 support these options, and
2190 .Ar keep state
2191 must be specified explicitly to apply options to a rule.
2192 .Pp
2193 .Bl -tag -width xxxx -compact
2194 .It Ar max Aq Ar number
2195 Limits the number of concurrent states the rule may create.
2196 When this limit is reached, further packets that would create
2197 state will not match this rule until existing states time out.
2198 .It Ar no-sync
2199 Prevent state changes for states created by this rule from appearing on the
2200 .Xr pfsync 4
2201 interface.
2202 .It Xo Aq Ar timeout
2203 .Aq Ar seconds
2204 .Xc
2205 Changes the timeout values used for states created by this rule.
2206 For a list of all valid timeout names, see
2207 .Sx OPTIONS
2208 above.
2209 .It Ar sloppy
2210 Uses a sloppy TCP connection tracker that does not check sequence
2211 numbers at all, which makes insertion and ICMP teardown attacks way
2212 easier.
2213 This is intended to be used in situations where one does not see all
2214 packets of a connection, e.g. in asymmetric routing situations.
2215 Cannot be used with modulate or synproxy state.
2216 .El
2217 .Pp
2218 Multiple options can be specified, separated by commas:
2219 .Bd -literal -offset indent
2220 pass in proto tcp from any to any \e
2221       port www keep state \e
2222       (max 100, source-track rule, max-src-nodes 75, \e
2223       max-src-states 3, tcp.established 60, tcp.closing 5)
2224 .Ed
2225 .Pp
2226 When the
2227 .Ar source-track
2228 keyword is specified, the number of states per source IP is tracked.
2229 .Pp
2230 .Bl -tag -width xxxx -compact
2231 .It Ar source-track rule
2232 The maximum number of states created by this rule is limited by the rule's
2233 .Ar max-src-nodes
2234 and
2235 .Ar max-src-states
2236 options.
2237 Only state entries created by this particular rule count toward the rule's
2238 limits.
2239 .It Ar source-track global
2240 The number of states created by all rules that use this option is limited.
2241 Each rule can specify different
2242 .Ar max-src-nodes
2243 and
2244 .Ar max-src-states
2245 options, however state entries created by any participating rule count towards
2246 each individual rule's limits.
2247 .El
2248 .Pp
2249 The following limits can be set:
2250 .Pp
2251 .Bl -tag -width xxxx -compact
2252 .It Ar max-src-nodes Aq Ar number
2253 Limits the maximum number of source addresses which can simultaneously
2254 have state table entries.
2255 .It Ar max-src-states Aq Ar number
2256 Limits the maximum number of simultaneous state entries that a single
2257 source address can create with this rule.
2258 .It Ar pickups
2259 Specify that mid-stream pickups are to be allowed.
2260 The default is to NOT allow mid-stream pickups and implies flags
2261 S/SA for TCP connections.
2262 If pickups are enabled, flags S/SA are not implied
2263 for TCP connections and state can be created for any packet.
2264 .Pp
2265 The implied flags parameters need not be specified in either case
2266 unless you explicitly wish to override them, which also allows
2267 you to roll-up several protocols into a single rule.
2268 .Pp
2269 Certain validations are disabled when mid-stream pickups occur.
2270 For example, the window scaling options are not known for
2271 TCP pickups and sequence space comparisons must be disabled.
2272 .Pp
2273 This does not effect state representing fully quantified
2274 connections (for which the SYN/SYN-ACK passed through the routing
2275 engine).
2276 Those connections continue to be fully validated.
2277 .It Ar hash-only
2278 Specify that mid-stream pickups are to be allowed, but unconditionally
2279 disables sequence space checks even if full state is available.
2280 .It Ar no-pickups
2281 Specify that mid-stream pickups are not to be allowed.
2282 This is the
2283 default and this keyword does not normally need to be specified.
2284 However, if you are concerned about rule set portability then
2285 specifying this keyword will at least result in an error from
2286 .Xr pfctl 8
2287 if it doesn't understand the feature.
2288 TCP flags of S/SA are implied
2289 and do not need to explicitly specified.
2290 .El
2291 .Pp
2292 For stateful TCP connections, limits on established connections (connections
2293 which have completed the TCP 3-way handshake) can also be enforced
2294 per source IP.
2295 .Pp
2296 .Bl -tag -width xxxx -compact
2297 .It Ar max-src-conn Aq Ar number
2298 Limits the maximum number of simultaneous TCP connections which have
2299 completed the 3-way handshake that a single host can make.
2300 .It Xo Ar max-src-conn-rate Aq Ar number
2301 .No / Aq Ar seconds
2302 .Xc
2303 Limit the rate of new connections over a time interval.
2304 The connection rate is an approximation calculated as a moving average.
2305 .El
2306 .Pp
2307 Because the 3-way handshake ensures that the source address is not being
2308 spoofed, more aggressive action can be taken based on these limits.
2309 With the
2310 .Ar overload Aq Ar table
2311 state option, source IP addresses which hit either of the limits on
2312 established connections will be added to the named table.
2313 This table can be used in the ruleset to block further activity from
2314 the offending host, redirect it to a tarpit process, or restrict its
2315 bandwidth.
2316 .Pp
2317 The optional
2318 .Ar flush
2319 keyword kills all states created by the matching rule which originate
2320 from the host which exceeds these limits.
2321 The
2322 .Ar global
2323 modifier to the flush command kills all states originating from the
2324 offending host, regardless of which rule created the state.
2325 .Pp
2326 For example, the following rules will protect the webserver against
2327 hosts making more than 100 connections in 10 seconds.
2328 Any host which connects faster than this rate will have its address added
2329 to the
2330 .Aq bad_hosts
2331 table and have all states originating from it flushed.
2332 Any new packets arriving from this host will be dropped unconditionally
2333 by the block rule.
2334 .Bd -literal -offset indent
2335 block quick from \*(Ltbad_hosts\*(Gt
2336 pass in on $ext_if proto tcp to $webserver port www keep state \e
2337         (max-src-conn-rate 100/10, overload \*(Ltbad_hosts\*(Gt flush global)
2338 .Ed
2339 .Sh OPERATING SYSTEM FINGERPRINTING
2340 Passive OS Fingerprinting is a mechanism to inspect nuances of a TCP
2341 connection's initial SYN packet and guess at the host's operating system.
2342 Unfortunately these nuances are easily spoofed by an attacker so the
2343 fingerprint is not useful in making security decisions.
2344 But the fingerprint is typically accurate enough to make policy decisions
2345 upon.
2346 .Pp
2347 The fingerprints may be specified by operating system class, by
2348 version, or by subtype/patchlevel.
2349 The class of an operating system is typically the vendor or genre
2350 and would be
2351 .Ox
2352 for the
2353 .Xr pf 4
2354 firewall itself.
2355 The version of the oldest available
2356 .Ox
2357 release on the main FTP site
2358 would be 2.6 and the fingerprint would be written
2359 .Pp
2360 .Dl \&"OpenBSD 2.6\&"
2361 .Pp
2362 The subtype of an operating system is typically used to describe the
2363 patchlevel if that patch led to changes in the TCP stack behavior.
2364 In the case of
2365 .Ox ,
2366 the only subtype is for a fingerprint that was
2367 normalized by the
2368 .Ar no-df
2369 scrub option and would be specified as
2370 .Pp
2371 .Dl \&"OpenBSD 3.3 no-df\&"
2372 .Pp
2373 Fingerprints for most popular operating systems are provided by
2374 .Xr pf.os 5 .
2375 Once
2376 .Xr pf 4
2377 is running, a complete list of known operating system fingerprints may
2378 be listed by running:
2379 .Pp
2380 .Dl # pfctl -so
2381 .Pp
2382 Filter rules can enforce policy at any level of operating system specification
2383 assuming a fingerprint is present.
2384 Policy could limit traffic to approved operating systems or even ban traffic
2385 from hosts that aren't at the latest service pack.
2386 .Pp
2387 The
2388 .Ar unknown
2389 class can also be used as the fingerprint which will match packets for
2390 which no operating system fingerprint is known.
2391 .Pp
2392 Examples:
2393 .Bd -literal -offset indent
2394 pass  out proto tcp from any os OpenBSD
2395 block out proto tcp from any os Doors
2396 block out proto tcp from any os "Doors PT"
2397 block out proto tcp from any os "Doors PT SP3"
2398 block out from any os "unknown"
2399 pass on lo0 proto tcp from any os "OpenBSD 3.3 lo0"
2400 .Ed
2401 .Pp
2402 Operating system fingerprinting is limited only to the TCP SYN packet.
2403 This means that it will not work on other protocols and will not match
2404 a currently established connection.
2405 .Pp
2406 Caveat: operating system fingerprints are occasionally wrong.
2407 There are three problems: an attacker can trivially craft his packets to
2408 appear as any operating system he chooses;
2409 an operating system patch could change the stack behavior and no fingerprints
2410 will match it until the database is updated;
2411 and multiple operating systems may have the same fingerprint.
2412 .Sh BLOCKING SPOOFED TRAFFIC
2413 "Spoofing" is the faking of IP addresses, typically for malicious
2414 purposes.
2415 The
2416 .Ar antispoof
2417 directive expands to a set of filter rules which will block all
2418 traffic with a source IP from the network(s) directly connected
2419 to the specified interface(s) from entering the system through
2420 any other interface.
2421 .Pp
2422 For example, the line
2423 .Bd -literal -offset indent
2424 antispoof for lo0
2425 .Ed
2426 .Pp
2427 expands to
2428 .Bd -literal -offset indent
2429 block drop in on ! lo0 inet from 127.0.0.1/8 to any
2430 block drop in on ! lo0 inet6 from ::1 to any
2431 .Ed
2432 .Pp
2433 For non-loopback interfaces, there are additional rules to block incoming
2434 packets with a source IP address identical to the interface's IP(s).
2435 For example, assuming the interface wi0 had an IP address of 10.0.0.1 and a
2436 netmask of 255.255.255.0,
2437 the line
2438 .Bd -literal -offset indent
2439 antispoof for wi0 inet
2440 .Ed
2441 .Pp
2442 expands to
2443 .Bd -literal -offset indent
2444 block drop in on ! wi0 inet from 10.0.0.0/24 to any
2445 block drop in inet from 10.0.0.1 to any
2446 .Ed
2447 .Pp
2448 Caveat: Rules created by the
2449 .Ar antispoof
2450 directive interfere with packets sent over loopback interfaces
2451 to local addresses.
2452 One should pass these explicitly.
2453 .Sh FRAGMENT HANDLING
2454 The size of IP datagrams (packets) can be significantly larger than the
2455 maximum transmission unit (MTU) of the network.
2456 In cases when it is necessary or more efficient to send such large packets,
2457 the large packet will be fragmented into many smaller packets that will each
2458 fit onto the wire.
2459 Unfortunately for a firewalling device, only the first logical fragment will
2460 contain the necessary header information for the subprotocol that allows
2461 .Xr pf 4
2462 to filter on things such as TCP ports or to perform NAT.
2463 .Pp
2464 Besides the use of
2465 .Ar scrub
2466 rules as described in
2467 .Sx TRAFFIC NORMALIZATION
2468 above, there are three options for handling fragments in the packet filter.
2469 .Pp
2470 One alternative is to filter individual fragments with filter rules.
2471 If no
2472 .Ar scrub
2473 rule applies to a fragment, it is passed to the filter.
2474 Filter rules with matching IP header parameters decide whether the
2475 fragment is passed or blocked, in the same way as complete packets
2476 are filtered.
2477 Without reassembly, fragments can only be filtered based on IP header
2478 fields (source/destination address, protocol), since subprotocol header
2479 fields are not available (TCP/UDP port numbers, ICMP code/type).
2480 The
2481 .Ar fragment
2482 option can be used to restrict filter rules to apply only to
2483 fragments, but not complete packets.
2484 Filter rules without the
2485 .Ar fragment
2486 option still apply to fragments, if they only specify IP header fields.
2487 For instance, the rule
2488 .Bd -literal -offset indent
2489 pass in proto tcp from any to any port 80
2490 .Ed
2491 .Pp
2492 never applies to a fragment, even if the fragment is part of a TCP
2493 packet with destination port 80, because without reassembly this information
2494 is not available for each fragment.
2495 This also means that fragments cannot create new or match existing
2496 state table entries, which makes stateful filtering and address
2497 translation (NAT, redirection) for fragments impossible.
2498 .Pp
2499 It's also possible to reassemble only certain fragments by specifying
2500 source or destination addresses or protocols as parameters in
2501 .Ar scrub
2502 rules.
2503 .Pp
2504 In most cases, the benefits of reassembly outweigh the additional
2505 memory cost, and it's recommended to use
2506 .Ar scrub
2507 rules to reassemble
2508 all fragments via the
2509 .Ar fragment reassemble
2510 modifier.
2511 .Pp
2512 The memory allocated for fragment caching can be limited using
2513 .Xr pfctl 8 .
2514 Once this limit is reached, fragments that would have to be cached
2515 are dropped until other entries time out.
2516 The timeout value can also be adjusted.
2517 .Pp
2518 Currently, only IPv4 fragments are supported and IPv6 fragments
2519 are blocked unconditionally.
2520 .Sh ANCHORS
2521 Besides the main ruleset,
2522 .Xr pfctl 8
2523 can load rulesets into
2524 .Ar anchor
2525 attachment points.
2526 An
2527 .Ar anchor
2528 is a container that can hold rules, address tables, and other anchors.
2529 .Pp
2530 An
2531 .Ar anchor
2532 has a name which specifies the path where
2533 .Xr pfctl 8
2534 can be used to access the anchor to perform operations on it, such as
2535 attaching child anchors to it or loading rules into it.
2536 Anchors may be nested, with components separated by
2537 .Sq /
2538 characters, similar to how file system hierarchies are laid out.
2539 The main ruleset is actually the default anchor, so filter and
2540 translation rules, for example, may also be contained in any anchor.
2541 .Pp
2542 An anchor can reference another
2543 .Ar anchor
2544 attachment point
2545 using the following kinds
2546 of rules:
2547 .Bl -tag -width xxxx
2548 .It Ar nat-anchor Aq Ar name
2549 Evaluates the
2550 .Ar nat
2551 rules in the specified
2552 .Ar anchor .
2553 .It Ar rdr-anchor Aq Ar name
2554 Evaluates the
2555 .Ar rdr
2556 rules in the specified
2557 .Ar anchor .
2558 .It Ar binat-anchor Aq Ar name
2559 Evaluates the
2560 .Ar binat
2561 rules in the specified
2562 .Ar anchor .
2563 .It Ar anchor Aq Ar name
2564 Evaluates the filter rules in the specified
2565 .Ar anchor .
2566 .It Xo Ar load anchor
2567 .Aq Ar name
2568 .Ar from Aq Ar file
2569 .Xc
2570 Loads the rules from the specified file into the
2571 anchor
2572 .Ar name .
2573 .El
2574 .Pp
2575 When evaluation of the main ruleset reaches an
2576 .Ar anchor
2577 rule,
2578 .Xr pf 4
2579 will proceed to evaluate all rules specified in that anchor.
2580 .Pp
2581 Matching filter and translation rules marked with the
2582 .Ar quick
2583 option are final and abort the evaluation of the rules in other
2584 anchors and the main ruleset.
2585 If the
2586 .Ar anchor
2587 itself is marked with the
2588 .Ar quick
2589 option,
2590 ruleset evaluation will terminate when the anchor is exited if the packet is
2591 matched by any rule within the anchor.
2592 .Pp
2593 .Ar anchor
2594 rules are evaluated relative to the anchor in which they are contained.
2595 For example, all
2596 .Ar anchor
2597 rules specified in the main ruleset will reference anchor
2598 attachment points underneath the main ruleset, and
2599 .Ar anchor
2600 rules specified in a file loaded from a
2601 .Ar load anchor
2602 rule will be attached under that anchor point.
2603 .Pp
2604 Rules may be contained in
2605 .Ar anchor
2606 attachment points which do not contain any rules when the main ruleset
2607 is loaded, and later such anchors can be manipulated through
2608 .Xr pfctl 8
2609 without reloading the main ruleset or other anchors.
2610 For example,
2611 .Bd -literal -offset indent
2612 ext_if = \&"kue0\&"
2613 block on $ext_if all
2614 anchor spam
2615 pass out on $ext_if all
2616 pass in on $ext_if proto tcp from any \e
2617       to $ext_if port smtp
2618 .Ed
2619 .Pp
2620 blocks all packets on the external interface by default, then evaluates
2621 all rules in the
2622 .Ar anchor
2623 named "spam", and finally passes all outgoing connections and
2624 incoming connections to port 25.
2625 .Bd -literal -offset indent
2626 # echo \&"block in quick from 1.2.3.4 to any\&" \&| \e
2627       pfctl -a spam -f -
2628 .Ed
2629 .Pp
2630 This loads a single rule into the
2631 .Ar anchor ,
2632 which blocks all packets from a specific address.
2633 .Pp
2634 The anchor can also be populated by adding a
2635 .Ar load anchor
2636 rule after the
2637 .Ar anchor
2638 rule:
2639 .Bd -literal -offset indent
2640 anchor spam
2641 load anchor spam from "/etc/pf-spam.conf"
2642 .Ed
2643 .Pp
2644 When
2645 .Xr pfctl 8
2646 loads
2647 .Nm ,
2648 it will also load all the rules from the file
2649 .Pa /etc/pf-spam.conf
2650 into the anchor.
2651 .Pp
2652 Optionally,
2653 .Ar anchor
2654 rules can specify packet filtering parameters using the same syntax as
2655 filter rules.
2656 When parameters are used, the
2657 .Ar anchor
2658 rule is only evaluated for matching packets.
2659 This allows conditional evaluation of anchors, like:
2660 .Bd -literal -offset indent
2661 block on $ext_if all
2662 anchor spam proto tcp from any to any port smtp
2663 pass out on $ext_if all
2664 pass in on $ext_if proto tcp from any to $ext_if port smtp
2665 .Ed
2666 .Pp
2667 The rules inside
2668 .Ar anchor
2669 spam are only evaluated for
2670 .Ar tcp
2671 packets with destination port 25.
2672 Hence,
2673 .Bd -literal -offset indent
2674 # echo \&"block in quick from 1.2.3.4 to any" \&| \e
2675       pfctl -a spam -f -
2676 .Ed
2677 .Pp
2678 will only block connections from 1.2.3.4 to port 25.
2679 .Pp
2680 Anchors may end with the asterisk
2681 .Pq Sq *
2682 character, which signifies that all anchors attached at that point
2683 should be evaluated in the alphabetical ordering of their anchor name.
2684 For example,
2685 .Bd -literal -offset indent
2686 anchor "spam/*"
2687 .Ed
2688 .Pp
2689 will evaluate each rule in each anchor attached to the
2690 .Li spam
2691 anchor.
2692 Note that it will only evaluate anchors that are directly attached to the
2693 .Li spam
2694 anchor, and will not descend to evaluate anchors recursively.
2695 .Pp
2696 Since anchors are evaluated relative to the anchor in which they are
2697 contained, there is a mechanism for accessing the parent and ancestor
2698 anchors of a given anchor.
2699 Similar to file system path name resolution, if the sequence
2700 .Dq ..
2701 appears as an anchor path component, the parent anchor of the current
2702 anchor in the path evaluation at that point will become the new current
2703 anchor.
2704 As an example, consider the following:
2705 .Bd -literal -offset indent
2706 # echo ' anchor "spam/allowed" ' | pfctl -f -
2707 # echo -e ' anchor "../banned" \en pass' | \e
2708       pfctl -a spam/allowed -f -
2709 .Ed
2710 .Pp
2711 Evaluation of the main ruleset will lead into the
2712 .Li spam/allowed
2713 anchor, which will evaluate the rules in the
2714 .Li spam/banned
2715 anchor, if any, before finally evaluating the
2716 .Ar pass
2717 rule.
2718 .Pp
2719 Filter rule
2720 .Ar anchors
2721 can also be loaded inline in the ruleset within a brace ('{' '}') delimited
2722 block.
2723 Brace delimited blocks may contain rules or other brace-delimited blocks.
2724 When anchors are loaded this way the anchor name becomes optional.
2725 .Bd -literal -offset indent
2726 anchor "external" on egress {
2727         block
2728         anchor out {
2729                 pass proto tcp from any to port { 25, 80, 443 }
2730         }
2731         pass in proto tcp to any port 22
2732 }
2733 .Ed
2734 .Pp
2735 Since the parser specification for anchor names is a string, any
2736 reference to an anchor name containing
2737 .Sq /
2738 characters will require double quote
2739 .Pq Sq \&"
2740 characters around the anchor name.
2741 .Sh TRANSLATION EXAMPLES
2742 This example maps incoming requests on port 80 to port 8080, on
2743 which a daemon is running (because, for example, it is not run as root,
2744 and therefore lacks permission to bind to port 80).
2745 .Bd -literal
2746 # use a macro for the interface name, so it can be changed easily
2747 ext_if = \&"ne3\&"
2748
2749 # map daemon on 8080 to appear to be on 80
2750 rdr on $ext_if proto tcp from any to any port 80 -\*(Gt 127.0.0.1 port 8080
2751 .Ed
2752 .Pp
2753 If the
2754 .Ar pass
2755 modifier is given, packets matching the translation rule are passed without
2756 inspecting the filter rules:
2757 .Bd -literal
2758 rdr pass on $ext_if proto tcp from any to any port 80 -\*(Gt 127.0.0.1 \e
2759       port 8080
2760 .Ed
2761 .Pp
2762 In the example below, vlan12 is configured as 192.168.168.1;
2763 the machine translates all packets coming from 192.168.168.0/24 to 204.92.77.111
2764 when they are going out any interface except vlan12.
2765 This has the net effect of making traffic from the 192.168.168.0/24
2766 network appear as though it is the Internet routable address
2767 204.92.77.111 to nodes behind any interface on the router except
2768 for the nodes on vlan12.
2769 (Thus, 192.168.168.1 can talk to the 192.168.168.0/24 nodes.)
2770 .Bd -literal
2771 nat on ! vlan12 from 192.168.168.0/24 to any -\*(Gt 204.92.77.111
2772 .Ed
2773 .Pp
2774 In the example below, the machine sits between a fake internal 144.19.74.*
2775 network, and a routable external IP of 204.92.77.100.
2776 The
2777 .Ar no nat
2778 rule excludes protocol AH from being translated.
2779 .Bd -literal
2780 # NO NAT
2781 no nat on $ext_if proto ah from 144.19.74.0/24 to any
2782 nat on $ext_if from 144.19.74.0/24 to any -\*(Gt 204.92.77.100
2783 .Ed
2784 .Pp
2785 In the example below, packets bound for one specific server, as well as those
2786 generated by the sysadmins are not proxied; all other connections are.
2787 .Bd -literal
2788 # NO RDR
2789 no rdr on $int_if proto { tcp, udp } from any to $server port 80
2790 no rdr on $int_if proto { tcp, udp } from $sysadmins to any port 80
2791 rdr on $int_if proto { tcp, udp } from any to any port 80 -\*(Gt 127.0.0.1 \e
2792       port 80
2793 .Ed
2794 .Pp
2795 This longer example uses both a NAT and a redirection.
2796 The external interface has the address 157.161.48.183.
2797 On localhost, we are running
2798 .Xr ftp-proxy 8 ,
2799 waiting for FTP sessions to be redirected to it.
2800 The three mandatory anchors for
2801 .Xr ftp-proxy 8
2802 are omitted from this example; see the
2803 .Xr ftp-proxy 8
2804 manpage.
2805 .Bd -literal
2806 # NAT
2807 # Translate outgoing packets' source addresses (any protocol).
2808 # In this case, any address but the gateway's external address is mapped.
2809 nat on $ext_if inet from ! ($ext_if) to any -\*(Gt ($ext_if)
2810
2811 # NAT PROXYING
2812 # Map outgoing packets' source port to an assigned proxy port instead of
2813 # an arbitrary port.
2814 # In this case, proxy outgoing isakmp with port 500 on the gateway.
2815 nat on $ext_if inet proto udp from any port = isakmp to any -\*(Gt ($ext_if) \e
2816       port 500
2817
2818 # BINAT
2819 # Translate outgoing packets' source address (any protocol).
2820 # Translate incoming packets' destination address to an internal machine
2821 # (bidirectional).
2822 binat on $ext_if from 10.1.2.150 to any -\*(Gt $ext_if
2823
2824 # RDR
2825 # Translate incoming packets' destination addresses.
2826 # As an example, redirect a TCP and UDP port to an internal machine.
2827 rdr on $ext_if inet proto tcp from any to ($ext_if) port 8080 \e
2828       -\*(Gt 10.1.2.151 port 22
2829 rdr on $ext_if inet proto udp from any to ($ext_if) port 8080 \e
2830       -\*(Gt 10.1.2.151 port 53
2831
2832 # RDR
2833 # Translate outgoing ftp control connections to send them to localhost
2834 # for proxying with ftp-proxy(8) running on port 8021.
2835 rdr on $int_if proto tcp from any to any port 21 -\*(Gt 127.0.0.1 port 8021
2836 .Ed
2837 .Pp
2838 In this example, a NAT gateway is set up to translate internal addresses
2839 using a pool of public addresses (192.0.2.16/28) and to redirect
2840 incoming web server connections to a group of web servers on the internal
2841 network.
2842 .Bd -literal
2843 # NAT LOAD BALANCE
2844 # Translate outgoing packets' source addresses using an address pool.
2845 # A given source address is always translated to the same pool address by
2846 # using the source-hash keyword.
2847 nat on $ext_if inet from any to any -\*(Gt 192.0.2.16/28 source-hash
2848
2849 # RDR ROUND ROBIN
2850 # Translate incoming web server connections to a group of web servers on
2851 # the internal network.
2852 rdr on $ext_if proto tcp from any to any port 80 \e
2853       -\*(Gt { 10.1.2.155, 10.1.2.160, 10.1.2.161 } round-robin
2854 .Ed
2855 .Sh FILTER EXAMPLES
2856 .Bd -literal
2857 # The external interface is kue0
2858 # (157.161.48.183, the only routable address)
2859 # and the private network is 10.0.0.0/8, for which we are doing NAT.
2860
2861 # use a macro for the interface name, so it can be changed easily
2862 ext_if = \&"kue0\&"
2863
2864 # normalize all incoming traffic
2865 scrub in on $ext_if all fragment reassemble
2866
2867 # block and log everything by default
2868 block return log on $ext_if all
2869
2870 # block anything coming from source we have no back routes for
2871 block in from no-route to any
2872
2873 # block packets whose ingress interface does not match the one in
2874 # the route back to their source address
2875 block in from urpf-failed to any
2876
2877 # block and log outgoing packets that do not have our address as source,
2878 # they are either spoofed or something is misconfigured (NAT disabled,
2879 # for instance), we want to be nice and do not send out garbage.
2880 block out log quick on $ext_if from ! 157.161.48.183 to any
2881
2882 # silently drop broadcasts (cable modem noise)
2883 block in quick on $ext_if from any to 255.255.255.255
2884
2885 # block and log incoming packets from reserved address space and invalid
2886 # addresses, they are either spoofed or misconfigured, we cannot reply to
2887 # them anyway (hence, no return-rst).
2888 block in log quick on $ext_if from { 10.0.0.0/8, 172.16.0.0/12, \e
2889       192.168.0.0/16, 255.255.255.255/32 } to any
2890
2891 # ICMP
2892
2893 # pass out/in certain ICMP queries and keep state (ping)
2894 # state matching is done on host addresses and ICMP id (not type/code),
2895 # so replies (like 0/0 for 8/0) will match queries
2896 # ICMP error messages (which always refer to a TCP/UDP packet) are
2897 # handled by the TCP/UDP states
2898 pass on $ext_if inet proto icmp all icmp-type 8 code 0
2899
2900 # UDP
2901
2902 # pass out all UDP connections and keep state
2903 pass out on $ext_if proto udp all
2904
2905 # pass in certain UDP connections and keep state (DNS)
2906 pass in on $ext_if proto udp from any to any port domain
2907
2908 # TCP
2909
2910 # pass out all TCP connections and modulate state
2911 pass out on $ext_if proto tcp all modulate state
2912
2913 # pass in certain TCP connections and keep state (SSH, SMTP, DNS, IDENT)
2914 pass in on $ext_if proto tcp from any to any port { ssh, smtp, domain, \e
2915       auth }
2916
2917 # Do not allow Windows 9x SMTP connections since they are typically
2918 # a viral worm. Alternately we could limit these OSes to 1 connection each.
2919 block in on $ext_if proto tcp from any os {"Windows 95", "Windows 98"} \e
2920       to any port smtp
2921
2922 # IPv6
2923 # pass in/out all IPv6 traffic: note that we have to enable this in two
2924 # different ways, on both our physical interface and our tunnel
2925 pass quick on gif0 inet6
2926 pass quick on $ext_if proto ipv6
2927
2928 # Using the pickup options to keep/modulate/synproxy state
2929 #
2930 # no-pickups    (default) Do not allow connections to be picked up in the
2931 #               middle.  Implies flags S/SA (the 'no-pickups' option need
2932 #               not be specified, it is the default).
2933 #
2934 # pickups       Allow connections to be picked up in the middle, even if
2935 #               no window scaling information is known.  Such connections
2936 #               will disable sequence space checks.  Implies no flag
2937 #               restrictions.
2938 #
2939 # hash-only     Do not fail packets on sequence space checks.  Implies no
2940 #               flag restrictions.
2941
2942 pass in on $ext_if proto tcp ... keep state (no-pickups)
2943 pass in on $ext_if proto tcp ... keep state (pickups)
2944 pass in on $ext_if proto tcp ... keep state (hash-only)
2945
2946 # Packet Tagging
2947
2948 # three interfaces: $int_if, $ext_if, and $wifi_if (wireless). NAT is
2949 # being done on $ext_if for all outgoing packets. tag packets in on
2950 # $int_if and pass those tagged packets out on $ext_if.  all other
2951 # outgoing packets (i.e., packets from the wireless network) are only
2952 # permitted to access port 80.
2953
2954 pass in on $int_if from any to any tag INTNET
2955 pass in on $wifi_if from any to any
2956
2957 block out on $ext_if from any to any
2958 pass out quick on $ext_if tagged INTNET
2959 pass out on $ext_if proto tcp from any to any port 80
2960
2961 # tag incoming packets as they are redirected to spamd(8). use the tag
2962 # to pass those packets through the packet filter.
2963
2964 rdr on $ext_if inet proto tcp from \*(Ltspammers\*(Gt to port smtp \e
2965         tag SPAMD -\*(Gt 127.0.0.1 port spamd
2966
2967 block in on $ext_if
2968 pass in on $ext_if inet proto tcp tagged SPAMD
2969 .Ed
2970 .Sh GRAMMAR
2971 Syntax for
2972 .Nm
2973 in BNF:
2974 .Bd -literal
2975 line           = option | pf-rule | nat-rule | binat-rule | rdr-rule |
2976                  antispoof-rule | altq-rule | queue-rule | trans-anchors |
2977                  anchor-rule | anchor-close | load-anchor | table-rule | include
2978
2979 option         = "set" ( [ "timeout" ( timeout | "{" timeout-list "}" ) ] |
2980                  [ "ruleset-optimization" [ "none" | "basic" | "profile" ] ] |
2981                  [ "optimization" [ "default" | "normal" |
2982                  "high-latency" | "satellite" |
2983                  "aggressive" | "conservative" ] ]
2984                  [ "limit" ( limit-item | "{" limit-list "}" ) ] |
2985                  [ "loginterface" ( interface-name | "none" ) ] |
2986                  [ "block-policy" ( "drop" | "return" ) ] |
2987                  [ "keep-policy" keep ] |
2988                  [ "state-policy" ( "if-bound" | "floating" ) ]
2989                  [ "require-order" ( "yes" | "no" ) ]
2990                  [ "fingerprints" filename ] |
2991                  [ "skip on" ( interface-name | "{" interface-list "}" ) ] |
2992                  [ "debug" ( "none" | "urgent" | "misc" | "loud" ) ] )
2993
2994 pf-rule        = action [ "in" | "out" ]
2995                  [ "log" [ "(" logopts ")"] ] [ "quick" ]
2996                  [ "on" ifspec ] [ "fastroute" | route ] [ af ] [ protospec ]
2997                  hosts [ filteropt-list ]
2998
2999 logopts        = logopt [ "," logopts ]
3000 logopt         = "all" | "user" | "to" interface-name
3001
3002 filteropt-list = filteropt-list filteropt | filteropt
3003 filteropt      = user | group | flags | icmp-type | icmp6-type | tos |
3004                  keep | "fragment" | "no-df" | "min-ttl" number |
3005                  "max-mss" number | "random-id" | "reassemble tcp" |
3006                  fragmentation | "allow-opts" |
3007                  "label" string | "tag" string | [ ! ] "tagged" string |
3008                  "queue" ( string | "(" string [ [ "," ] string ] ")" ) |
3009                  "probability" number"%"
3010
3011 keep           = "no" "state" |
3012                  ( "keep" | "modulate" | "synproxy" ) "state"
3013                  [ "(" state-opts ")" ]
3014
3015 nat-rule       = [ "no" ] "nat" [ "pass" [ "log" [ "(" logopts ")" ] ] ]
3016                  [ "on" ifspec ] [ af ]
3017                  [ protospec ] hosts [ "tag" string ] [ "tagged" string ]
3018                  [ "-\*(Gt" ( redirhost | "{" redirhost-list "}" )
3019                  [ portspec ] [ pooltype ] [ "static-port" ] ]
3020
3021 binat-rule     = [ "no" ] "binat" [ "pass" [ "log" [ "(" logopts ")" ] ] ]
3022                  [ "on" interface-name ] [ af ]
3023                  [ "proto" ( proto-name | proto-number ) ]
3024                  "from" address [ "/" mask-bits ] "to" ipspec
3025                  [ "tag" string ] [ "tagged" string ]
3026                  [ "-\*(Gt" address [ "/" mask-bits ] ]
3027
3028 rdr-rule       = [ "no" ] "rdr" [ "pass" [ "log" [ "(" logopts ")" ] ] ]
3029                  [ "on" ifspec ] [ af ]
3030                  [ protospec ] hosts [ "tag" string ] [ "tagged" string ]
3031                  [ "-\*(Gt" ( redirhost | "{" redirhost-list "}" )
3032                  [ portspec ] [ pooltype ] ]
3033
3034 antispoof-rule = "antispoof" [ "log" ] [ "quick" ]
3035                  "for" ( interface-name | "{" interface-list "}" )
3036                  [ af ] [ "label" string ]
3037
3038 table-rule     = "table" "\*(Lt" string "\*(Gt" [ tableopts-list ]
3039 tableopts-list = tableopts-list tableopts | tableopts
3040 tableopts      = "persist" | "const" | "counters" | "file" string |
3041                  "{" [ tableaddr-list ] "}"
3042 tableaddr-list = tableaddr-list [ "," ] tableaddr-spec | tableaddr-spec
3043 tableaddr-spec = [ "!" ] tableaddr [ "/" mask-bits ]
3044 tableaddr      = hostname | ipv4-dotted-quad | ipv6-coloned-hex |
3045                  interface-name | "self"
3046
3047 altq-rule      = "altq on" interface-name queueopts-list
3048                  "queue" subqueue
3049 queue-rule     = "queue" string [ "on" interface-name ] queueopts-list
3050                  subqueue
3051
3052 anchor-rule    = "anchor" string [ "in" | "out" ] [ "on" ifspec ]
3053                  [ af ] [ "proto" ] [ protospec ] [ hosts ]
3054
3055 trans-anchors  = ( "nat-anchor" | "rdr-anchor" | "binat-anchor" ) string
3056                  [ "on" ifspec ] [ af ] [ "proto" ] [ protospec ] [ hosts ]
3057
3058 load-anchor    = "load anchor" string "from" filename
3059
3060 queueopts-list = queueopts-list queueopts | queueopts
3061 queueopts      = "bandwidth" bandwidth-spec |
3062                  "qlimit" number | "tbrsize" number |
3063                  "priority" number | schedulers
3064 schedulers     = cbq-def | hfsc-def | priq-def | fairq-def
3065 bandwidth-spec = "number" ( "b" | "Kb" | "Mb" | "Gb" | "%" )
3066
3067 action         = "pass" | "block" [ return ] | [ "no" ] "scrub"
3068 return         = "drop" | "return" | "return-rst" [ "( ttl" number ")" ] |
3069                  "return-icmp" [ "(" icmpcode [ [ "," ] icmp6code ] ")" ] |
3070                  "return-icmp6" [ "(" icmp6code ")" ]
3071 icmpcode       = icmp-code-name | icmp-code-number
3072 icmp6code      = icmp6-code-name | icmp6-code-number
3073
3074 ifspec         = ( [ "!" ] interface-name ) | "{" interface-list "}"
3075 interface-list = [ "!" ] interface-name [ [ "," ] interface-list ]
3076 route          = ( "route-to" | "reply-to" | "dup-to" )
3077                  ( routehost | "{" routehost-list "}" )
3078                  [ pooltype ]
3079 af             = "inet" | "inet6"
3080
3081 protospec      = "proto" ( proto-name | proto-number |
3082                  "{" proto-list "}" )
3083 proto-list     = ( proto-name | proto-number ) [ [ "," ] proto-list ]
3084
3085 hosts          = "all" |
3086                  "from" ( "any" | "no-route" | "urpf-failed" | "self" | host |
3087                  "{" host-list "}" | "route" string ) [ port ] [ os ]
3088                  "to"   ( "any" | "no-route" | "self" | host |
3089                  "{" host-list "}" | "route" string ) [ port ]
3090
3091 ipspec         = "any" | host | "{" host-list "}"
3092 host           = [ "!" ] ( address [ "/" mask-bits ] | "\*(Lt" string "\*(Gt" )
3093 redirhost      = address [ "/" mask-bits ]
3094 routehost      = "(" interface-name [ address [ "/" mask-bits ] ] ")"
3095 address        = interface-name | "(" interface-name ")" | hostname |
3096                  ipv4-dotted-quad | ipv6-coloned-hex
3097 host-list      = host [ [ "," ] host-list ]
3098 redirhost-list = redirhost [ [ "," ] redirhost-list ]
3099 routehost-list = routehost [ [ "," ] routehost-list ]
3100
3101 port           = "port" ( unary-op | binary-op | "{" op-list "}" )
3102 portspec       = "port" ( number | name ) [ ":" ( "*" | number | name ) ]
3103 os             = "os" ( os-name | "{" os-list "}" )
3104 user           = "user" ( unary-op | binary-op | "{" op-list "}" )
3105 group          = "group" ( unary-op | binary-op | "{" op-list "}" )
3106
3107 unary-op       = [ "=" | "!=" | "\*(Lt" | "\*(Le" | "\*(Gt" | "\*(Ge" ]
3108                  ( name | number )
3109 binary-op      = number ( "\*(Lt\*(Gt" | "\*(Gt\*(Lt" | ":" ) number
3110 op-list        = ( unary-op | binary-op ) [ [ "," ] op-list ]
3111
3112 os-name        = operating-system-name
3113 os-list        = os-name [ [ "," ] os-list ]
3114
3115 flags          = "flags" ( [ flag-set ] "/" flag-set | "any" )
3116 flag-set       = [ "F" ] [ "S" ] [ "R" ] [ "P" ] [ "A" ] [ "U" ] [ "E" ]
3117                  [ "W" ]
3118
3119 icmp-type      = "icmp-type" ( icmp-type-code | "{" icmp-list "}" )
3120 icmp6-type     = "icmp6-type" ( icmp-type-code | "{" icmp-list "}" )
3121 icmp-type-code = ( icmp-type-name | icmp-type-number )
3122                  [ "code" ( icmp-code-name | icmp-code-number ) ]
3123 icmp-list      = icmp-type-code [ [ "," ] icmp-list ]
3124
3125 tos            = ( "lowdelay" | "throughput" | "reliability" |
3126                  [ "0x" ] number )
3127
3128 state-opts     = state-opt [ [ "," ] state-opts ]
3129 state-opt      = "max" number | "no-sync" | timeout |
3130                  "source-track" [ "rule" | "global" ] |
3131                  "max-src-nodes" number | "max-src-states" number |
3132                  "max-src-conn" number |
3133                  "max-src-conn-rate" number "/" number |
3134                  "overload" "\*(Lt" string "\*(Gt" [ "flush" ] |
3135                  "if-bound" | "floating" |
3136                  "pickups" | "no-pickups" | "hash-only"
3137
3138 fragmentation  = [ "fragment reassemble" | "fragment crop" |
3139                  "fragment drop-ovl" ]
3140
3141 timeout-list   = timeout [ [ "," ] timeout-list ]
3142 timeout        = ( "tcp.first" | "tcp.opening" | "tcp.established" |
3143                  "tcp.closing" | "tcp.finwait" | "tcp.closed" |
3144                  "udp.first" | "udp.single" | "udp.multiple" |
3145                  "icmp.first" | "icmp.error" |
3146                  "other.first" | "other.single" | "other.multiple" |
3147                  "frag" | "interval" | "src.track" |
3148                  "adaptive.start" | "adaptive.end" ) number
3149
3150 limit-list     = limit-item [ [ "," ] limit-list ]
3151 limit-item     = ( "states" | "frags" | "src-nodes" ) number
3152
3153 pooltype       = ( "bitmask" | "random" |
3154                  "source-hash" [ hex-key | string-key ] |
3155                  "round-robin" ) [ sticky-address ]
3156
3157 subqueue       = string | "{" queue-list "}"
3158 queue-list     = string [ [ "," ] string ]
3159
3160 cbq-def        = "cbq" [ "(" cbq-opts ")" ]
3161 priq-def       = "priq" [ "(" priq-opts ")" ]
3162 hfsc-def       = "hfsc" [ "(" hfsc-opts ")" ]
3163 fairq-def      = "fairq" [ "(" fairq-opts ")" ]
3164
3165 cbq-opts       = cbq-opt [ [ "," ] cbq-opts ]
3166 priq-opts      = priq-opt [ [ "," ] priq-opts ]
3167 hfsc-opts      = hfsc-opt [ [ "," ] hfsc-opts ]
3168 fairq-opts     = fairq-opt [ [ "," ] fairq-opts ]
3169
3170 cbq-opt        = "default" | "borrow" | "red" | "ecn" | "rio"
3171 priq-opt       = "default" | "red" | "ecn" | "rio"
3172 hfsc-opt       = "default" | "red" | "ecn" | "rio" |
3173                  linkshare-sc | realtime-sc | upperlimit-sc
3174 fairq-opt      = "default" | "red" | "ecn" | "rio" |
3175                  "buckets" number | "hogs" number | linkshare-sc
3176
3177 linkshare-sc   = "linkshare" sc-spec
3178 realtime-sc    = "realtime" sc-spec
3179 upperlimit-sc  = "upperlimit" sc-spec
3180 sc-spec        = ( bandwidth-spec |
3181                  "(" bandwidth-spec number bandwidth-spec ")" )
3182 include        = "include" filename
3183 .Ed
3184 .Sh FILES
3185 .Bl -tag -width ".Pa /usr/share/examples/pf" -compact
3186 .It Pa /etc/hosts
3187 Host name database.
3188 .It Pa /etc/pf.conf
3189 Default location of the ruleset file.
3190 .It Pa /etc/pf.os
3191 Default location of OS fingerprints.
3192 .It Pa /etc/protocols
3193 Protocol name database.
3194 .It Pa /etc/services
3195 Service name database.
3196 .It Pa /usr/share/examples/pf
3197 Example rulesets.
3198 .El
3199 .Sh SEE ALSO
3200 .Xr carp 4 ,
3201 .Xr icmp 4 ,
3202 .Xr icmp6 4 ,
3203 .Xr ip 4 ,
3204 .Xr ip6 4 ,
3205 .Xr pf 4 ,
3206 .Xr pfsync 4 ,
3207 .Xr route 4 ,
3208 .Xr tcp 4 ,
3209 .Xr udp 4 ,
3210 .Xr hosts 5 ,
3211 .Xr pf.os 5 ,
3212 .Xr protocols 5 ,
3213 .Xr services 5 ,
3214 .Xr ftp-proxy 8 ,
3215 .Xr pfctl 8 ,
3216 .Xr pflogd 8 ,
3217 .Xr route 8
3218 .Sh HISTORY
3219 The
3220 .Nm
3221 file format first appeared in
3222 .Ox 3.0 .