fix previous NEWS commit, oops
[ferm.git] / doc / ferm.pod
blob97c550c25c1cddb6123491b9cedeaedb3e391599
2 # ferm pod manual file
6 # ferm, a firewall setup program that makes firewall rules easy!
8 # Copyright 2001-2017 Max Kellermann, Auke Kok
10 # Bug reports and patches for this program may be sent to the GitHub
11 # repository: L<https://github.com/MaxKellermann/ferm>
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 2 of the License, or
18 # (at your option) any later version.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1301 USA.
31 =head1 NAME
33 B<ferm> - a firewall rule parser for linux
35 =head1 SYNOPSIS
37 B<ferm> I<options> I<inputfile>
39 =head1 DESCRIPTION
41 B<ferm> is a frontend for B<iptables>. It reads the rules from a
42 structured configuration file and calls iptables(8) to insert them
43 into the running kernel.
45 B<ferm>'s goal is to make firewall rules easy to write and easy to
46 read. It tries to reduce the tedious task of writing down rules, thus
47 enabling the firewall administrator to spend more time on developing
48 good rules than the proper implementation of the rule.
50 To achieve this, B<ferm> uses a simple but powerful configuration
51 language, which allows variables, functions, arrays, blocks. It also
52 allows you to include other files, allowing you to create libraries of
53 commonly used structures and functions.
55 B<ferm>, pronounced "firm", stands for "For Easy Rule Making".
58 =head1 CAUTION
60 This manual page does I<not> indend to teach you how firewalling works
61 and how to write good rules.  There is already enough documentation on
62 this topic.
65 =head1 INTRODUCTION
67 Let's start with a simple example:
69     chain INPUT {
70         proto tcp ACCEPT;
71     }
73 This will add a rule to the predefined input chain, matching and
74 accepting all tcp packets.  Ok, let's make it more complicated:
76     chain (INPUT OUTPUT) {
77         proto (udp tcp) ACCEPT;
78     }
80 This will insert 4 rules, namely 2 in chain input, and 2 in chain
81 output, matching and accepting both udp and tcp packets.  Normally you
82 would type this:
84    iptables -A INPUT -p tcp -j ACCEPT
85    iptables -A OUTPUT -p tcp -j ACCEPT
86    iptables -A INPUT -p udp -j ACCEPT
87    iptables -A OUTPUT -p udp -j ACCEPT
89 Note how much less typing we need to do? :-)
91 Basically, this is all there is to it, although you can make it quite
92 more complex. Something to look at:
94    chain INPUT {
95        policy ACCEPT;
96        daddr 10.0.0.0/8 proto tcp dport ! ftp jump mychain sport :1023 TOS 4 settos 8 mark 2;
97        daddr 10.0.0.0/8 proto tcp dport ftp REJECT;
98    }
100 My point here is, that *you* need to make nice rules, keep
101 them readable to you and others, and not make it into a mess.
103 It would aid the reader if the resulting firewall rules were placed
104 here for reference. Also, you could include the nested version with
105 better readability.
107 Try using comments to show what you are doing:
109     # this line enables transparent http-proxying for the internal network:
110     proto tcp if eth0 daddr ! 192.168.0.0/255.255.255.0
111         dport http REDIRECT to-ports 3128;
113 You will be thankful for it later!
115     chain INPUT {
116         policy ACCEPT;
117         interface (eth0 ppp0) {
118             # deny access to notorius hackers, return here if no match
119             # was found to resume normal firewalling
120             jump badguys;
122             protocol tcp jump fw_tcp;
123             protocol udp jump fw_udp;
124         }
125     }
127 The more you nest, the better it looks. Make sure the order you
128 specify is correct, you would not want to do this:
130     chain FORWARD {
131         proto ! udp DROP;
132         proto tcp dport ftp ACCEPT;
133     }
135 because the second rule will never match. Best way is to specify
136 first everyting that is allowed, and then deny everything else.
137 Look at the examples for more good snapshots. Most people do
138 something like this:
140     proto tcp {
141         dport (
142             ssh http ftp
143         ) ACCEPT;
144         dport 1024:65535 ! syn ACCEPT;
145         DROP;
146     }
148 =head1 STRUCTURE OF A FIREWALL FILE
150 The structure of a proper firewall file looks like  simplified
151 C-code. Only a few syntactic characters are used in ferm-
152 configuration files. Besides these special caracters, ferm
153 uses 'keys' and 'values', think of them as options and
154 parameters, or as variables and values, whatever.
156 With these words, you define the characteristics of your firewall.
157 Every firewall consists of two things: First, look if network
158 traffic matches certain conditions, and second, what to do
159 with that traffic.
161 You may specify conditions that are valid for the kernel
162 interface program you are using, probably iptables(8). For
163 instance, in iptables, when you are trying to match tcp
164 packets, you would say:
166     iptables --protocol tcp
168 In ferm, this will become:
170     protocol tcp;
172 Just typing this in ferm doesn't do anything, you need to tell
173 ferm (actually, you need to tell iptables(8) and the kernel) what
174 to do with any traffic that matches this condition:
176     iptables --protocol tcp -j ACCEPT
178 Or, translated to B<ferm>:
180     protocol tcp ACCEPT;
182 The B<;> character is at the end of every ferm rule. Ferm ignores line
183 breaks, meaning the above example is identical to the following:
185     protocol tcp
186       ACCEPT;
188 Here's a list of the special characters:
190 =over 8
192 =item B<;>
194 This character finalizes a rule.
196 Separated by semicolons, you may write multiple rules in one line,
197 although this decreases readability:
199     protocol tcp ACCEPT; protocol udp DROP;
201 =item B<{}>
203 The nesting symbol defines a 'block' of rules.
205 The curly brackets contain any number of nested rules. All matches
206 before the block are carried forward to these.
208 The closing curly bracket finalizes the rule set. You should not write
209 a ';' after that, because that would be an empty rule.
211 Example:
213     chain INPUT proto icmp {
214         icmp-type echo-request ACCEPT;
215         DROP;
216     }
218 This block shows two rules inside a block, which will both be merged
219 with anything in front of it, so you will get two rules:
221     iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
222     iptables -A INPUT -p icmp -j DROP
224 There can be multiple nesting levels:
226     chain INPUT {
227         proto icmp {
228             icmp-type echo-request ACCEPT;
229             DROP;
230         }
231         daddr 172.16.0.0/12 REJECT;
232     }
234 Note that the 'REJECT' rule is not affected by 'proto icmp', although
235 there is no ';' after the closing curly brace. Translated to iptables:
237     iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
238     iptables -A INPUT -p icmp -j DROP
239     iptables -A INPUT -d 172.16.0.0/12 -j REJECT
241 =item B<$>
243 Variable expansion. Replaces '$FOO' by the value of the variable. See
244 the section I<VARIABLES> for details.
246 =item B<&>
248 Function call. See the section I<FUNCTIONS> for details.
250 =item B<()>
252 The array symbol. Using the parentheses, you can define
253 a 'list' of values that should be applied for the key to the
254 left of it.
256 Example:
258     protocol ( tcp udp icmp )
260 this will result in three rules:
262     ... -p tcp ...
263     ... -p udp ...
264     ... -p icmp ...
266 Only values can be 'listed', so you cannot do something like this:
268     proto tcp ( ACCEPT LOG );
270 but you can do this:
272     chain (INPUT OUTPUT FORWARD) proto (icmp udp tcp) DROP;
274 (which will result in nine rules!)
276 Values are separated by spaces. The array symbol is both left- and
277 right-associative, in contrast with the nesting block, which is
278 left-associative only.
280 =item C< # >
282 The comment symbol. Anything that follows this symbol up to
283 the end of line is ignored.
285 =item C<`command`>
287 Execute the command in a shell, and insert the process output. See the
288 section I<backticks> for details.
290 =item C<'string'>
292 Quote a string which may contain whitespaces, the dollar sign etc.
294     LOG log-prefix ' hey, this is my log prefix!';
296 =item C<"string">
298 Quote a string (see above), but variable references with a dollar sign
299 are evaluated:
301     DNAT to "$myhost:$myport";
303 =back
306 =head2 Keywords
308 In the previous section, we already introduced some basic keywords
309 like "chain", "protocol" and "ACCEPT". Let's explore their nature.
311 There are three kinds of keywords:
313 =over 8
315 =item
317 B<location> keywords define where a rule will be created. Example:
318 "table", "chain".
320 =item
322 B<match> keywords perform a test on all passing packets. The current
323 rule is without effect if one (or more) of the matches does not
324 pass. Example: "proto", "daddr".
326 Most matches are followed by a parameter: "proto tcp", "daddr
327 172.16.0.0/12".
329 =item
331 B<target> keywords state what to do with a packet. Example: "ACCEPT",
332 "REJECT", "jump".
334 Some targets define more keywords to specify details: "REJECT
335 reject-with icmp-net-unreachable".
337 =back
339 Every rule consists of a B<location> and a B<target>, plus any number
340 of B<matches>:
342     table filter                  # location
343     proto tcp dport (http https)  # match
344     ACCEPT;                       # target
346 Strictly speaking, there is a fourth kind: B<ferm> keywords (which
347 control ferm's internal behaviour), but they will be explained later.
350 =head2 Parameters
352 Many keywords take parameters. These can be specified as literals,
353 variable references or lists (arrays):
355     proto udp
356     saddr $TRUSTED_HOSTS;
357     proto tcp dport (http https ssh);
358     LOG log-prefix "funky wardriver alert: ";
360 Some of them can be negated (lists cannot be negated):
362     proto !esp;
363     proto udp dport !domain;
365 Keywords which take no parameters are negated by a prefixed '!':
367     proto tcp !syn;
369 Read iptables(8) to see where the B<!> can be used.
372 =head1 BASIC KEYWORDS
375 =head2 Location keywords
377 =over 8
379 =item B<domain [ip|ip6]>
381 Set the domain. "ip" is default and means "IPv4" (iptables). "ip6" is
382 for IPv6 support, using "ip6tables".
384 =item B<table [filter|nat|mangle]>
386 Specifies which netfilter table this rule will be inserted to:
387 "filter" (default), "nat" or "mangle".
389 =item B<chain [chain-name]>
391 Specifies the netfilter chain (within the current table) this rule
392 will be inserted to. Common predefined chain names are "INPUT",
393 "OUTPUT", "FORWARD", "PREROUTING", "POSTROUTING", depending on the
394 table. See the netfilter documentation for details.
396 If you specify a non-existing chain here, ferm will add the rule to a
397 custom chain with that name.
399 =item B<policy [ACCEPT|DROP|..]>
401 Specifies the default policy for the current chain (built-in
402 only). Can be one of the built-in targets (ACCEPT, DROP, REJECT,
403 ...). A packet that matches no rules in a chain will be treated as
404 specified by the policy.
406 To avoid ambiguity, always specify the policies of all predefined
407 chains explicitly.
409 =item B<@subchain ["CHAIN-NAME"] { ... }>
411 Works like the normal block operators (i.e. without the I<@subchain>
412 keyword), except that B<ferm> moves rules within the curly braces into
413 a new custom chain. The name for this chain is chosen automatically by
414 ferm.
416 In many cases, this is faster than just a block, because the kernel
417 may skip a huge block of rules when a precondition is false. Imagine
418 the following example:
420  table filter chain INPUT {
421      saddr (1.2.3.4 2.3.4.5 3.4.5.6 4.5.6.7 5.6.7.8) {
422          proto tcp dport (http https ssh) ACCEPT;
423          proto udp dport domain ACCEPT;
424      }
427 This generates 20 rules. When a packet arrives which does not pass the
428 B<saddr> match, it nonetheless checks all 20 rules. With B<@subchain>,
429 this check is done once, resulting in faster network filtering and
430 less CPU load:
432  table filter chain INPUT {
433      saddr (1.2.3.4 2.3.4.5 3.4.5.6 4.5.6.7 5.6.7.8) @subchain {
434          proto tcp dport (http https ssh) ACCEPT;
435          proto udp dport domain ACCEPT;
436      }
439 Optionally, you may define the name of the sub chain:
441  saddr (1.2.3.4 2.3.4.5 3.4.5.6) @subchain "foobar" {
442      proto tcp dport (http https ssh) ACCEPT;
443      proto udp dport domain ACCEPT;
446 The name can either be a quoted string literal, or an expanded ferm
447 expression such as @cat("interface_", $iface) or @substr($var,0,20).
449 You can achieve the same by explicitly declaring a custom chain, but
450 you may feel that using B<@subchain> requires less typing.
452 =item B<@gotosubchain ["CHAIN-NAME"] { ... }>
454 Works like B<@subchain> except that instead of using B<jump> target it
455 uses B<goto> target. See discussion below for the difference between
456 these two targets.
458 =item B<@preserve>
460 Preserve existing rules of the current chain:
462  chain (foo bar) @preserve;
464 With this option, B<ferm> loads the previous rule set using
465 B<iptables-save>, extracts all "preserved" chains and inserts their
466 data into the output.
468 "Preserved" chains must not be modified with B<ferm>: no rules and no
469 policies.
471 =back
474 =head2 Basic iptables match keywords
476 =over 8
478 =item B<interface [interface-name]>
480 Define the interface name, your outside network card, like eth0,
481 or dialup like ppp1, or whatever device you want to match for
482 passing packets. It is equivalent to the C<-i> switch in
483 iptables(8).
485 =item B<outerface [interface-name]>
487 Same as interface, only for matching the outgoing interface
488 for a packet, as in iptables(8).
490 =item B<protocol [protocol-name|protocol-number]>
492 Currently supported by the kernel are tcp, udp and icmp, or
493 their respective numbers.
495 =item B<saddr|daddr [address-spec]>
497 Matches on packets originating from the specified address (saddr) or
498 targeted at the address (daddr).
500 Examples:
502     saddr 192.168.0.0/24 ACCEPT; # (identical to the next one:)
503     saddr 192.168.0.0/255.255.255.0 ACCEPT;
504     daddr my.domain.com ACCEPT;
506 =item B<fragment>
508 Specify that only fragmented IP packets should be matched.
509 When packets are larger that the maximum packet size your
510 system can handle (called Maximum Transmission Unit or MTU)
511 they will be chopped into bits and sent one by one as single
512 packets. See ifconfig(8) if you want to find the MTU for
513 your system (the default is usually 1500 bytes).
515 Fragments are frequently used in DOS attacks, because there
516 is no way of finding out the origin of a fragment packet.
518 =item B<sport|dport [port-spec]>
520 Matches on packets on the specified TCP or UDP port. "sport" matches
521 the source port, and dport matches the destination port.
523 This match can be used only after you specified "protocol tcp" or
524 "protocol udp", because only these two protocols actually have ports.
526 And some examples of valid ports/ranges:
528     dport 80 ACCEPT;
529     dport http ACCEPT;
530     dport ssh:http ACCEPT;
531     dport 0:1023 ACCEPT; # equivalent to :1023
532     dport 1023:65535 ACCEPT;
534 =item B<syn>
536 Specify that the SYN flag in a tcp package should be matched,
537 which are used to build new tcp connections. You can identify
538 incoming connections with this, and decide whether you want
539 to allow it or not. Packets that do not have this flag are
540 probably from an already established connection, so it's
541 considered reasonably safe to let these through.
543 =item B<module [module-name]>
545 Load an iptables module. Most modules provide more match
546 keywords. We'll get to that later.
548 =back
551 =head2 Basic target keywords
553 =over 8
555 =item B<jump [custom-chain-name]>
557 Jumps to a custom chain. If no rule in the custom chain matched,
558 netfilter returns to the next rule in the previous chain.
560 =item B<goto [custom-chain-name]>
562 Go to a custom chain.  Unlike the B<jump> option, B<RETURN> will not
563 continue processing in this chain but instead in the chain that called
564 us via B<jump>.
566 =item B<ACCEPT>
568 Accepts matching packets.
570 =item B<DROP>
572 Drop matching packets without further notice.
574 =item B<REJECT>
576 Rejects matching packets, i.e. send an ICMP packet to the sender,
577 which is port-unreachable by default. You may specify another ICMP
578 type.
580     REJECT; # default to icmp-port-unreachable
581     REJECT reject-with icmp-net-unreachable;
583 Type "iptables -j REJECT -h" for details.
585 =item B<RETURN>
587 Finish the current chain and return to the calling chain (if "jump
588 [custom-chain-name]" was used).
590 =item B<NOP>
592 No action at all.
594 =back
597 =head1 ADDITIONAL KEYWORDS
599 Netfilter is modular. Modules may provide additional targets and match
600 keywords. The list of netfilter modules is constantly growing, and
601 ferm tries to keep up with supporting them all. This chapter describes
602 modules which are currently supported.
605 =head2 iptables match modules
607 =over 8
609 =item B<account>
611 Account traffic for all hosts in defined network/netmask.  This is one
612 of the match modules which behave like a target, i.e. you will mostly
613 have to use the B<NOP> target.
615     mod account aname mynetwork aaddr 192.168.1.0/24 ashort NOP;
617 =item B<addrtype>
619 Check the address type; either source address or destination address.
621     mod addrtype src-type BROADCAST;
622     mod addrtype dst-type LOCAL;
624 Type "iptables -m addrtype -h" for details.
626 =item B<ah>
628 Checks the SPI header in an AH packet.
630     mod ah ahspi 0x101;
631     mod ah ahspi ! 0x200:0x2ff;
633 Additional arguments for IPv6:
635     mod ah ahlen 32 ACCEPT;
636     mod ah ahlen !32 ACCEPT;
637     mod ah ahres ACCEPT;
639 =item B<bpf>
641 Match using Linux Socket Filter.
643     mod bpf bytecode "4,48 0 0 9,21 0 1 6,6 0 0 1,6 0 0 0";
645 =item B<cgroup>
647 Match using cgroupsv2 hierarchy or legacy net_cls cgroup.
649     mod cgroup path ! example/path ACCEPT;
651 The path is relative to the root of the cgroupsv2 hiearchy, and is compared
652 against the initial portion of a process' path in the hierarchy.
654     mod cgroup cgroup 10:10 DROP;
655     mod cgroup cgroup 1048592 DROP;
657 Matches against the value of C<net_cls.classid> set on the process' legacy
658 net_cls cgroup. The class may be specified as a hexadecimal major:minor pair
659 (see L<tc(8)>), or as a decimal, so those two rules are equivalent.
661 =item B<comment>
663 Adds a comment of up to 256 characters to a rule, without an effect.
664 Note that unlike ferm comments ('#'), this one will show up in
665 "iptables -L".
667     mod comment comment "This is my comment." ACCEPT;
669 =item B<condition>
671 Matches if a value in /proc/net/ipt_condition/NAME is 1 (path is
672 /proc/net/ip6t_condition/NAME for the ip6 domain).
674     mod condition condition (abc def) ACCEPT;
675     mod condition condition !foo ACCEPT;
677 =item B<connbytes>
679 Match by how many bytes or packets a connection (or one of the two
680 flows constituting the connection) have tranferred so far, or by
681 average bytes per packet.
683     mod connbytes connbytes 65536: connbytes-dir both connbytes-mode bytes ACCEPT;
684     mod connbytes connbytes !1024:2048 connbytes-dir reply connbytes-mode packets ACCEPT;
686 Valid values for I<connbytes-dir>: I<original>, I<reply>, I<both>; for
687 I<connbytes-mode>: I<packets>, I<bytes>, I<avgpkt>.
689 =item B<connlabel>
691 Module matches or adds connlabels to a connection.
693     mod connlabel label "name";
694     mod connlabel label "name" set;
696 =item B<connlimit>
698 Allows you to restrict the number of parallel TCP connections to a
699 server per client IP address (or address block).
701     mod connlimit connlimit-above 4 REJECT;
702     mod connlimit connlimit-above !4 ACCEPT;
703     mod connlimit connlimit-above 4 connlimit-mask 24 REJECT;
704     mod connlimit connlimit-upto 4 connlimit-saddr REJECT;
705     mod connlimit connlimit-above 4 connlimit-daddr REJECT;
707 =item B<connmark>
709 Check the mark field associated with the connection, set by the
710 CONNMARK target.
712     mod connmark mark 64;
713     mod connmark mark 6/7;
715 =item B<conntrack>
717 Check connection tracking information.
719     mod conntrack ctstate (ESTABLISHED RELATED);
720     mod conntrack ctproto tcp;
721     mod conntrack ctorigsrc 192.168.0.2;
722     mod conntrack ctorigdst 1.2.3.0/24;
723     mod conntrack ctorigsrcport 67;
724     mod conntrack ctorigdstport 22;
725     mod conntrack ctreplsrc 2.3.4.5;
726     mod conntrack ctrepldst ! 3.4.5.6;
727     mod conntrack ctstatus ASSURED;
728     mod conntrack ctexpire 60;
729     mod conntrack ctexpire 180:240;
731 Type "iptables -m conntrack -h" for details.
733 =item B<cpu>
735 Match cpu handling this packet.
737     mod cpu cpu 0;
739 =item B<dccp>
741 Check DCCP (Datagram Congestion Control Protocol) specific attributes.
742 This module is automatically loaded when you use "protocol dccp".
744     proto dccp sport 1234 dport 2345 ACCEPT;
745     proto dccp dccp-types (SYNCACK ACK) ACCEPT;
746     proto dccp dccp-types !REQUEST DROP;
747     proto dccp dccp-option 2 ACCEPT;
749 =item B<dscp>
751 Match the 6 bit DSCP field within the TOS field.
753     mod dscp dscp 11;
754     mod dscp dscp-class AF41;
756 =item B<dst>
758 Match the parameters in Destination Options header (IPv6).
760     mod dst dst-len 10;
761     mod dst dst-opts (type1 type2 ...);
763 =item B<ecn>
765 Match the ECN bits of an IPv4 TCP header.
767     mod ecn ecn-tcp-cwr;
768     mod ecn ecn-tcp-ece;
769     mod ecn ecn-ip-ect 2;
771 Type "iptables -m ecn -h" for details.
773 =item B<esp>
775 Checks the SPI header in an ESP packet.
777     mod esp espspi 0x101;
778     mod esp espspi ! 0x200:0x2ff;
780 =item B<eui64>
782 "This module matches the EUI-64 part of a stateless autoconfigured
783 IPv6 address.  It compares the EUI-64 derived from the source MAC
784 address in Ehternet frame with the lower 64 bits of the IPv6 source
785 address.  But "Universal/Local" bit is not compared.  This module
786 doesn't match other link layer frame, and is only valid in the
787 PREROUTING, INPUT and FORWARD chains."
789     mod eui64 ACCEPT;
791 =item B<fuzzy>
793 "This module matches a rate limit based on a fuzzy logic controller [FLC]."
795     mod fuzzy lower-limit 10 upper-limit 20 ACCEPT;
797 =item B<geoip>
799 Matches packets based on their geological location. (Needs an installed
800 GeoDB.)
802     mod geoip src-cc "CN,VN,KR,BH,BR,AR,TR,IN,HK" REJECT;
803     mod geoip dst-cc "DE,FR,CH,AT" ACCEPT;
805 =item B<hbh>
807 Matches the Hop-by-Hop Options header (ip6).
809     mod hbh hbh-len 8 ACCEPT;
810     mod hbh hbh-len !8 ACCEPT;
811     mod hbh hbh-opts (1:4 2:8) ACCEPT;
813 =item B<hl>
815 Matches the Hop Limit field (ip6).
817     mod hl hl-eq (8 10) ACCEPT;
818     mod hl hl-eq !5 ACCEPT;
819     mod hl hl-gt 15 ACCEPT;
820     mod hl hl-lt 2 ACCEPT;
822 =item B<helper>
824 Checks which conntrack helper module tracks this connection.  The port
825 may be specified with "-portnr".
827     mod helper helper irc ACCEPT;
828     mod helper helper ftp-21 ACCEPT;
830 =item B<icmp>
832 Check ICMP specific attributes.  This module is automatically loaded
833 when you use "protocol icmp".
835     proto icmp icmp-type echo-request ACCEPT;
837 This option can also be used in be I<ip6> domain, although this is
838 called B<icmpv6> in F<ip6tables>.
840 Use "iptables -p icmp C<-h>" to obtain a list of valid ICMP types.
842 =item B<iprange>
844 Match a range of IPv4 addresses.
846     mod iprange src-range 192.168.2.0-192.168.3.255;
847     mod iprange dst-range ! 192.168.6.0-192.168.6.255;
849 =item B<ipv4options>
851 Match on IPv4 header options like source routing, record route,
852 timestamp and router-alert.
854     mod ipv4options ssrr ACCEPT;
855     mod ipv4options lsrr ACCEPT;
856     mod ipv4options no-srr ACCEPT;
857     mod ipv4options !rr ACCEPT;
858     mod ipv4options !ts ACCEPT;
859     mod ipv4options !ra ACCEPT;
860     mod ipv4options !any-opt ACCEPT;
862 =item B<ipv6header>
864 Matches the IPv6 extension header (ip6).
866     mod ipv6header header !(hop frag) ACCEPT;
867     mod ipv6header header (auth dst) ACCEPT;
869 =item B<hashlimit>
871 Similar to 'mod limit', but adds the ability to add per-destination or
872 per-port limits managed in a hash table.
874     mod hashlimit  hashlimit 10/minute  hashlimit-burst 30/minute
875       hashlimit-mode dstip  hashlimit-name foobar  ACCEPT;
877 Possible values for hashlimit-mode: dstip dstport srcip srcport (or a
878 list with more than one of these).
880 There are more possible settings, type "iptables -m hashlimit -h" for
881 documentation.
883 =item B<ipvs>
885 Match IPVS connection properties.
887     mod ipvs ipvs ACCEPT; # packet belongs to an IPVS connection
888     mod ipvs vproto tcp ACCEPT; # VIP protocol to match; by number or name, e.g. "tcp
889     mod ipvs vaddr 1.2.3.4/24 ACCEPT; # VIP address to match
890     mod ipvs vport http ACCEPT; # VIP port to match
891     mod ipvs vdir ORIGINAL ACCEPT; # flow direction of packet
892     mod ipvs vmethod GATE ACCEPT; # IPVS forwarding method used
893     mod ipvs vportctl 80; # VIP port of the controlling connection to match
895 =item B<length>
897 Check the package length.
899     mod length length 128; # exactly 128 bytes
900     mod length length 512:768; # range
901     mod length length ! 256; # negated
903 =item B<limit>
905 Limits the packet rate.
907     mod limit limit 1/second;
908     mod limit limit 15/minute limit-burst 10;
910 Type "iptables -m limit -h" for details.
912 =item B<mac>
914 Match the source MAC address.
916     mod mac mac-source 01:23:45:67:89;
918 =item B<mark>
920 Matches packets based on their netfilter mark field. This may be a 32
921 bit integer between 0 and 4294967295.
923     mod mark mark 42;
925 =item B<mh>
927 Matches the mobility header (domain I<ip6>).
929     proto mh mh-type binding-update ACCEPT;
931 =item B<multiport>
933 Match a set of source or destination ports (UDP and TCP only).
935     mod multiport source-ports (https ftp);
936     mod multiport destination-ports (mysql domain);
938 This rule has a big advantage over "dport" and "sport": it generates
939 only one rule for up to 15 ports instead of one rule for every port.
941 =item B<nth>
943 Match every 'n'th packet.
945     mod nth every 3;
946     mod nth counter 5 every 2;
947     mod nth start 2 every 3;
948     mod nth start 5 packet 2 every 6;
950 Type "iptables -m nth -h" for details.
952 =item B<osf>
954 Match packets depending on the operating system of the sender.
956     mod osf genre Linux;
957     mod osf ! genre FreeBSD ttl 1 log 1;
959 Type "iptables -m osf -h" for details.
961 =item B<owner>
963 Check information about the packet creator, namely user id, group id,
964 process id, session id and command name.
966     mod owner uid-owner 0;
967     mod owner gid-owner 1000;
968     mod owner pid-owner 5432;
969     mod owner sid-owner 6543;
970     mod owner cmd-owner "sendmail";
972 ("cmd-owner", "pid-owner" and "sid-owner" require special kernel
973 patches not included in the vanilla Linux kernel)
975 =item B<physdev>
977 Matches the physical device on which a packet entered or is about to
978 leave the machine. This is useful for bridged interfaces.
980     mod physdev physdev-in ppp1;
981     mod physdev physdev-out eth2;
982     mod physdev physdev-is-in;
983     mod physdev physdev-is-out;
984     mod physdev physdev-is-bridged;
986 =item B<pkttype>
988 Check the link-layer packet type.
990     mod pkttype pkt-type unicast;
991     mod pkttype pkt-type broadcase;
992     mod pkttype pkt-type multicast;
994 =item B<policy>
996 Matches IPsec policy being applied to this packet.
998     mod policy dir out pol ipsec ACCEPT;
999     mod policy strict reqid 23 spi 0x10 proto ah ACCEPT;
1000     mod policy mode tunnel tunnel-src 192.168.1.2 ACCEPT;
1001     mod policy mode tunnel tunnel-dst 192.168.2.1 ACCEPT;
1002     mod policy strict next reqid 24 spi 0x11 ACCEPT;
1004 Note that the keyword I<proto> is also used as a shorthand version of
1005 I<protocol> (built-in match module).  You can fix this conflict by
1006 always using the long keyword I<protocol>.
1008 =item B<psd>
1010 Detect TCP/UDP port scans.
1012     mod psd psd-weight-threshold 21 psd-delay-threshold 300
1013       psd-lo-ports-weight 3 psd-hi-ports-weight 1 DROP;
1015 =item B<quota>
1017 Implements network quotas by decrementing a byte counter with each packet.
1019     mod quota quota 65536 ACCEPT;
1021 =item B<random>
1023 Match a random percentage of all packets.
1025     mod random average 70;
1027 =item B<realm>
1029 Match the routing realm. Useful in environments using BGP.
1031     mod realm realm 3;
1033 =item B<recent>
1035 Temporarily mark source IP addresses.
1037     mod recent set;
1038     mod recent rcheck seconds 60;
1039     mod recent set rsource name "badguy";
1040     mod recent set rdest;
1041     mod recent rcheck rsource name "badguy" seconds 60;
1042     mod recent update seconds 120 hitcount 3 rttl;
1043     mod recent mask 255.255.255.0 reap;
1045 This netfilter module has a design flaw: although it is implemented as
1046 a match module, it has target-like behaviour when using the "set"
1047 keyword.
1049 L<http://snowman.net/projects/ipt_recent/>
1051 =item B<rpfilter>
1053 Checks a reply to the packet would be sent via the same interface it arrived on.
1054 Packets from the loopback interface are always permitted.
1056     mod rpfilter proto tcp loose RETURN;
1057     mod rpfilter validmark accept-local RETURN;
1058     mod rpfilter invert DROP;
1060 This netfilter module is the preferred way to perform reverse path filtering for
1061 IPv6, and a powerful alternative to checks controlled by sysctl
1062 I<net.ipv4.conf.*.rp_filter>.
1064 =item B<rt>
1066 Match the IPv6 routing header (ip6 only).
1068     mod rt rt-type 2 rt-len 20 ACCEPT;
1069     mod rt rt-type !2 rt-len !20 ACCEPT;
1070     mod rt rt-segsleft 2:3 ACCEPT;
1071     mod rt rt-segsleft !4:5 ACCEPT;
1072     mod rt rt-0-res rt-0-addrs (::1 ::2) rt-0-not-strict ACCEPT;
1074 =item B<sctp>
1076 Check SCTP (Stream Control Transmission Protocol) specific attributes.
1077 This module is automatically loaded when you use "protocol sctp".
1079     proto sctp sport 1234 dport 2345 ACCEPT;
1080     proto sctp chunk-types only DATA:Be ACCEPT;
1081     proto sctp chunk-types any (INIT INIT_ACK) ACCEPT;
1082     proto sctp chunk-types !all (HEARTBEAT) ACCEPT;
1084 Use "iptables -p sctp C<-h>" to obtain a list of valid chunk types.
1086 =item B<set>
1088 Checks the source or destination IP/Port/MAC against a set.
1090     mod set set badguys src DROP;
1092 See L<http://ipset.netfilter.org/> for more information.
1094 =item B<state>
1096 Checks the connection tracking state.
1098     mod state state INVALID DROP;
1099     mod state state (ESTABLISHED RELATED) ACCEPT;
1101 Type "iptables -m state -h" for details.
1103 =item B<statistic>
1105 Successor of B<nth> and B<random>, currently undocumented in the
1106 iptables(8) man page.
1108     mod statistic mode random probability 0.8 ACCEPT;
1109     mod statistic mode nth every 5 packet 0 DROP;
1111 =item B<string>
1113 Matches a string.
1115     mod string string "foo bar" ACCEPT;
1116     mod string algo kmp from 64 to 128 hex-string "deadbeef" ACCEPT;
1118 =item B<tcp>
1120 Checks TCP specific attributes. This module is automatically loaded
1121 when you use "protocol tcp".
1123     proto tcp sport 1234;
1124     proto tcp dport 2345;
1125     proto tcp tcp-flags (SYN ACK) SYN;
1126     proto tcp tcp-flags ! (SYN ACK) SYN;
1127     proto tcp tcp-flags ALL (RST ACK);
1128     proto tcp syn;
1129     proto tcp tcp-option 2;
1130     proto tcp mss 512;
1132 Type "iptables -p tcp -h" for details.
1134 =item B<tcpmss>
1136 Check the TCP MSS field of a SYN or SYN/ACK packet.
1138     mod tcpmss mss 123 ACCEPT;
1139     mod tcpmss mss 234:567 ACCEPT;
1141 =item B<time>
1143 Check if the time a packet arrives is in given range.
1145     mod time timestart 12:00;
1146     mod time timestop 13:30;
1147     mod time days (Mon Wed Fri);
1148     mod time datestart 2005:01:01;
1149     mod time datestart 2005:01:01:23:59:59;
1150     mod time datestop 2005:04:01;
1151     mod time monthday (30 31);
1152     mod time weekdays (Wed Thu);
1153     mod time timestart 12:00;
1154     mod time timestart 12:00 kerneltz;
1156 Type "iptables -m time -h" for details.
1158 =item B<tos>
1160 Matches a packet on the specified TOS-value.
1162     mod tos tos Minimize-Cost ACCEPT;
1163     mod tos tos !Normal-Service ACCEPT;
1165 Type "iptables -m tos -h" for details.
1167 =item B<ttl>
1169 Matches the ttl (time to live) field in the IP header.
1171     mod ttl ttl-eq 12; # ttl equals
1172     mod ttl ttl-gt 10; # ttl greater than
1173     mod ttl ttl-lt 16; # ttl less than
1175 =item B<u32>
1177 Compares raw data from the packet.  You can specify more than one
1178 filter in a ferm list; these are not expanded into multiple rules.
1180     mod u32 u32 '6&0xFF=1' ACCEPT;
1181     mod u32 u32 ('27&0x8f=7' '31=0x527c4833') DROP;
1183 =item B<unclean>
1185 Matches packets which seem malformed or unusual. This match has no
1186 further parameters.
1188 =back
1191 =head2 iptables target modules
1193 The following additional targets are available in ferm, provided that
1194 you enabled them in your kernel:
1196 =over 8
1198 =item B<CHECKSUM>
1200 Compute packet checksum.
1202     CHECKSUM checksum-fill;
1204 =item B<CLASSIFY>
1206 Set the CBQ class.
1208     CLASSIFY set-class 3:50;
1210 =item B<CLUSTERIP>
1212 Configure a simple cluster of nodes that share a certain IP and MAC
1213 address.  Connections are statically distributed between the nodes.
1215     CLUSTERIP new hashmode sourceip clustermac 00:12:34:45:67:89
1216       total-nodes 4 local-node 2 hash-init 12345;
1218 =item B<CONNMARK>
1220 Sets the netfilter mark value associated with a connection.
1222     CONNMARK set-xmark 42/0xff;
1223     CONNMARK set-mark 42;
1224     CONNMARK save-mark;
1225     CONNMARK restore-mark;
1226     CONNMARK save-mark nfmask 0xff ctmask 0xff;
1227     CONNMARK save-mark mask 0x7fff;
1228     CONNMARK restore-mark mask 0x8000;
1229     CONNMARK and-mark 0x7;
1230     CONNMARK or-mark 0x4;
1231     CONNMARK xor-mark 0x7;
1232     CONNMARK and-mark 0x7;
1234 =item B<CONNSECMARK>
1236 This module copies security markings from packets to connections (if
1237 unlabeled), and from connections back to packets (also only if
1238 unlabeled).  Typically used in conjunction with SECMARK, it is only
1239 valid in the mangle table.
1241     CONNSECMARK save;
1242     CONNSECMARK restore;
1244 =item B<DNAT to [ip-address|ip-range|ip-port-range]>
1246 Change the destination address of the packet.
1248     DNAT to 10.0.0.4;
1249     DNAT to 10.0.0.4:80;
1250     DNAT to 10.0.0.4:1024-2048;
1251     DNAT to 10.0.1.1-10.0.1.20;
1253 =item B<DNPT>
1255 Provides stateless destination IPv6-to-IPv6 Network Prefix Translation.
1257     DNPT src-pfx 2001:42::/16 dst-pfx 2002:42::/16;
1259 =item B<ECN>
1261 This target allows to selectively work around known ECN blackholes.
1262 It can only be used in the mangle table.
1264     ECN ecn-tcp-remove;
1266 =item B<HL>
1268 Modify the IPv6 Hop Limit field (ip6/mangle only).
1270     HL hl-set 5;
1271     HL hl-dec 2;
1272     HL hl-inc 1;
1274 =item B<HMARK>
1276 Like MARK, i.e.  set the fwmark, but the mark is calculated from
1277 hashing packet selector at choice.
1279     HMARK hmark-tuple "src" hmark-mod "1" hmark-offset "1"
1280       hmark-src-prefix 192.168.1.0/24 hmark-dst-prefix 192.168.2.0/24
1281       hmark-sport-mask 0x1234 hmark-dport-mask 0x2345
1282       hmark-spi-mask 0xdeadbeef hmark-proto-mask 0x42 hmark-rnd 0xcoffee;
1284 =item B<IDLETIMER>
1286 This target can be used to identify when interfaces have been idle for
1287 a certain period of time.
1289     IDLETIMER timeout 60 label "foo";
1291 =item B<IPV4OPTSSTRIP>
1293 Strip all the IP options from a packet.  This module does not take any
1294 options.
1296     IPV4OPTSSTRIP;
1298 =item B<LED>
1300 This creates an LED-trigger that can then be attached to system
1301 indicator lights, to blink or illuminate them when certain packets
1302 pass through the system.
1304     LED led-trigger-id "foo" led-delay 100 led-always-blink;
1306 =item B<LOG>
1308 Log all packets that match this rule in the kernel log. Be carefull
1309 with log flooding. Note that this is a "non-terminating target",
1310 i.e. rule traversal continues at the next rule.
1312     LOG log-level warning log-prefix "Look at this: ";
1313     LOG log-tcp-sequence log-tcp-options;
1314     LOG log-ip-options;
1316 =item B<MARK>
1318 Sets the netfilter mark field for the packet (a 32 bit integer between
1319 0 and 4294967295):
1321     MARK set-mark 42;
1322     MARK set-xmark 7/3;
1323     MARK and-mark 31;
1324     MARK or-mark 1;
1325     MARK xor-mark 12;
1327 =item B<MASQUERADE>
1329 Masquerades matching packets. Optionally followed by a port or
1330 port-range for iptables. Specify as "123", "123-456" or "123:456".
1331 The port range parameter specifies what local ports masqueraded
1332 connections should originate from.
1334     MASQUERADE;
1335     MASQUERADE to-ports 1234:2345;
1336     MASQUERADE to-ports 1234:2345 random;
1338 =item B<MIRROR>
1340 Experimental demonstration target which inverts the source and
1341 destination fields in the IP header.
1343     MIRROR;
1345 =item B<NETMAP>
1347 Map a whole network onto another network in the B<nat> table.
1349     NETMAP to 192.168.2.0/24;
1351 =item B<NOTRACK>
1353 Disable connection tracking for all packets matching that rule.
1355     proto tcp dport (135:139 445) NOTRACK;
1357 =item B<RATEEST>
1359     RATEEST rateest-name "foo" rateest-interval 60s rateest-ewmalog 100;
1361     proto tcp dport (135:139 445) NOTRACK;
1363 =item B<NFLOG>
1365 Log packets over netlink; this is the successor of I<ULOG>.
1367     NFLOG nflog-group 5 nflog-prefix "Look at this: ";
1368     NFLOG nflog-range 256;
1369     NFLOG nflog-threshold 10;
1371 =item B<NFQUEUE>
1373 Userspace queueing, requires nfnetlink_queue kernel support.
1375     proto tcp dport ftp NFQUEUE queue-num 20;
1377 =item B<QUEUE>
1379 Userspace queueing, the predecessor to B<NFQUEUE>.  All packets go to
1380 queue 0.
1382     proto tcp dport ftp QUEUE;
1384 =item B<REDIRECT to-ports [ports]>
1386 Transparent proxying: alter the destination IP of the packet to the
1387 machine itself.
1389     proto tcp dport http REDIRECT to-ports 3128;
1390     proto tcp dport http REDIRECT to-ports 3128 random;
1392 =item B<SAME>
1394 Similar to SNAT, but a client is mapped to the same source IP for all
1395 its connections.
1397     SAME to 1.2.3.4-1.2.3.7;
1398     SAME to 1.2.3.8-1.2.3.15 nodst;
1399     SAME to 1.2.3.16-1.2.3.31 random;
1401 =item B<SECMARK>
1403 This is used to set the security mark value associated with the packet
1404 for use by security subsystems such as SELinux.  It is only valid in
1405 the mangle table.
1407     SECMARK selctx "system_u:object_r:httpd_packet_t:s0";
1409 =item B<SET [add-set|del-set] [setname] [flag(s)]>
1411 Add the IP to the specified set. See L<http://ipset.netfilter.org/>
1413     proto icmp icmp-type echo-request SET add-set badguys src;
1414     SET add-set "foo" timeout 60 exist;
1416 =item B<SNAT to [ip-address|ip-range|ip-port-range]>
1418 Change the source address of the packet.
1420     SNAT to 1.2.3.4;
1421     SNAT to 1.2.3.4:20000-30000;
1422     SNAT to 1.2.3.4 random;
1424 =item B<SNPT>
1426 Provides stateless source IPv6-to-IPv6 Network Prefix Translation.
1428     SNPT src-pfx 2001:42::/16 dst-pfx 2002:42::/16;
1430 =item B<SYNPROXY>
1432 TCP 3-way handshake proxy: let the firewall handle the TCP 3-way handshake and
1433 only establish connection with the server socket once the client handshake has
1434 finished.
1436     SYNPROXY wscale 7 mss 1460 timestamp sack-perm
1438 =item B<TCPMSS>
1440 Alter the MSS value of TCP SYN packets.
1442     TCPMSS set-mss 1400;
1443     TCPMSS clamp-mss-to-pmtu;
1445 =item B<TCPOPTSTRIP>
1447 This target will strip TCP options off a TCP packet.
1449     TCPOPTSTRIP strip-options (option1 option2 ...);
1451 =item B<TOS set-tos [value]>
1453 Set the tcp package Type Of Service bit to this value.  This will be
1454 used by whatever traffic scheduler is willing to, mostly your own
1455 linux-machine, but maybe more. The original tos-bits are blanked and
1456 overwritten by this value.
1458     TOS set-tos Maximize-Throughput;
1459     TOS and-tos 7;
1460     TOS or-tos 1;
1461     TOS xor-tos 4;
1463 Type "iptables -j TOS -h" for details.
1465 =item B<TTL>
1467 Modify the TTL header field.
1469     TTL ttl-set 16;
1470     TTL ttl-dec 1; # decrease by 1
1471     TTL ttl-inc 4; # increase by 4
1473 =item B<ULOG>
1475 Log packets to a userspace program.
1477     ULOG ulog-nlgroup 5 ulog-prefix "Look at this: ";
1478     ULOG ulog-cprange 256;
1479     ULOG ulog-qthreshold 10;
1481 =back
1483 =head1 OTHER DOMAINS
1485 Since version 2.0, B<ferm> supports not only I<ip> and I<ip6>, but
1486 also I<arp> (ARP tables) and I<eb> (ethernet bridging tables).  The
1487 concepts are similar to I<iptables>.
1489 =head2 arptables keywords
1491 =over 8
1493 =item B<source-ip>, B<destination-ip>
1495 Matches the source or destination IPv4 address.  Same as B<saddr> and
1496 B<daddr> in the I<ip> domain.
1498 =item B<source-mac>, B<destination-mac>
1500 Matches the source or destination MAC address.
1502 =item B<interface>, B<outerface>
1504 Input and output interface.
1506 =item B<h-length>
1508 Hardware length of the packet.
1510     chain INPUT h-length 64 ACCEPT;
1512 =item B<opcode>
1514 Operation code, for details see the iptables(8).
1516     opcode 9 ACCEPT;
1518 =item B<h-type>
1520 Hardware type.
1522     h-type 1 ACCEPT;
1524 =item B<proto-type>
1526 Protocol type.
1528     proto-type 0x800 ACCEPT;
1530 =item B<Mangling>
1532 The keywords B<mangle-ip-s>, B<mangle-ip-d>, B<mangle-mac-s>,
1533 B<mangle-mac-d>, B<mangle-target> may be used for ARP mangling.  See
1534 iptables(8) for details.
1536 =back
1538 =head2 ebtables keywords
1540 =over 8
1542 =item B<proto>
1544 Matches the protocol which created the frame, e.g. I<IPv4> or B<PPP>.
1545 For a list, see F</etc/ethertypes>.
1547 =item B<interface>, B<outerface>
1549 Physical input and output interface.
1551 =item B<logical-in>, B<logical-out>
1553 The logical bridge interface.
1555 =item B<saddr>, B<daddr>
1557 Matches source or destination MAC address.
1559 =item B<Match modules>
1561 The following match modules are supported: 802.3, arp, ip, mark_m,
1562 pkttype, stp, vlan, log.
1564 =item B<Target extensions>
1566 The following target extensions are supported: arpreply, dnat, mark,
1567 redirect, snat.
1569 Please note that there is a conflict between I<--mark> from the
1570 I<mark_m> match module and I<-j mark>.  Since both would be
1571 implemented with the ferm keyword B<mark>, we decided to solve this by
1572 writing the target's name in uppercase, like in the other domains.
1573 The following example rewrites mark 1 to 2:
1575     mark 1 MARK 2;
1577 =back
1579 =head1 ADVANCED FEATURES
1581 =head2 Variables
1583 In complex firewall files, it is helpful to use variables, e.g. to
1584 give a network interface a meaningful name.
1586 To set variables, write:
1588     @def $DEV_INTERNET = eth0;
1589     @def $PORTS = (http ftp);
1590     @def $MORE_PORTS = ($PORTS 8080);
1592 In the real ferm code, variables are used like any other keyword
1593 parameter:
1595     chain INPUT interface $DEV_INTERNET proto tcp dport $MORE_PORTS ACCEPT;
1597 Note that variables can only be used in keyword parameters
1598 ("192.168.1.1", "http"); they cannot contain ferm keywords like
1599 "proto" or "interface".
1601 Variables are only valid in the current block:
1603     @def $DEV_INTERNET = eth1;
1604     chain INPUT {
1605         proto tcp {
1606             @def $DEV_INTERNET = ppp0;
1607             interface $DEV_INTERNET dport http ACCEPT;
1608         }
1609         interface $DEV_INTERNET DROP;
1610     }
1612 will be expanded to:
1614     chain INPUT {
1615         proto tcp {
1616             interface ppp0 dport http ACCEPT;
1617         }
1618         interface eth1 DROP;
1619     }
1621 The "def $DEV_INTERNET = ppp0" is only valid in the "proto tcp" block;
1622 the parent block still knows "set $DEV_INTERNET = eth1".
1624 Include files are special - variables declared in an included file are
1625 still available in the calling block. This is useful when you include
1626 a file which only declares variables.
1628 =head2 Automatic variables
1630 Some variables are set internally by ferm. Ferm scripts can use them
1631 just like any other variable.
1633 =over 8
1635 =item B<$FILENAME>
1637 The name of the configuration file relative to the directory ferm was
1638 started in.
1640 =item B<$FILEBNAME>
1642 The base name of the configuration file.
1644 =item B<$DIRNAME>
1646 The directory of the configuration file.
1648 =item B<$DOMAIN>
1650 The current domain.  One of I<ip>, I<ip6>, I<arp>, I<eb>.
1652 =item B<$TABLE>
1654 The current netfilter table.
1656 =item B<$CHAIN>
1658 The current netfilter chain.
1660 =item B<$LINE>
1662 The line of the current script.  It can be used like this:
1664     @def &log($msg) = {
1665              LOG log-prefix "rule=$msg:$LINE ";
1666     }
1667     .
1668     .
1669     .
1670     &log("log message");
1672 =back
1674 =head2 Functions
1676 Functions are similar to variables, except that they may have
1677 parameters, and they provide ferm commands, not values.
1679     @def &FOO() = proto (tcp udp) dport domain;
1680     &FOO() ACCEPT;
1682     @def &TCP_TUNNEL($port, $dest) = {
1683         table filter chain FORWARD interface ppp0 proto tcp dport $port daddr $dest outerface eth0 ACCEPT;
1684         table nat chain PREROUTING interface ppp0 proto tcp dport $port daddr 1.2.3.4 DNAT to $dest;
1685     }
1687     &TCP_TUNNEL(http, 192.168.1.33);
1688     &TCP_TUNNEL(ftp, 192.168.1.30);
1689     &TCP_TUNNEL((ssh smtp), 192.168.1.2);
1691 A function call which contains a block (like '{...}') must be the last
1692 command in a ferm rule, i.e. it must be followed by ';'. The '&FOO()'
1693 example does not contain a block, thus you may write 'ACCEPT' after
1694 the call. To circumvent this, you can reorder the keywords:
1696     @def &IPSEC() = { proto (esp ah); proto udp dport 500; }
1697     chain INPUT ACCEPT &IPSEC();
1699 =head2 Backticks
1701 With backticks, you may use the output of an external command:
1703     @def $DNSSERVERS = `grep nameserver /etc/resolv.conf | awk '{print $2}'`;
1704     chain INPUT proto tcp saddr $DNSSERVERS ACCEPT;
1706 The command is executed with the shell (F</bin/sh>), just like
1707 backticks in perl.  ferm does not do any variable expansion here.
1709 The output is then tokenized, and saved as a ferm list (array). Lines
1710 beginning with '#' are ignored; the other lines may contain any number
1711 of values, separated by whitespace.
1713 =head2 Includes
1715 The B<@include> keyword allows you to include external files:
1717     @include 'vars.ferm';
1719 The file name is relative to the calling file, e.g. when including
1720 from F</etc/ferm/ferm.conf>, the above statement includes
1721 F</etc/ferm/vars.ferm>. Variables and functions declared in an
1722 included file are still available in the calling file.
1724 B<include> works within a block:
1726     chain INPUT {
1727         @include 'input.ferm';
1728     }
1730 If you specify a directory (with a trailing '/'), all files in this
1731 directory are included, sorted alphabetically:
1733     @include 'ferm.d/';
1735 The function @glob can be used to expand wild cards:
1737     @include @glob('*.include');
1739 With a trailing pipe symbol, B<ferm> executes a shell command and
1740 parses its output:
1742     @include "/root/generate_ferm_rules.sh $HOSTNAME|"
1744 B<ferm> aborts, if return code is not 0.
1746 =head2 Conditionals
1748 The keyword B<@if> introduces a conditional expression:
1750     @if $condition DROP;
1752 A value is evaluated true just like in Perl: zero, empty list, empty
1753 string are false, everything else is true.  Examples for true values:
1755     (a b); 1; 'foo'; (0 0)
1757 Examples for false values:
1759     (); 0; '0'; ''
1761 There is also B<@else>:
1763     @if $condition DROP; @else REJECT;
1765 Note the semicolon before the B<@else>.
1767 It is possible to use curly braces after either B<@if> or B<@else>:
1769     @if $condition {
1770         MARK set-mark 2;
1771         RETURN;
1772     } @else {
1773         MARK set-mark 3;
1774     }
1776 Since the closing curly brace also finishes the command, there is no
1777 need for semicolon.
1779 There is no B<@elsif>, use B<@else @if> instead.
1781 Example:
1783     @def $have_ipv6 = `test -f /proc/net/ip6_tables_names && echo 1 || echo`;
1784     @if $have_ipv6 {
1785         domain ip6 {
1786             # ....
1787         }
1788     }
1790 =head2 Hooks
1792 To run custom commands, you may install hooks:
1794     @hook pre "echo 0 >/proc/sys/net/ipv4/conf/eth0/forwarding";
1795     @hook post "echo 1 >/proc/sys/net/ipv4/conf/eth0/forwarding";
1796     @hook flush "echo 0 >/proc/sys/net/ipv4/conf/eth0/forwarding";
1798 The specified command is executed using the shell.  "pre" means run
1799 the command before applying the firewall rules, and "post" means run
1800 the command afterwards.  "flush" hooks are run after ferm has flushed
1801 the firewall rules (option --flush).  You may install any number of
1802 hooks.
1804 =head1 BUILT-IN FUNCTIONS
1806 There are several built-in functions which you might find useful.
1808 =head2 @defined($name), @defined(&name)
1810 Tests if the variable or function is defined.
1812     @def $a = 'foo';
1813     @if @defined($a) good;
1814     @if @not(@defined($a)) bad;
1815     @if @defined(&funcname) good;
1817 =head2 @eq(a,b)
1819 Tests two values for equality.  Example:
1821     @if @eq($DOMAIN, ip6) DROP;
1823 =head2 @ne(a,b)
1825 Similar to @eq, this tests for non-equality.
1827 =head2 @not(x)
1829 Negates a boolean value.
1831 =head2 @resolve((hostname1 hostname2 ...), [type])
1833 Usually, host names are resolved by iptables.  To let ferm resolve
1834 host names, use the function @resolve:
1836     saddr @resolve(my.host.foo) proto tcp dport ssh ACCEPT;
1837     saddr @resolve((another.host.foo third.host.foo)) proto tcp dport openvpn ACCEPT;
1838     daddr @resolve(ipv6.google.com, AAAA) proto tcp dport http ACCEPT;
1840 Note the double parentheses in the second line: the inner pair for
1841 creating a ferm list, and the outer pair as function parameter
1842 delimiters.
1844 The second parameter is optional, and specifies the DNS record type.
1845 The default is "A".
1847 Be careful with resolved host names in firewall configuration.  DNS
1848 requests may block the firewall configuration for a long time, leaving
1849 the machine vulnerable, or they may fail.
1851 =head2 @cat(a, b, ...)
1853 Concatenate all parameters into one string.
1855 =head2 @substr(expression, offset, length)
1857 Extracts a substring out of expression and returns it.  First
1858 character is at offset 0. If OFFSET is negative, starts that far from
1859 the end of the string.  
1861 =head2 @length(expression)
1863 Returns the length in characters of the value of EXPR.
1865 =head2 @basename(path)
1867 Return the base name of the file for a given path
1868 (File::Spec::splitpath).
1870 =head2 @dirname(path)
1872 Return the name of the last directory for a given path, assuming the
1873 last component is a file name (File::Spec::splitpath).
1875 =head2 @glob(path)
1877 Expand shell wildcards in the given paths (assumed to be relative to
1878 the current script).  Returns a list of matching files.  This function
1879 is useful as parameter of @include.
1881 =head2 @ipfilter(list)
1883 Filters out the IP addresses that obviously do not match the current
1884 domain.  That is useful to create common variables and rules for IPv4
1885 and IPv6:
1887     @def $TRUSTED_HOSTS = (192.168.0.40 2001:abcd:ef::40);
1889     domain (ip ip6) chain INPUT {
1890         saddr @ipfilter($TRUSTED_HOSTS) proto tcp dport ssh ACCEPT;
1891     }
1893 =head1 RECIPES
1895 The F<./examples/> directory contains numerous ferm configuration
1896 which can be used to begin a new firewall. This sections contains more
1897 samples, recipes and tricks.
1899 =head2 Easy port forwarding
1901 Ferm function make routine tasks quick and easy:
1903     @def &FORWARD_TCP($proto, $port, $dest) = {
1904         table filter chain FORWARD interface $DEV_WORLD outerface $DEV_DMZ daddr $dest proto $proto dport $port ACCEPT;
1905         table nat chain PREROUTING interface $DEV_WORLD daddr $HOST_STATIC proto $proto dport $port DNAT to $dest;
1906     }
1908     &FORWARD_TCP(tcp, http, 192.168.1.2);
1909     &FORWARD_TCP(tcp, smtp, 192.168.1.3);
1910     &FORWARD_TCP((tcp udp), domain, 192.168.1.4);
1912 =head2 Remote B<ferm>
1914 If the target machine is not able to run B<ferm> for some reason
1915 (maybe an embedded device without Perl), you can edit the B<ferm>
1916 configuration file on another computer and let B<ferm> generate a
1917 shell script there.
1919 Example for OpenWRT:
1921     ferm --remote --shell mywrt/ferm.conf >mywrt/firewall.user
1922     chmod +x mywrt/firewall.user
1923     scp mywrt/firewall.user mywrt.local.net:/etc/
1924     ssh mywrt.local.net /etc/firewall.user
1926 =head1 OPTIONS
1928 =over 12
1930 =item B<--noexec>
1932 Do not execute the iptables(8) commands, but skip instead. This way
1933 you can parse your data, use B<--lines> to view the output.
1935 =item B<--flush>
1937 Clears the firewall rules and sets the policy of all chains to ACCEPT.
1938 B<ferm> needs a configuration file for that to determine which domains
1939 and tables are affected.
1941 =item B<--lines>
1943 Show the firewall lines that were generated from the rules. They
1944 will be shown just before they are executed, so if you get error
1945 messages from iptables(8) etc., you can see which rule caused
1946 the error.
1948 =item B<--interactive>
1950 Apply the firewall rules and ask the user for confirmation.  Reverts
1951 to the previous ruleset if there is no valid user response within 30
1952 seconds (see B<--timeout>).  This is useful for remote firewall
1953 administration: you can test the rules without fearing to lock
1954 yourself out.
1956 =item B<--timeout S>
1958 If B<--interactive> is used, then roll back if there is no valid user
1959 response after this number of seconds.  The default is 30.
1961 =item B<--help>
1963 Show a brief list of available commandline options.
1965 =item B<--version>
1967 Shows the version number of the program.
1969 =item B<--fast>
1971 Enable fast mode: ferm generates an iptables-save(8) file, and
1972 installs it with iptables-restore(8). This is much faster, because
1973 ferm calls iptables(8) once for every rule by default.
1975 Fast mode is enabled by default since B<ferm> 2.0, deprecating this
1976 option.
1978 =item B<--slow>
1980 Disable fast mode, i.e. run iptables(8) for every rule, and don't use
1981 iptables-restore(8).
1983 =item B<--shell>
1985 Generate a shell script which calls iptables-restore(8) and prints it.
1986 Implies --fast --lines.
1988 =item B<--remote>
1990 Generate rules for a remote machine.  Implies B<--noexec> and
1991 B<--lines>.  Can be combined with B<--shell>.
1993 =item B<--domain {ip|ip6}>
1995 Handle only the specified domain. B<ferm> output may be empty if the
1996 domain is not configured in the input file.
1998 =item B<--def '$name=value'>
2000 Override a variable defined in the configuration file.
2002 =back
2005 =head1 SEE ALSO
2007 iptables(8)
2010 =head1 REQUIREMENTS
2012 =head2 Operating system
2014 Linux 2.4 or newer, with netfilter support and all netfilter modules
2015 used by your firewall script
2017 =head2 Software
2019 iptables and perl 5.6
2021 =head1 BUGS
2023 Bugs? What bugs?
2025 If you find a bug, please report it on GitHub:
2026 L<https://github.com/MaxKellermann/ferm/issues>
2028 =head1 COPYRIGHT
2030 Copyright 2001-2017 Max Kellermann <max.kellermann@gmail.com>,
2031 Auke Kok <sofar@foo-projects.org> and various other contributors.
2033 This program is free software; you can redistribute it and/or modify
2034 it under the terms of the GNU General Public License as published by
2035 the Free Software Foundation; either version 2 of the License, or (at
2036 your option) any later version.
2038 This program is distributed in the hope that it will be useful, but
2039 WITHOUT ANY WARRANTY; without even the implied warranty of
2040 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2041 General Public License for more details.
2043 You should have received a copy of the GNU General Public License
2044 along with this program; if not, write to the Free Software
2045 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
2046 MA 02110-1301 USA.
2048 =head1 AUTHOR
2050 Max Kellermann <max.kellermann@gmail.com>, Auke Kok
2051 <sofar@foo-projects.org>
2053 =cut