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