4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2010 Max Kellermann, Auke Kok
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 eval { require strict
; import strict
; };
36 # we need no vars.pm if there is not even strict.pm
38 *vars
::import
= sub {};
43 eval { require Getopt
::Long
; import Getopt
::Long
; };
47 use vars
qw($has_strict $has_getopt);
49 use vars qw($VERSION);
54 ## interface variables
55 # %option = command line and other options
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
113 # u32=m an array which renders into multiple iptables options in one
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # add a module definition
139 my $domain_family = shift;
140 my $params_default = shift;
142 die if exists $defs->{$domain_family}{$name};
143 my $def = $defs->{$domain_family}{$name} = {};
148 if ($keyword =~ s,:=(\S+)$,,) {
149 $k = $def->{keywords}{$1} || die;
150 $k->{ferm_name} ||= $keyword;
152 my $params = $params_default;
153 $params = $1 if $keyword =~ s,\*(\d+)$,,;
154 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
155 if ($keyword =~ s,&(\S+)$,,) {
156 $params = eval "\\&$1";
161 $k->{params} = $params if $params;
163 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
164 $k->{negation} = 1 if $keyword =~ s,!$,,;
165 $k->{name} = $keyword;
168 $def->{keywords}{$keyword} = $k;
174 # add a protocol module definition
175 sub add_proto_def_x(@) {
176 my $domain_family = shift;
177 add_def_x(\%proto_defs, $domain_family, 1, @_);
180 # add a match module definition
181 sub add_match_def_x(@) {
182 my $domain_family = shift;
183 add_def_x(\%match_defs, $domain_family, 1, @_);
186 # add a target module definition
187 sub add_target_def_x(@) {
188 my $domain_family = shift;
189 add_def_x(\%target_defs, $domain_family, 's', @_);
194 add_def_x($defs, 'ip', @_);
197 # add a protocol module definition
198 sub add_proto_def(@) {
199 add_def(\%proto_defs, 1, @_);
202 # add a match module definition
203 sub add_match_def(@) {
204 add_def(\%match_defs, 1, @_);
207 # add a target module definition
208 sub add_target_def(@) {
209 add_def(\%target_defs, 's', @_);
212 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
213 add_proto_def
'mh', qw(mh-type!);
214 add_proto_def
'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
215 add_proto_def
'sctp', qw(chunk-types!=sc);
216 add_proto_def
'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
217 add_proto_def
'udp', qw();
220 # --source, --destination
221 qw(source! saddr:=source destination! daddr:=destination),
223 qw(in-interface! interface:=in-interface if:=in-interface),
225 qw(out-interface! outerface:=out-interface of:=out-interface),
228 add_match_def
'account', qw(aaddr=s aname=s ashort*0);
229 add_match_def
'addrtype', qw(!src-type !dst-type),
230 qw(limit-iface-in*0 limit-iface-out*0);
231 add_match_def
'ah', qw(ahspi! ahlen! ahres*0);
232 add_match_def
'comment', qw(comment=s);
233 add_match_def
'condition', qw(condition!);
234 add_match_def
'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
235 add_match_def
'connlimit', qw(!connlimit-above connlimit-mask);
236 add_match_def
'connmark', qw(!mark);
237 add_match_def
'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst!),
238 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
239 add_match_def
'dscp', qw(dscp dscp-class);
240 add_match_def
'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
241 add_match_def
'esp', qw(espspi!);
242 add_match_def
'eui64';
243 add_match_def
'fuzzy', qw(lower-limit=s upper-limit=s);
244 add_match_def
'hbh', qw(hbh-len! hbh-opts=c);
245 add_match_def
'helper', qw(helper);
246 add_match_def
'hl', qw(hl-eq! hl-lt=s hl-gt=s);
247 add_match_def
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
248 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
249 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
250 add_match_def
'iprange', qw(!src-range !dst-range);
251 add_match_def
'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
252 add_match_def
'ipv6header', qw(header!=c soft*0);
253 add_match_def
'length', qw(length!);
254 add_match_def
'limit', qw(limit=s limit-burst=s);
255 add_match_def
'mac', qw(mac-source!);
256 add_match_def
'mark', qw(!mark);
257 add_match_def
'multiport', qw(source-ports!&multiport_params),
258 qw(destination-ports!&multiport_params ports!&multiport_params);
259 add_match_def
'nth', qw(every counter start packet);
260 add_match_def
'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
261 qw(cmd-owner !socket-exists=0);
262 add_match_def
'physdev', qw(physdev-in! physdev-out!),
263 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
264 add_match_def
'pkttype', qw(pkt-type!),
265 add_match_def
'policy',
266 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
267 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
268 qw(psd-lo-ports-weight psd-hi-ports-weight);
269 add_match_def
'quota', qw(quota=s);
270 add_match_def
'random', qw(average);
271 add_match_def
'realm', qw(realm!);
272 add_match_def
'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
273 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
274 add_match_def
'set', qw(!set=sc);
275 add_match_def
'state', qw(!state=c);
276 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
277 add_match_def
'string', qw(algo=s from=s to=s string hex-string);
278 add_match_def
'tcpmss', qw(!mss);
279 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
280 qw(!monthday=c !weekdays=c utc*0 localtz*0);
281 add_match_def
'tos', qw(!tos);
282 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
283 add_match_def
'u32', qw(!u32=m);
285 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
286 add_target_def
'CLASSIFY', qw(set-class);
287 add_target_def
'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
288 add_target_def
'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
289 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
290 add_target_def
'DNAT', qw(to-destination=m to:=to-destination random*0);
291 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
292 add_target_def
'ECN', qw(ecn-tcp-remove*0);
293 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
294 add_target_def
'IPV4OPTSSTRIP';
295 add_target_def
'LOG', qw(log-level log-prefix),
296 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
297 add_target_def
'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
298 add_target_def
'MASQUERADE', qw(to-ports random*0);
299 add_target_def
'MIRROR';
300 add_target_def
'NETMAP', qw(to);
301 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
302 add_target_def
'NFQUEUE', qw(queue-num);
303 add_target_def
'NOTRACK';
304 add_target_def
'REDIRECT', qw(to-ports random*0);
305 add_target_def
'REJECT', qw(reject-with);
306 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
307 add_target_def
'SAME', qw(to nodst*0 random*0);
308 add_target_def
'SECMARK', qw(selctx);
309 add_target_def
'SET', qw(add-set=sc del-set=sc);
310 add_target_def
'SNAT', qw(to-source=m to:=to-source random*0);
311 add_target_def
'TARPIT';
312 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
313 add_target_def
'TOS', qw(set-tos and-tos or-tos xor-tos);
314 add_target_def
'TRACE';
315 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
316 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
318 add_match_def_x
'arp', '',
320 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
322 qw(source-mac! destination-mac!),
324 qw(in-interface! interface:=in-interface if:=in-interface),
326 qw(out-interface! outerface:=out-interface of:=out-interface),
328 qw(h-length=s opcode=s h-type=s proto-type=s),
329 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
331 add_proto_def_x
'eb', 'IPv4',
332 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!);
334 add_proto_def_x
'eb', 'ARP',
335 qw(!arp-gratuitous*0),
336 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
337 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
339 add_proto_def_x
'eb', 'RARP',
340 qw(!arp-gratuitous*0),
341 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
342 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
344 add_proto_def_x
'eb', '802_1Q',
345 qw(vlan-id! vlan-prio! vlan-encap!),
347 add_match_def_x
'eb', '',
349 qw(in-interface! interface:=in-interface if:=in-interface),
351 qw(out-interface! outerface:=out-interface of:=out-interface),
353 qw(logical-in! logical-out!),
354 # --source, --destination
355 qw(source! saddr:=source destination! daddr:=destination),
357 qw(802_3-sap! 802_3-type!),
363 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
364 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
365 qw(stp-hello-time! stp-forward-delay!),
367 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
369 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
370 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
371 add_target_def_x
'eb', 'MARK', qw(set-mark mark-target);
372 add_target_def_x
'eb', 'redirect', qw(redirect-target);
373 add_target_def_x
'eb', 'snat', qw(to-source snat-target snat-arp*0);
375 # import-ferm uses the above tables
376 return 1 if $0 =~ /import-ferm$/;
378 # parameter parser for ipt_multiport
379 sub multiport_params
{
382 # multiport only allows 15 ports at a time. For this
383 # reason, we do a little magic here: split the ports
384 # into portions of 15, and handle these portions as
387 my $proto = $rule->{protocol
};
388 error
('To use multiport, you have to specify "proto tcp" or "proto udp" first')
389 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array
($proto);
391 my $value = getvalues
(undef, allow_negation
=> 1,
392 allow_array_negation
=> 1);
393 if (ref $value and ref $value eq 'ARRAY') {
398 push @params, join(',', splice(@value, 0, 15));
405 return join_value
(',', $value);
409 # initialize stack: command line definitions
412 # Get command line stuff
414 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
415 $opt_timeout, $opt_help,
416 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
419 Getopt
::Long
::Configure
('bundling', 'auto_help', 'no_ignore_case',
423 my ($opt, $value) = @_;
424 die 'Invalid --def specification'
425 unless $value =~ /^\$?(\w+)=(.*)$/s;
426 my ($name, $unparsed_value) = ($1, $2);
427 my $tokens = tokenize_string
($unparsed_value);
428 my $value = getvalues
(sub { shift @
$tokens; });
429 die 'Extra tokens after --def'
431 $stack[0]{vars
}{$name} = $value;
434 local $SIG{__WARN__
} = sub { die $_[0]; };
435 GetOptions
('noexec|n' => \
$opt_noexec,
436 'flush|F' => \
$opt_flush,
437 'noflush' => \
$opt_noflush,
438 'lines|l' => \
$opt_lines,
439 'interactive|i' => \
$opt_interactive,
440 'timeout|t=s' => \
$opt_timeout,
441 'help|h' => \
$opt_help,
442 'version|V' => \
$opt_version,
444 remote
=> \
$opt_test,
447 shell
=> \
$opt_shell,
448 'domain=s' => \
$opt_domain,
449 'def=s' => \
&opt_def
,
452 if (defined $opt_help) {
454 Pod
::Usage
::pod2usage
(-exitstatus
=> 0);
457 if (defined $opt_version) {
462 $option{noexec
} = $opt_noexec || $opt_test;
463 $option{flush
} = $opt_flush;
464 $option{noflush
} = $opt_noflush;
465 $option{lines
} = $opt_lines || $opt_test || $opt_shell;
466 $option{interactive
} = $opt_interactive && !$opt_noexec;
467 $option{timeout
} = defined $opt_timeout ?
$opt_timeout : "30";
468 $option{test
} = $opt_test;
469 $option{fast
} = !$opt_slow;
470 $option{shell
} = $opt_shell;
472 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
473 if $option{interactive
} and not -t STDIN
;
474 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
475 if $option{interactive
} and not -t STDERR
;
476 die("ferm timeout has no sense without interactive mode")
477 if not $opt_interactive and defined $opt_timeout;
478 die("invalid timeout. must be an integer")
479 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
481 $option{domain
} = $opt_domain if defined $opt_domain;
483 # tiny getopt emulation for microperl
486 if ($_ eq '--noexec' or $_ eq '-n') {
488 } elsif ($_ eq '--lines' or $_ eq '-l') {
490 } elsif ($_ eq '--fast') {
492 } elsif ($_ eq '--test') {
496 } elsif ($_ eq '--shell') {
497 $option{$_} = 1 foreach qw(shell fast lines);
499 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
506 push @ARGV, $filename;
509 unless (@ARGV == 1) {
511 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
515 open LINES
, ">&STDOUT" if $option{lines
};
516 open STDOUT
, ">&STDERR" if $option{shell
};
518 # microperl can't redirect file handles
521 if ($option{fast
} and not $option{noexec
}) {
522 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
528 open_script
($ARGV[0]);
530 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $ARGV[0] );
531 $stack[0]{auto
}{FILENAME
} = $ARGV[0];
532 $stack[0]{auto
}{FILEBNAME
} = $file;
533 $stack[0]{auto
}{DIRNAME
} = $dirs;
537 # parse all input recursively
539 die unless @stack == 2;
541 # enable/disable hooks depending on --flush
543 if ($option{flush
}) {
550 # execute all generated rules
553 foreach my $cmd (@pre_hooks) {
554 print LINES
"$cmd\n" if $option{lines
};
555 system($cmd) unless $option{noexec
};
558 while (my ($domain, $domain_info) = each %domains) {
559 next unless $domain_info->{enabled
};
560 my $s = $option{fast
} &&
561 defined $domain_info->{tools
}{'tables-restore'}
562 ? execute_fast
($domain_info) : execute_slow
($domain_info);
563 $status = $s if defined $s;
566 foreach my $cmd (@post_hooks, @flush_hooks) {
567 print LINES
"$cmd\n" if $option{lines
};
568 system($cmd) unless $option{noexec
};
571 if (defined $status) {
576 # ask user, and rollback if there is no confirmation
578 if ($option{interactive
}) {
579 if ($option{shell
}) {
580 print LINES
"echo 'ferm has applied the new firewall rules.'\n";
581 print LINES
"echo 'Please press Ctrl-C to confirm.'\n";
582 print LINES
"sleep $option{timeout}\n";
583 while (my ($domain, $domain_info) = each %domains) {
584 my $restore = $domain_info->{tools
}{'tables-restore'};
585 next unless defined $restore;
586 print LINES
"$restore <\$${domain}_tmp\n";
590 confirm_rules
() or rollback
() unless $option{noexec
};
595 # end of program execution!
601 print "ferm $VERSION\n";
602 print "Copyright (C) 2001-2010 Max Kellermann, Auke Kok\n";
603 print "This program is free software released under GPLv2.\n";
604 print "See the included COPYING file for license details.\n";
609 # returns a nice formatted error message, showing the
610 # location of the error.
614 my @words = map { @
$_ } @
{$script->{past_tokens
}};
616 for my $w ( 0 .. $#words ) {
617 if ($words[$w] eq "\x29")
618 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
619 if ($words[$w] eq "\x28")
620 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
621 if ($words[$w] eq "\x7d")
622 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
623 if ($words[$w] eq "\x7b")
624 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
625 if ( $l > $#lines ) { $lines[$l] = "" };
626 $lines[$l] .= $words[$w] . " ";
627 if ($words[$w] eq "\x28")
628 { $l++ ; $lines[$l] = " " x
$tabs ;};
629 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
630 { $l++ ; $lines[$l] = " " x
$tabs ;};
631 if ($words[$w] eq "\x7b")
632 { $l++ ; $lines[$l] = " " x
$tabs ;};
633 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
634 { $l++ ; $lines[$l] = " " x
$tabs ;};
635 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
636 { $l++ ; $lines[$l] = " " x
$tabs ;}
637 if ($words[$w-1] eq "option")
638 { $l++ ; $lines[$l] = " " x
$tabs ;}
640 my $start = $#lines - 4;
641 if ($start < 0) { $start = 0 } ;
642 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
643 for $l ( $start .. $#lines)
644 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
645 print STDERR
"<--\n";
649 # print a warning message about code from an input file
651 print STDERR
"Warning in $script->{filename} line $script->{line}: "
657 return $name if $option{test
};
658 for my $path ('/sbin', split ':', $ENV{PATH
}) {
659 my $ret = "$path/$name";
660 return $ret if -x
$ret;
662 die "$name not found in PATH\n";
665 sub initialize_domain
{
667 my $domain_info = $domains{$domain} ||= {};
669 return if exists $domain_info->{initialized
};
671 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
673 my @tools = qw(tables);
674 push @tools, qw(tables-save tables-restore)
675 if $domain =~ /^ip6?$/;
677 # determine the location of this domain's tools
678 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
679 $domain_info->{tools
} = \
%tools;
681 # make tables-save tell us about the state of this domain
682 # (which tables and chains do exist?), also remember the old
683 # save data which may be used later by the rollback function
685 if (!$option{test
} &&
686 exists $tools{'tables-save'} &&
687 open(SAVE
, "$tools{'tables-save'}|")) {
696 $table_info = $domain_info->{tables
}{$table} ||= {};
697 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
699 $table_info->{chains
}{$1}{builtin
} = 1;
700 $table_info->{has_builtin
} = 1;
705 $domain_info->{previous
} = $save;
708 if ($option{shell
} && $option{interactive
} &&
709 exists $tools{'tables-save'}) {
710 print LINES
"${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
711 print LINES
"$tools{'tables-save'} >\$${domain}_tmp\n";
714 $domain_info->{initialized
} = 1;
717 sub filter_domains
($) {
721 foreach my $domain (to_array
($domains)) {
722 next if exists $option{domain
}
723 and $domain ne $option{domain
};
726 initialize_domain
($domain);
730 push @result, $domain;
733 return @result == 1 ?
@result[0] : \
@result;
736 # split the input string into words and delete comments
737 sub tokenize_string
($) {
742 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
743 last if $word eq '#';
750 # read some more tokens from the input file into a buffer
751 sub prepare_tokens
() {
752 my $tokens = $script->{tokens
};
753 while (@
$tokens == 0) {
754 my $handle = $script->{handle
};
755 my $line = <$handle>;
756 return unless defined $line;
760 # the next parser stage eats this
761 push @
$tokens, @
{tokenize_string
($line)};
767 # open a ferm sub script
769 my $filename = shift;
771 for (my $s = $script; defined $s; $s = $s->{parent
}) {
772 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
773 if $s->{filename
} eq $filename;
777 open FILE
, "$filename" or die("Failed to open $filename: $!\n");
780 $script = { filename
=> $filename,
791 # collect script filenames which are being included
792 sub collect_filenames
(@
) {
795 # determine the current script's parent directory for relative
797 die unless defined $script;
798 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
801 foreach my $pathname (@_) {
802 # non-absolute file names are relative to the parent script's
804 $pathname = $parent_dir . $pathname
805 unless $pathname =~ m
,^/|\
|$,;
807 if ($pathname =~ m
,/$,) {
808 # include all regular files in a directory
810 error
("'$pathname' is not a directory")
814 opendir DIR
, $pathname
815 or error
("Failed to open directory '$pathname': $!");
816 my @names = readdir DIR
;
819 # sort those names for a well-defined order
820 foreach my $name (sort { $a cmp $b } @names) {
821 # ignore dpkg's backup files
822 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
823 # don't include hidden and backup files
824 next if $name =~ /^\.|~$/;
826 my $filename = $pathname . $name;
830 } elsif ($pathname =~ m
,\
|$,) {
831 # run a program and use its output
832 push @ret, $pathname;
833 } elsif ($pathname =~ m
,^\
|,) {
834 error
('This kind of pipe is not allowed');
836 # include a regular file
838 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
840 error
("'$pathname' is not a file")
843 push @ret, $pathname;
850 # peek a token from the queue, but don't remove it
852 return unless prepare_tokens
();
853 return $script->{tokens
}[0];
856 # get a token from the queue
858 return unless prepare_tokens
();
859 my $token = shift @
{$script->{tokens
}};
861 # update $script->{past_tokens}
862 my $past_tokens = $script->{past_tokens
};
864 if (@
$past_tokens > 0) {
865 my $prev_token = $past_tokens->[-1][-1];
866 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
867 if $prev_token eq ';';
868 if ($prev_token eq '}') {
870 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
872 if @
$past_tokens > 0;
876 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
877 push @
{$past_tokens->[-1]}, $token;
883 sub expect_token
($;$) {
886 my $token = next_token
();
887 error
($msg || "'$expect' expected")
888 unless defined $token and $token eq $expect;
891 # require that another token exists, and that it's not a "special"
892 # token, e.g. ";" and "{"
893 sub require_next_token
{
894 my $code = shift || \
&next_token
;
896 my $token = &$code(@_);
898 error
('unexpected end of file')
899 unless defined $token;
901 error
("'$token' not allowed here")
902 if $token =~ /^[;{}]$/;
907 # return the value of a variable
908 sub variable_value
($) {
911 if ($name eq "LINE") {
912 return $script->{line
};
916 return $_->{vars
}{$name}
917 if exists $_->{vars
}{$name};
920 return $stack[0]{auto
}{$name}
921 if exists $stack[0]{auto
}{$name};
926 # determine the value of a variable, die if the value is an array
927 sub string_variable_value
($) {
929 my $value = variable_value
($name);
931 error
("variable '$name' must be a string, but it is an array")
937 # similar to the built-in "join" function, but also handle negated
938 # values in a special way
940 my ($expr, $value) = @_;
942 unless (ref $value) {
944 } elsif (ref $value eq 'ARRAY') {
945 return join($expr, @
$value);
946 } elsif (ref $value eq 'negated') {
947 # bless'negated' is a special marker for negated values
948 $value = join_value
($expr, $value->[0]);
949 return bless [ $value ], 'negated';
955 sub negate_value
($$;$) {
956 my ($value, $class, $allow_array) = @_;
959 error
('double negation is not allowed')
960 if ref $value eq 'negated' or ref $value eq 'pre_negated';
962 error
('it is not possible to negate an array')
963 if ref $value eq 'ARRAY' and not $allow_array;
966 return bless [ $value ], $class || 'negated';
970 return $_[0] ?
1 : 0;
974 my ($resolver, $names, $type) = @_;
977 foreach my $hostname (@
$names) {
978 my $query = $resolver->search($hostname, $type);
979 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
982 foreach my $rr ($query->answer) {
983 next unless $rr->type eq $type;
986 push @result, $rr->nsdname;
987 } elsif ($type eq 'MX') {
988 push @result, $rr->exchange;
990 push @result, $rr->address;
995 # NS/MX records return host names; resolve these again in the
996 # second pass (IPv4 only currently)
997 @result = resolve
($resolver, \
@result, 'A')
998 if $type eq 'NS' or $type eq 'MX';
1003 # returns the next parameter, which may either be a scalar or an array
1008 my $token = require_next_token
($code);
1010 if ($token eq '(') {
1011 # read an array until ")"
1015 $token = getvalues
($code,
1016 parenthesis_allowed
=> 1,
1017 comma_allowed
=> 1);
1019 unless (ref $token) {
1020 last if $token eq ')';
1022 if ($token eq ',') {
1023 error
('Comma is not allowed within arrays, please use only a space');
1027 push @wordlist, $token;
1028 } elsif (ref $token eq 'ARRAY') {
1029 push @wordlist, @
$token;
1031 error
('unknown toke type');
1035 error
('empty array not allowed here')
1036 unless @wordlist or not $options{non_empty
};
1038 return @wordlist == 1
1041 } elsif ($token =~ /^\`(.*)\`$/s) {
1042 # execute a shell command, insert output
1044 my $output = `$command`;
1047 error
("failed to execute: $!");
1048 } elsif ($?
& 0x7f) {
1049 error
("child died with signal " . ($?
& 0x7f));
1051 error
("child exited with status " . ($?
>> 8));
1056 $output =~ s/#.*//mg;
1059 my @tokens = grep { length } split /\s+/s, $output;
1063 my $value = getvalues
(sub { shift @tokens });
1064 push @values, to_array
($value);
1071 } elsif ($token =~ /^\'(.*)\'$/s) {
1072 # single quotes: a string
1074 } elsif ($token =~ /^\"(.*)\"$/s) {
1075 # double quotes: a string with escapes
1077 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
1079 } elsif ($token eq '!') {
1080 error
('negation is not allowed here')
1081 unless $options{allow_negation
};
1083 $token = getvalues
($code);
1085 return negate_value
($token, undef, $options{allow_array_negation
});
1086 } elsif ($token eq ',') {
1088 if $options{comma_allowed
};
1090 error
('comma is not allowed here');
1091 } elsif ($token eq '=') {
1092 error
('equals operator ("=") is not allowed here');
1093 } elsif ($token eq '$') {
1094 my $name = require_next_token
($code);
1095 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1096 unless $name =~ /^\w+$/;
1098 my $value = variable_value
($name);
1100 error
("no such variable: \$$name")
1101 unless defined $value;
1104 } elsif ($token eq '&') {
1105 error
("function calls are not allowed as keyword parameter");
1106 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1107 error
('Syntax error');
1108 } elsif ($token =~ /^@/) {
1109 if ($token eq '@resolve') {
1110 my @params = get_function_params
();
1111 error
('Usage: @resolve((hostname ...), [type])')
1112 unless @params == 1 or @params == 2;
1113 eval { require Net
::DNS
; };
1114 error
('For the @resolve() function, you need the Perl library Net::DNS')
1116 my $type = $params[1] || 'A';
1117 my $resolver = new Net
::DNS
::Resolver
;
1118 my @params = to_array
($params[0]);
1119 return [resolve
($resolver, @params, $type)];
1120 } elsif ($token eq '@eq') {
1121 my @params = get_function_params
();
1122 error
('Usage: @eq(a, b)') unless @params == 2;
1123 return format_bool
($params[0] eq $params[1]);
1124 } elsif ($token eq '@ne') {
1125 my @params = get_function_params
();
1126 error
('Usage: @ne(a, b)') unless @params == 2;
1127 return format_bool
($params[0] ne $params[1]);
1128 } elsif ($token eq '@not') {
1129 my @params = get_function_params
();
1130 error
('Usage: @not(a)') unless @params == 1;
1131 return format_bool
(not $params[0]);
1132 } elsif ($token eq '@cat') {
1134 map { $value .= $_ } get_function_params
();
1136 } elsif ($token eq '@substr') {
1137 my @params = get_function_params
();
1138 error
('Usage: @substr(string, num, num)') unless @params == 3;
1139 return substr($params[0],$params[1],$params[2]);
1140 } elsif ($token eq '@length') {
1141 my @params = get_function_params
();
1142 error
('Usage: @length(string)') unless @params == 1;
1143 return length($params[0]);
1144 } elsif ($token eq '@basename') {
1145 my @params = get_function_params
();
1146 error
('Usage: @basename(path)') unless @params == 1;
1147 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1149 } elsif ($token eq '@dirname') {
1150 my @params = get_function_params
();
1151 error
('Usage: @dirname(path)') unless @params == 1;
1152 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1155 error
("unknown ferm built-in function");
1162 # returns the next parameter, but only allow a scalar
1164 my $token = getvalues
();
1166 error
('array not allowed here')
1167 if ref $token and ref $token eq 'ARRAY';
1172 sub get_function_params
(%) {
1173 expect_token
('(', 'function name must be followed by "()"');
1175 my $token = peek_token
();
1176 if ($token eq ')') {
1177 require_next_token
();
1185 $token = require_next_token
();
1189 error
('"," expected')
1190 unless $token eq ',';
1193 push @params, getvalues
(undef, @_);
1199 # collect all tokens in a flat array reference until the end of the
1200 # command is reached
1201 sub collect_tokens
() {
1206 my $keyword = next_token
();
1207 error
('unexpected end of file within function/variable declaration')
1208 unless defined $keyword;
1210 if ($keyword =~ /^[\{\(]$/) {
1211 push @level, $keyword;
1212 } elsif ($keyword =~ /^[\}\)]$/) {
1213 my $expected = $keyword;
1214 $expected =~ tr/\}\)/\{\(/;
1215 my $opener = pop @level;
1216 error
("unmatched '$keyword'")
1217 unless defined $opener and $opener eq $expected;
1218 } elsif ($keyword eq ';' and @level == 0) {
1222 push @tokens, $keyword;
1225 if $keyword eq '}' and @level == 0;
1232 # returns the specified value as an array. dereference arrayrefs
1235 die unless wantarray;
1237 unless (ref $value) {
1239 } elsif (ref $value eq 'ARRAY') {
1246 # evaluate the specified value as bool
1251 unless (ref $value) {
1253 } elsif (ref $value eq 'ARRAY') {
1260 sub is_netfilter_core_target
($) {
1262 die unless defined $target and length $target;
1263 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1266 sub is_netfilter_module_target
($$) {
1267 my ($domain_family, $target) = @_;
1268 die unless defined $target and length $target;
1270 return defined $domain_family &&
1271 exists $target_defs{$domain_family} &&
1272 $target_defs{$domain_family}{$target};
1275 sub is_netfilter_builtin_chain
($$) {
1276 my ($table, $chain) = @_;
1278 return grep { $_ eq $chain }
1279 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1282 sub netfilter_canonical_protocol
($) {
1285 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1287 if $proto eq 'ipv6-mh';
1291 sub netfilter_protocol_module
($) {
1293 return unless defined $proto;
1295 if $proto eq 'icmpv6';
1299 # escape the string in a way safe for the shell
1300 sub shell_escape
($) {
1303 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1305 if ($option{fast
}) {
1306 # iptables-save/iptables-restore are quite buggy concerning
1307 # escaping and special characters... we're trying our best
1310 $token =~ s
,",\\",g
;
1311 $token = '"' . $token . '"'
1312 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1315 if $token =~ /^\`.*\`$/;
1316 $token =~ s/'/'\\''/g;
1317 $token = '\'' . $token . '\''
1318 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1324 # append an option to the shell command line, using information from
1325 # the module definition (see %match_defs etc.)
1326 sub shell_format_option
($$) {
1327 my ($keyword, $value) = @_;
1331 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1332 $value = $value->[0];
1337 unless (defined $value) {
1338 $cmd .= " --$keyword";
1339 } elsif (ref $value) {
1340 if (ref $value eq 'params') {
1341 $cmd .= " --$keyword ";
1342 $cmd .= join(' ', map { shell_escape
($_) } @
$value);
1343 } elsif (ref $value eq 'multi') {
1345 $cmd .= " --$keyword " . shell_escape
($_);
1351 $cmd .= " --$keyword " . shell_escape
($value);
1357 sub format_option
($$$) {
1358 my ($domain, $name, $value) = @_;
1359 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1360 and $value eq 'icmp';
1361 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1362 return shell_format_option
($name, $value);
1365 sub append_rule
($$) {
1366 my ($chain_rules, $rule) = @_;
1368 my $cmd = join('', map { $_->[2] } @
{$rule->{options
}});
1369 push @
$chain_rules, { rule
=> $cmd,
1370 script
=> $rule->{script
},
1375 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1376 return append_rule
($chain_rules, $rule) unless @_;
1379 my @values = @
{$option->[1]};
1381 foreach my $value (@values) {
1382 $option->[2] = format_option
($domain, $option->[0], $value);
1383 unfold_rule
($domain, $chain_rules, $rule, @_);
1388 my ($domain, $chain_rules, $rule) = @_;
1391 foreach my $option (@
{$rule->{options
}}) {
1392 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1393 push @unfold, $option
1395 $option->[2] = format_option
($domain, $option->[0], $option->[1]);
1399 unfold_rule
($domain, $chain_rules, $rule, @unfold);
1402 # convert a bunch of internal rule structures in iptables calls,
1403 # unfold arrays during that
1407 foreach my $domain (to_array
$rule->{domain
}) {
1408 my $domain_info = $domains{$domain};
1409 $domain_info->{enabled
} = 1;
1411 foreach my $table (to_array
$rule->{table
}) {
1412 my $table_info = $domain_info->{tables
}{$table} ||= {};
1414 foreach my $chain (to_array
$rule->{chain
}) {
1415 my $chain_rules = $table_info->{chains
}{$chain}{rules
} ||= [];
1416 mkrules2
($domain, $chain_rules, $rule)
1417 if $rule->{has_rule
} and not $option{flush
};
1423 # parse a keyword from a module definition
1424 sub parse_keyword
(\
%$$) {
1425 my ($rule, $def, $negated_ref) = @_;
1427 my $params = $def->{params
};
1432 if ($$negated_ref && exists $def->{pre_negation
}) {
1434 undef $$negated_ref;
1437 unless (defined $params) {
1439 } elsif (ref $params && ref $params eq 'CODE') {
1440 $value = &$params($rule);
1441 } elsif ($params eq 'm') {
1442 $value = bless [ to_array getvalues
() ], 'multi';
1443 } elsif ($params =~ /^[a-z]/) {
1444 if (exists $def->{negation
} and not $negated) {
1445 my $token = peek_token
();
1446 if ($token eq '!') {
1447 require_next_token
();
1453 foreach my $p (split(//, $params)) {
1455 push @params, getvar
();
1456 } elsif ($p eq 'c') {
1457 my @v = to_array getvalues
(undef, non_empty
=> 1);
1458 push @params, join(',', @v);
1464 $value = @params == 1
1466 : bless \
@params, 'params';
1467 } elsif ($params == 1) {
1468 if (exists $def->{negation
} and not $negated) {
1469 my $token = peek_token
();
1470 if ($token eq '!') {
1471 require_next_token
();
1476 $value = getvalues
();
1478 warning
("log-prefix is too long; truncating to 29 characters: '$1'")
1479 if $def->{name
} eq 'log-prefix' && $value =~ s
,^(.{29}).+$,$1,;
1481 if (exists $def->{negation
} and not $negated) {
1482 my $token = peek_token
();
1483 if ($token eq '!') {
1484 require_next_token
();
1489 $value = bless [ map {
1491 } (1..$params) ], 'params';
1494 $value = negate_value
($value, exists $def->{pre_negation
} && 'pre_negated')
1500 sub append_option
(\
%$$) {
1501 my ($rule, $name, $value) = @_;
1502 push @
{$rule->{options
}}, [ $name, $value ];
1505 # parse options of a module
1506 sub parse_option
($\
%$) {
1507 my ($def, $rule, $negated_ref) = @_;
1509 append_option
(%$rule, $def->{name
},
1510 parse_keyword
(%$rule, $def, $negated_ref));
1513 sub copy_on_write
($$) {
1514 my ($rule, $key) = @_;
1515 return unless exists $rule->{cow
}{$key};
1516 $rule->{$key} = {%{$rule->{$key}}};
1517 delete $rule->{cow
}{$key};
1520 sub new_level
(\
%$) {
1521 my ($rule, $prev) = @_;
1524 if (defined $prev) {
1525 # copy data from previous level
1526 $rule->{cow
} = { keywords
=> 1, };
1527 $rule->{keywords
} = $prev->{keywords
};
1528 $rule->{match
} = { %{$prev->{match
}} };
1529 $rule->{options
} = [@
{$prev->{options
}}];
1530 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1531 $rule->{$key} = $prev->{$key}
1532 if exists $prev->{$key};
1536 $rule->{keywords
} = {};
1537 $rule->{match
} = {};
1538 $rule->{options
} = [];
1542 sub merge_keywords
(\
%$) {
1543 my ($rule, $keywords) = @_;
1544 copy_on_write
($rule, 'keywords');
1545 while (my ($name, $def) = each %$keywords) {
1546 $rule->{keywords
}{$name} = $def;
1550 sub set_domain
(\
%$) {
1551 my ($rule, $domain) = @_;
1553 my $filtered_domain = filter_domains
($domain);
1555 unless (ref $domain) {
1556 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1557 } elsif (@
$domain == 0) {
1558 $domain_family = 'none';
1559 } elsif (grep { not /^ip6?$/s } @
$domain) {
1560 error
('Cannot combine non-IP domains');
1562 $domain_family = 'ip';
1565 $rule->{domain_family
} = $domain_family;
1566 $rule->{keywords
} = $match_defs{$domain_family}{''}{keywords
};
1567 $rule->{cow
}{keywords
} = 1;
1569 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $filtered_domain;
1572 sub set_target
(\
%$$) {
1573 my ($rule, $name, $value) = @_;
1574 error
('There can only one action per rule')
1575 if exists $rule->{has_action
};
1576 $rule->{has_action
} = 1;
1577 append_option
(%$rule, $name, $value);
1580 sub set_module_target
(\
%$$) {
1581 my ($rule, $name, $defs) = @_;
1583 if ($name eq 'TCPMSS') {
1584 my $protos = $rule->{protocol
};
1585 error
('No protocol specified before TCPMSS')
1586 unless defined $protos;
1587 foreach my $proto (to_array
$protos) {
1588 error
('TCPMSS not available for protocol "$proto"')
1589 unless $proto eq 'tcp';
1593 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1594 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family
} eq 'eb';
1596 set_target
(%$rule, 'jump', $name);
1597 merge_keywords
(%$rule, $defs->{keywords
});
1600 # the main parser loop: read tokens, convert them into internal rule
1603 my $lev = shift; # current recursion depth
1604 my $prev = shift; # previous rule hash
1606 # enter is the core of the firewall setup, it is a
1607 # simple parser program that recognizes keywords and
1608 # retreives parameters to set up the kernel routing
1611 my $base_level = $script->{base_level
} || 0;
1612 die if $base_level > $lev;
1615 new_level
(%rule, $prev);
1617 # read keywords 1 by 1 and dump into parser
1618 while (defined (my $keyword = next_token
())) {
1619 # check if the current rule should be negated
1620 my $negated = $keyword eq '!';
1622 # negation. get the next word which contains the 'real'
1624 $keyword = getvar
();
1626 error
('unexpected end of file after negation')
1627 unless defined $keyword;
1630 # the core: parse all data
1633 # deprecated keyword?
1634 if (exists $deprecated_keywords{$keyword}) {
1635 my $new_keyword = $deprecated_keywords{$keyword};
1636 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1637 $keyword = $new_keyword;
1640 # effectuation operator
1641 if ($keyword eq ';') {
1642 error
('Empty rule before ";" not allowed')
1643 unless $rule{non_empty
};
1645 if ($rule{has_rule
} and not exists $rule{has_action
}) {
1646 # something is wrong when a rule was specified,
1648 error
('No action defined; did you mean "NOP"?');
1651 error
('No chain defined') unless exists $rule{chain
};
1653 $rule{script
} = { filename
=> $script->{filename
},
1654 line
=> $script->{line
},
1659 # and clean up variables set in this level
1660 new_level
(%rule, $prev);
1665 # conditional expression
1666 if ($keyword eq '@if') {
1667 unless (eval_bool
(getvalues
)) {
1669 my $token = peek_token
();
1670 require_next_token
() if $token and $token eq '@else';
1676 if ($keyword eq '@else') {
1677 # hack: if this "else" has not been eaten by the "if"
1678 # handler above, we believe it came from an if clause
1679 # which evaluated "true" - remove the "else" part now.
1684 # hooks for custom shell commands
1685 if ($keyword eq 'hook') {
1686 warning
("'hook' is deprecated, use '\@hook'");
1690 if ($keyword eq '@hook') {
1691 error
('"hook" must be the first token in a command')
1692 if exists $rule{domain
};
1694 my $position = getvar
();
1696 if ($position eq 'pre') {
1697 $hooks = \
@pre_hooks;
1698 } elsif ($position eq 'post') {
1699 $hooks = \
@post_hooks;
1700 } elsif ($position eq 'flush') {
1701 $hooks = \
@flush_hooks;
1703 error
("Invalid hook position: '$position'");
1706 push @
$hooks, getvar
();
1712 # recursing operators
1713 if ($keyword eq '{') {
1715 my $old_stack_depth = @stack;
1717 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1720 enter
($lev + 1, \
%rule);
1724 die unless @stack == $old_stack_depth;
1726 # after a block, the command is finished, clear this
1728 new_level
(%rule, $prev);
1733 if ($keyword eq '}') {
1734 error
('Unmatched "}"')
1735 if $lev <= $base_level;
1737 # consistency check: check if they havn't forgotten
1738 # the ';' after the last statement
1739 error
('Missing semicolon before "}"')
1740 if $rule{non_empty
};
1746 # include another file
1747 if ($keyword eq '@include' or $keyword eq 'include') {
1748 my @files = collect_filenames to_array getvalues
;
1749 $keyword = next_token
;
1750 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1751 unless defined $keyword and $keyword eq ';';
1753 foreach my $filename (@files) {
1754 # save old script, open new script
1755 my $old_script = $script;
1756 open_script
($filename);
1757 $script->{base_level
} = $lev + 1;
1760 my $old_stack_depth = @stack;
1765 # include files may set variables for their parent
1766 $stack->{vars
} = ($stack[0]{vars
} ||= {});
1767 $stack->{functions
} = ($stack[0]{functions
} ||= {});
1768 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
1771 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $filename );
1772 $stack->{auto
}{FILENAME
} = $filename;
1773 $stack->{auto
}{FILEBNAME
} = $file;
1774 $stack->{auto
}{DIRNAME
} = $dirs;
1776 unshift @stack, $stack;
1779 enter
($lev + 1, \
%rule);
1783 die unless @stack == $old_stack_depth;
1785 # restore old script
1786 $script = $old_script;
1792 # definition of a variable or function
1793 if ($keyword eq '@def' or $keyword eq 'def') {
1794 error
('"def" must be the first token in a command')
1795 if $rule{non_empty
};
1797 my $type = require_next_token
();
1799 my $name = require_next_token
();
1800 error
('invalid variable name')
1801 unless $name =~ /^\w+$/;
1805 my $value = getvalues
(undef, allow_negation
=> 1);
1809 $stack[0]{vars
}{$name} = $value
1810 unless exists $stack[-1]{vars
}{$name};
1811 } elsif ($type eq '&') {
1812 my $name = require_next_token
();
1813 error
('invalid function name')
1814 unless $name =~ /^\w+$/;
1816 expect_token
('(', 'function parameter list or "()" expected');
1820 my $token = require_next_token
();
1821 last if $token eq ')';
1824 error
('"," expected')
1825 unless $token eq ',';
1827 $token = require_next_token
();
1830 error
('"$" and parameter name expected')
1831 unless $token eq '$';
1833 $token = require_next_token
();
1834 error
('invalid function parameter name')
1835 unless $token =~ /^\w+$/;
1837 push @params, $token;
1842 $function{params
} = \
@params;
1846 my $tokens = collect_tokens
();
1847 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
1848 $function{tokens
} = $tokens;
1850 $stack[0]{functions
}{$name} = \
%function
1851 unless exists $stack[-1]{functions
}{$name};
1853 error
('"$" (variable) or "&" (function) expected');
1859 # this rule has something which isn't inherited by its
1860 # parent closure. This variable is used in a lot of
1863 $rule{non_empty
} = 1;
1866 if ($keyword eq '$') {
1867 error
('variable references are only allowed as keyword parameter');
1870 if ($keyword eq '&') {
1871 my $name = require_next_token
();
1872 error
('function name expected')
1873 unless $name =~ /^\w+$/;
1877 $function = $_->{functions
}{$name};
1878 last if defined $function;
1880 error
("no such function: \&$name")
1881 unless defined $function;
1883 my $paramdef = $function->{params
};
1884 die unless defined $paramdef;
1886 my @params = get_function_params
(allow_negation
=> 1);
1888 error
("Wrong number of parameters for function '\&$name': "
1889 . @
$paramdef . " expected, " . @params . " given")
1890 unless @params == @
$paramdef;
1893 for (my $i = 0; $i < @params; $i++) {
1894 $vars{$paramdef->[$i]} = $params[$i];
1897 if ($function->{block
}) {
1898 # block {} always ends the current rule, so if the
1899 # function contains a block, we have to require
1900 # the calling rule also ends here
1904 my @tokens = @
{$function->{tokens
}};
1905 for (my $i = 0; $i < @tokens; $i++) {
1906 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1907 exists $vars{$tokens[$i + 1]}) {
1908 my @value = to_array
($vars{$tokens[$i + 1]});
1909 @value = ('(', @value, ')')
1910 unless @tokens == 1;
1911 splice(@tokens, $i, 2, @value);
1913 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
1914 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
1918 unshift @
{$script->{tokens
}}, @tokens;
1923 # where to put the rule?
1924 if ($keyword eq 'domain') {
1925 error
('Domain is already specified')
1926 if exists $rule{domain
};
1928 set_domain
(%rule, getvalues
());
1932 if ($keyword eq 'table') {
1933 warning
('Table is already specified')
1934 if exists $rule{table
};
1935 $rule{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
1937 set_domain
(%rule, 'ip')
1938 unless exists $rule{domain
};
1943 if ($keyword eq 'chain') {
1944 warning
('Chain is already specified')
1945 if exists $rule{chain
};
1947 my $chain = $rule{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
1949 # ferm 1.1 allowed lower case built-in chain names
1950 foreach (ref $rule{chain
} ? @
{$rule{chain
}} : $rule{chain
}) {
1951 error
('Please write built-in chain names in upper case')
1952 if /^(?:input|forward|output|prerouting|postrouting)$/;
1955 set_domain
(%rule, 'ip')
1956 unless exists $rule{domain
};
1958 $rule{table
} = 'filter'
1959 unless exists $rule{table
};
1961 foreach my $domain (to_array
$rule{domain
}) {
1962 foreach my $table (to_array
$rule{table
}) {
1963 foreach my $c (to_array
$chain) {
1964 $domains{$domain}{tables
}{$table}{chains
}{$c} ||= {};
1972 error
('Chain must be specified')
1973 unless exists $rule{chain
};
1975 # policy for built-in chain
1976 if ($keyword eq 'policy') {
1977 error
('Cannot specify matches for policy')
1980 my $policy = getvar
();
1981 error
("Invalid policy target: $policy")
1982 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1986 foreach my $domain (to_array
$rule{domain
}) {
1987 my $domain_info = $domains{$domain};
1988 $domain_info->{enabled
} = 1;
1990 foreach my $table (to_array
$rule{table
}) {
1991 foreach my $chain (to_array
$rule{chain
}) {
1992 $domain_info->{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
1997 new_level
(%rule, $prev);
2002 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2003 error
('Chain must be specified')
2004 unless exists $rule{chain
};
2006 error
('No rule specified before "@subchain"')
2007 unless $rule{has_rule
};
2010 my $token = peek_token
();
2012 if ($token =~ /^(["'])(.*)\1$/s) {
2015 $keyword = next_token
();
2016 } elsif ($token eq '{') {
2017 $keyword = next_token
();
2018 $subchain = 'ferm_auto_' . ++$auto_chain;
2020 $subchain = getvar
();
2021 $keyword = next_token
();
2024 foreach my $domain (to_array
$rule{domain
}) {
2025 foreach my $table (to_array
$rule{table
}) {
2026 $domains{$domain}{tables
}{$table}{chains
}{$subchain} ||= {};
2030 set_target
(%rule, 'jump', $subchain);
2032 error
('"{" or chain name expected after "@subchain"')
2033 unless $keyword eq '{';
2035 # create a deep copy of %rule, only containing values
2036 # which must be in the subchain
2037 my %inner = ( cow
=> { keywords
=> 1, },
2041 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
2042 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2044 if (exists $rule{protocol
}) {
2045 $inner{protocol
} = $rule{protocol
};
2046 append_option
(%inner, 'protocol', $inner{protocol
});
2049 # create a new stack frame
2050 my $old_stack_depth = @stack;
2051 my $stack = { auto
=> { %{$stack[0]{auto
} || {}} } };
2052 $stack->{auto
}{CHAIN
} = $subchain;
2053 unshift @stack, $stack;
2056 enter
($lev + 1, \
%inner);
2060 die unless @stack == $old_stack_depth;
2062 # now handle the parent - it's a jump to the sub chain
2064 filename
=> $script->{filename
},
2065 line
=> $script->{line
},
2070 # and clean up variables set in this level
2071 new_level
(%rule, $prev);
2072 delete $rule{has_rule
};
2077 # everything else must be part of a "real" rule, not just
2079 $rule{has_rule
} = 1;
2081 # extended parameters:
2082 if ($keyword =~ /^mod(?:ule)?$/) {
2083 foreach my $module (to_array getvalues
) {
2084 next if exists $rule{match
}{$module};
2086 my $domain_family = $rule{domain_family
};
2087 my $defs = $match_defs{$domain_family}{$module};
2089 append_option
(%rule, 'match', $module);
2090 $rule{match
}{$module} = 1;
2092 merge_keywords
(%rule, $defs->{keywords
})
2099 # keywords from $rule{keywords}
2101 if (exists $rule{keywords
}{$keyword}) {
2102 my $def = $rule{keywords
}{$keyword};
2103 parse_option
($def, %rule, \
$negated);
2112 if ($keyword eq 'jump') {
2113 set_target
(%rule, 'jump', getvar
());
2118 if ($keyword eq 'realgoto') {
2119 set_target
(%rule, 'goto', getvar
());
2124 if (is_netfilter_core_target
($keyword)) {
2125 set_target
(%rule, 'jump', $keyword);
2129 if ($keyword eq 'NOP') {
2130 error
('There can only one action per rule')
2131 if exists $rule{has_action
};
2132 $rule{has_action
} = 1;
2136 if (my $defs = is_netfilter_module_target
($rule{domain_family
}, $keyword)) {
2137 set_module_target
(%rule, $keyword, $defs);
2142 # protocol specific options
2145 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2146 my $protocol = parse_keyword
(%rule,
2147 { params
=> 1, negation
=> 1 },
2149 $rule{protocol
} = $protocol;
2150 append_option
(%rule, 'protocol', $rule{protocol
});
2152 unless (ref $protocol) {
2153 $protocol = netfilter_canonical_protocol
($protocol);
2154 my $domain_family = $rule{domain_family
};
2155 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2156 merge_keywords
(%rule, $defs->{keywords
});
2157 my $module = netfilter_protocol_module
($protocol);
2158 $rule{match
}{$module} = 1;
2165 if ($keyword =~ /^[sd]port$/) {
2166 my $proto = $rule{protocol
};
2167 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2168 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2170 append_option
(%rule, $keyword,
2171 getvalues
(undef, allow_negation
=> 1));
2176 error
("Unrecognized keyword: $keyword");
2179 # if the rule didn't reset the negated flag, it's not
2181 error
("Doesn't support negation: $keyword")
2185 error
('Missing "}" at end of file')
2186 if $lev > $base_level;
2188 # consistency check: check if they havn't forgotten
2189 # the ';' before the last statement
2190 error
("Missing semicolon before end of file")
2191 if $rule{non_empty
};
2194 sub execute_command
{
2195 my ($command, $script) = @_;
2197 print LINES
"$command\n"
2199 return if $option{noexec
};
2201 my $ret = system($command);
2202 unless ($ret == 0) {
2204 print STDERR
"failed to execute: $!\n";
2206 } elsif ($?
& 0x7f) {
2207 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2210 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2219 sub execute_slow
($) {
2220 my $domain_info = shift;
2222 my $domain_cmd = $domain_info->{tools
}{tables
};
2225 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2226 my $table_cmd = "$domain_cmd -t $table";
2228 # reset chain policies
2229 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2230 next unless $chain_info->{builtin
} or
2231 (not $table_info->{has_builtin
} and
2232 is_netfilter_builtin_chain
($table, $chain));
2233 $status ||= execute_command
("$table_cmd -P $chain ACCEPT")
2234 unless $option{noflush
};
2238 unless ($option{noflush
}) {
2239 $status ||= execute_command
("$table_cmd -F");
2240 $status ||= execute_command
("$table_cmd -X");
2243 next if $option{flush
};
2245 # create chains / set policy
2246 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2247 if (exists $chain_info->{policy
}) {
2248 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2249 unless $chain_info->{policy
} eq 'ACCEPT';
2250 } elsif (not is_netfilter_builtin_chain
($table, $chain)) {
2251 $status ||= execute_command
("$table_cmd -N $chain");
2256 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2257 my $chain_cmd = "$table_cmd -A $chain";
2258 foreach my $rule (@
{$chain_info->{rules
}}) {
2259 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2267 sub table_to_save
($$) {
2268 my ($result_r, $table_info) = @_;
2270 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2271 my $chain_info = $table_info->{chains
}{$chain};
2272 foreach my $rule (@
{$chain_info->{rules
}}) {
2273 $$result_r .= "-A $chain$rule->{rule}\n";
2278 sub rules_to_save
($) {
2279 my ($domain_info) = @_;
2281 # convert this into an iptables-save text
2282 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2284 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2286 $result .= '*' . $table . "\n";
2288 # create chains / set policy
2289 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2290 my $chain_info = $table_info->{chains
}{$chain};
2291 my $policy = $option{flush
} ?
undef : $chain_info->{policy
};
2292 unless (defined $policy) {
2293 if (is_netfilter_builtin_chain
($table, $chain)) {
2296 next if $option{flush
};
2300 $result .= ":$chain $policy\ [0:0]\n";
2303 table_to_save
(\
$result, $table_info)
2304 unless $option{flush
};
2307 $result .= "COMMIT\n";
2313 sub restore_domain
($$) {
2314 my ($domain_info, $save) = @_;
2316 my $path = $domain_info->{tools
}{'tables-restore'};
2319 open RESTORE
, "|$path"
2320 or die "Failed to run $path: $!\n";
2322 print RESTORE
$save;
2325 or die "Failed to run $path\n";
2328 sub execute_fast
($) {
2329 my $domain_info = shift;
2331 my $save = rules_to_save
($domain_info);
2333 if ($option{lines
}) {
2334 print LINES
"$domain_info->{tools}{'tables-restore'} <<EOT\n"
2341 return if $option{noexec};
2344 restore_domain($domain_info, $save);
2356 while (my ($domain, $domain_info) = each %domains) {
2357 next unless $domain_info->{enabled};
2358 unless (defined $domain_info->{tools}{'tables-restore'}) {
2359 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2364 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2365 my $reset_chain = '';
2366 foreach my $chain (keys %{$table_info->{chains}}) {
2367 next unless is_netfilter_builtin_chain($table, $chain);
2368 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2370 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2371 if length $reset_chain;
2374 $reset .= $domain_info->{previous}
2375 if defined $domain_info->{previous};
2377 restore_domain($domain_info, $reset);
2380 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2385 # do nothing, just interrupt a system call
2389 $SIG{ALRM} = \&alrm_handler;
2394 . "ferm has applied the new firewall rules
.\n"
2395 . "Please type
'yes' to confirm
:\n";
2398 alarm($option{timeout});
2401 STDIN->sysread($line, 3);
2405 POSIX::tcflush(*STDIN, 2);
2407 print STDERR "$@
" if $@;
2409 $SIG{ALRM} = 'DEFAULT';
2411 return $line eq 'yes';
2420 ferm - a firewall rule parser for linux
2424 B<ferm> I<options> I<inputfiles>
2428 -n, --noexec Do not execute the rules, just simulate
2429 -F, --flush Flush all netfilter tables managed by ferm
2430 -l, --lines Show all rules that were created
2431 -i, --interactive Interactive mode: revert if user does not confirm
2432 -t, --timeout s Define interactive mode timeout in seconds
2433 --remote Remote mode; ignore host specific configuration.
2434 This implies --noexec and --lines.
2435 -V, --version Show current version number
2436 -h, --help Look at this text
2437 --slow Slow mode, don't use iptables-restore
2438 --shell Generate a shell script which calls iptables-restore
2439 --domain {ip|ip6} Handle only the specified domain
2440 --def '$name=v' Override a variable