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