4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2007 Auke Kok, Max Kellermann
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
31 eval { require strict
; import strict
; };
34 # we need no vars.pm if there is not even strict.pm
36 *vars
::import
= sub {};
41 eval { require Getopt
::Long
; import Getopt
::Long
; };
45 use vars
qw($has_strict $has_getopt);
47 use vars qw($DATE $VERSION);
49 # subversion keyword magic
50 $DATE = '$Date$' =~ m,(\d{4})-(\d\d)-(\d\d), ? $1.$2.$3 : '';
53 $VERSION .= '~svn' . $DATE;
55 ## interface variables
56 # %option = command line and other options
60 use vars qw(@pre_hooks @post_hooks);
63 # $script: current script file
64 # @stack = ferm's parser stack containing local variables
65 # $auto_chain = index for the next auto-generated chain
66 use vars qw($script @stack $auto_chain);
68 ## netfilter variables
69 # %domains = state information about all domains ("ip" and "ip6")
70 # - initialized: domain initialization is done
71 # - tools: hash providing the paths of the domain's tools
72 # - previous: save file of the previous ruleset, for rollback
73 # - reset: has this domain already been reset?
74 # - tables{$name}: ferm state information about tables
75 # - chains{$chain}: ferm state information about the chains
76 # - builtin: whether this is a built-in chain
77 # - was_created: custom chain has been created
78 # - non_empty: are there rules for this chain?
79 use vars qw(%domains);
82 use vars qw(%deprecated_keywords);
84 # keywords from ferm 1.1 which are deprecated, and the new one; these
85 # are automatically replaced, and a warning is printed
86 %deprecated_keywords = ( goto => 'jump',
89 # these hashes provide the Netfilter module definitions
90 use vars qw(%proto_defs %match_defs %target_defs);
93 # This subsubsystem allows you to support (most) new netfilter modules
94 # in ferm. Add a call to one of the "add_XY_def()" functions below.
96 # Ok, now about the cryptic syntax: the function "add_XY_def()"
97 # registers a new module. There are three kinds of modules: protocol
98 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
99 # target modules (e.g. DNAT, MARK).
101 # The first parameter is always the module name which is passed to
102 # iptables with "-p", "-m" or "-j" (depending on which kind of module
105 # After that, you add an encoded string for each option the module
106 # supports. This is where it becomes tricky.
108 # foo defaults to an option with one argument (which may be a ferm
111 # foo*0 option without any arguments
113 # foo=s one argument which must not be a ferm array ('s' stands for
116 # u32=m an array which renders into multiple iptables options in one
119 # ctstate=c one argument, if it's an array, pass it to iptables as a
120 # single comma separated value; example:
121 # ctstate (ESTABLISHED RELATED) translates to:
122 # --ctstate ESTABLISHED,RELATED
124 # foo=sac three arguments: scalar, array, comma separated; you may
125 # concatenate more than one letter code after the '='
127 # foo&bar one argument; call the perl function '&bar()' which parses
130 # !foo negation is allowed and the '!' is written before the keyword
132 # foo! same as above, but '!' is after the keyword and before the
135 # to:=to-destination makes "to" an alias for "to-destination"; you have
136 # to add a declaration for option "to-destination"
139 # add a module definition
142 my $domain_family = shift;
144 die if exists $defs->{$domain_family}{$name};
145 my $def = $defs->{$domain_family}{$name} = {};
151 $params = $1 if $keyword =~ s,\*(\d+)$,,;
152 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
153 if ($keyword =~ s,&(\S+)$,,) {
154 $params = eval "\\&$1";
157 $k->{params} = $params if $params;
159 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
160 $k->{negation} = 1 if $keyword =~ s,!$,,;
162 $k->{alias} = [$1, $def->{keywords}{$1} || die] if $keyword =~ s,:=(\S+)$,,;
164 $def->{keywords}{$keyword} = $k;
170 # add a protocol module definition
171 sub add_proto_def_x(@) {
172 add_def_x(\%proto_defs, @_);
175 # add a match module definition
176 sub add_match_def_x(@) {
177 add_def_x(\%match_defs, @_);
180 # add a target module definition
181 sub add_target_def_x(@) {
182 add_def_x(\%target_defs, @_);
187 add_def_x($defs, 'ip', @_);
190 # add a protocol module definition
191 sub add_proto_def(@) {
192 add_def(\%proto_defs, @_);
195 # add a match module definition
196 sub add_match_def(@) {
197 add_def(\%match_defs, @_);
200 # add a target module definition
201 sub add_target_def(@) {
202 add_def(\%target_defs, @_);
205 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
206 add_proto_def
'mh', qw(mh-type!);
207 add_proto_def
'icmp', qw(icmp-type!);
208 add_proto_def
'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
209 add_proto_def
'sctp', qw(chunk-types!=sc);
210 add_proto_def
'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
211 add_proto_def
'udp', qw();
215 qw(protocol! proto:=protocol),
216 # --source, --destination
217 qw(source! saddr:=source destination! daddr:=destination),
219 qw(in-interface! interface:=in-interface if:=in-interface),
221 qw(out-interface! outerface:=out-interface of:=out-interface),
224 add_match_def
'account', qw(aaddr=s aname=s ashort*0);
225 add_match_def
'addrtype', qw(src-type dst-type);
226 add_match_def
'ah', qw(ahspi! ahlen! ahres*0);
227 add_match_def
'comment', qw(comment=s);
228 add_match_def
'condition', qw(condition!);
229 add_match_def
'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
230 add_match_def
'connlimit', qw(!connlimit-above connlimit-mask);
231 add_match_def
'connmark', qw(mark);
232 add_match_def
'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
233 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
234 add_match_def
'dscp', qw(dscp dscp-class);
235 add_match_def
'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
236 add_match_def
'esp', qw(espspi!);
237 add_match_def
'eui64';
238 add_match_def
'fuzzy', qw(lower-limit=s upper-limit=s);
239 add_match_def
'hbh', qw(hbh-len! hbh-opts=c);
240 add_match_def
'helper', qw(helper);
241 add_match_def
'hl', qw(hl-eq! hl-lt=s hl-gt=s);
242 add_match_def
'length', qw(length!);
243 add_match_def
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
244 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
245 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
246 add_match_def
'iprange', qw(!src-range !dst-range);
247 add_match_def
'ipv6header', qw(header!=c soft*0);
248 add_match_def
'limit', qw(limit=s limit-burst=s);
249 add_match_def
'mac', qw(mac-source!);
250 add_match_def
'mark', qw(mark);
251 add_match_def
'multiport', qw(source-ports!&multiport_params),
252 qw(destination-ports!&multiport_params ports!&multiport_params);
253 add_match_def
'nth', qw(every counter start packet);
254 add_match_def
'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
255 add_match_def
'physdev', qw(physdev-in! physdev-out!),
256 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
257 add_match_def
'pkttype', qw(pkt-type),
258 add_match_def
'policy',
259 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
260 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
261 qw(psd-lo-ports-weight psd-hi-ports-weight);
262 add_match_def
'quota', qw(quota=s);
263 add_match_def
'random', qw(average);
264 add_match_def
'realm', qw(realm!);
265 add_match_def
'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0);
266 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
267 add_match_def
'set', qw(set=sc);
268 add_match_def
'state', qw(state=c);
269 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
270 add_match_def
'tcpmss', qw(!mss);
271 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s);
272 add_match_def
'tos', qw(!tos);
273 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
274 add_match_def
'u32', qw(u32=m);
276 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
277 add_target_def
'CLASSIFY', qw(set-class);
278 add_target_def
'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
279 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
280 add_target_def
'DNAT', qw(to-destination to:=to-destination);
281 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
282 add_target_def
'ECN', qw(ecn-tcp-remove*0);
283 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
284 add_target_def
'LOG', qw(log-level log-prefix),
285 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
286 add_target_def
'MARK', qw(set-mark);
287 add_target_def
'MASQUERADE', qw(to-ports);
288 add_target_def
'MIRROR';
289 add_target_def
'NETMAP', qw(to);
290 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
291 add_target_def
'NFQUEUE', qw(queue-num);
292 add_target_def
'NOTRACK';
293 add_target_def
'REDIRECT', qw(to-ports);
294 add_target_def
'REJECT', qw(reject-with);
295 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
296 add_target_def
'SAME', qw(to nodst*0);
297 add_target_def
'SECMARK', qw(selctx);
298 add_target_def
'SET', qw(add-set=sc del-set=sc);
299 add_target_def
'SNAT', qw(to-source=m to:=to-source);
300 add_target_def
'TARPIT';
301 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
302 add_target_def
'TOS', qw(set-tos);
303 add_target_def
'TRACE';
304 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
305 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
307 add_match_def_x
'arp', '',
309 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
311 qw(source-mac! destination-mac!),
313 qw(in-interface! interface:=in-interface if:=in-interface),
315 qw(out-interface! outerface:=out-interface of:=out-interface),
317 qw(h-length=s opcode=s h-type=s proto-type=s),
318 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
320 add_match_def_x
'eb', '',
322 qw(protocol! proto:=protocol),
324 qw(in-interface! interface:=in-interface if:=in-interface),
326 qw(out-interface! outerface:=out-interface of:=out-interface),
328 qw(logical-in! logical-out!),
329 # --source, --destination
330 qw(source! saddr:=source destination! daddr:=destination),
332 qw(802_3-sap! 802_3-type!),
334 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
335 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
337 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
343 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
344 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
345 qw(stp-hello-time! stp-forward-delay!),
347 qw(vlan-id! vlan-prio! vlan-encap!),
349 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
351 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
352 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
353 add_target_def_x
'eb', 'mark', qw(set-mark mark-target);
354 add_target_def_x
'eb', 'redirect', qw(redirect-target);
355 add_target_def_x
'eb', 'snat', qw(to-source snat-target);
357 use vars
qw(%builtin_keywords);
359 sub get_builtin_keywords($) {
360 my $domain_family = shift;
361 return {} unless defined $domain_family;
363 return {%{$builtin_keywords{$domain_family}}}
364 if exists $builtin_keywords{$domain_family};
366 return {} unless exists $match_defs{$domain_family};
367 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
368 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
370 $builtin_keywords{$domain_family} = \%keywords;
374 # parameter parser for ipt_multiport
375 sub multiport_params {
378 # multiport only allows 15 ports at a time. For this
379 # reason, we do a little magic here: split the ports
380 # into portions of 15, and handle these portions as
383 my $proto = $fw->{builtin}{protocol};
384 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
385 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
387 my $value = getvalues(undef, undef,
389 allow_array_negation => 1);
390 if (ref $value and ref $value eq 'ARRAY') {
395 push @params, join(',', splice(@value, 0, 15));
402 return join_value(',', $value);
406 # initialize stack: command line definitions
409 # Get command line stuff
411 my ($opt_noexec, $opt_flush, $opt_lines, $opt_interactive,
412 $opt_verbose, $opt_debug,
414 $opt_version, $opt_test, $opt_fast, $opt_shell,
417 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
421 my ($opt, $value) = @_;
422 die 'Invalid --def specification'
423 unless $value =~ /^\$?(\w+)=(.*)$/s;
424 my ($name, $unparsed_value) = ($1, $2);
425 my $tokens = tokenize_string($unparsed_value);
426 my $value = getvalues(\&next_array_token, $tokens);
427 die 'Extra tokens after --def'
429 $stack[0]{vars}{$name} = $value;
432 local $SIG{__WARN__} = sub { die $_[0]; };
433 GetOptions('noexec|n' => \$opt_noexec,
434 'flush|F' => \$opt_flush,
435 'lines|l' => \$opt_lines,
436 'interactive|i' => \$opt_interactive,
437 'verbose|v' => \$opt_verbose,
438 'debug|d' => \$opt_debug,
439 'help|h' => \$opt_help,
440 'version|V' => \$opt_version,
442 remote => \$opt_test,
444 shell => \$opt_shell,
445 'domain=s' => \$opt_domain,
446 'def=s' => \&opt_def,
449 if (defined $opt_help) {
451 Pod::Usage::pod2usage(-exitstatus => 0);
454 if (defined $opt_version) {
459 $option{'noexec'} = (defined $opt_noexec);
460 $option{flush} = defined $opt_flush;
461 $option{'lines'} = (defined $opt_lines);
462 $option{interactive} = (defined $opt_interactive);
463 $option{test} = (defined $opt_test);
470 delete $option{interactive} if $option{noexec};
472 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
473 if $option{interactive} and not -t STDIN;
474 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
475 if $option{interactive} and not -t STDERR;
477 $option{fast} = 1 if defined $opt_fast;
479 if (defined $opt_shell) {
480 $option{$_} = 1 foreach qw(shell fast lines);
483 $option{domain
} = $opt_domain if defined $opt_domain;
485 print STDERR
"Warning: ignoring the obsolete --debug option\n"
486 if defined $opt_debug;
487 print STDERR
"Warning: ignoring the obsolete --verbose option\n"
488 if defined $opt_verbose;
490 # tiny getopt emulation for microperl
493 if ($_ eq '--noexec' or $_ eq '-n') {
495 } elsif ($_ eq '--lines' or $_ eq '-l') {
497 } elsif ($_ eq '--fast') {
499 } elsif ($_ eq '--test') {
503 } elsif ($_ eq '--shell') {
504 $option{$_} = 1 foreach qw(shell fast lines);
506 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
513 push @ARGV, $filename;
516 unless (@ARGV == 1) {
518 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
522 open LINES
, ">&STDOUT" if $option{lines
};
523 open STDOUT
, ">&STDERR" if $option{shell
};
525 # microperl can't redirect file handles
528 if ($option{fast
} and not $option{noexec
}) {
529 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
535 open_script
($ARGV[0]);
537 # parse all input recursively
539 die unless @stack == 2;
544 # execute all generated rules
547 foreach my $cmd (@pre_hooks) {
548 print LINES
"$cmd\n" if $option{lines
};
549 system($cmd) unless $option{noexec
};
552 while (my ($domain, $domain_info) = each %domains) {
553 next unless $domain_info->{enabled
};
554 my $s = $option{fast
} &&
555 defined $domain_info->{tools
}{'tables-restore'}
556 ? execute_fast
($domain, $domain_info)
557 : execute_slow
($domain, $domain_info);
558 $status = $s if defined $s;
561 foreach my $cmd (@post_hooks) {
562 print "$cmd\n" if $option{lines
};
563 system($cmd) unless $option{noexec
};
566 if (defined $status) {
571 # ask user, and rollback if there is no confirmation
573 confirm_rules
() or rollback
() if $option{interactive
};
577 # end of program execution!
583 print "ferm $VERSION\n";
584 print "Copyright (C) 2001-2007 Auke Kok, Max Kellermann\n";
585 print "This program is free software released under GPLv2.\n";
586 print "See the included COPYING file for license details.\n";
598 # returns a nice formatted error message, showing the
599 # location of the error.
603 my @words = map { @
$_ } @
{$script->{past_tokens
}};
605 for my $w ( 0 .. $#words ) {
606 if ($words[$w] eq "\x29")
607 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
608 if ($words[$w] eq "\x28")
609 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
610 if ($words[$w] eq "\x7d")
611 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
612 if ($words[$w] eq "\x7b")
613 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
614 if ( $l > $#lines ) { $lines[$l] = "" };
615 $lines[$l] .= $words[$w] . " ";
616 if ($words[$w] eq "\x28")
617 { $l++ ; $lines[$l] = " " x
$tabs ;};
618 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
619 { $l++ ; $lines[$l] = " " x
$tabs ;};
620 if ($words[$w] eq "\x7b")
621 { $l++ ; $lines[$l] = " " x
$tabs ;};
622 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
623 { $l++ ; $lines[$l] = " " x
$tabs ;};
624 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
625 { $l++ ; $lines[$l] = " " x
$tabs ;}
626 if ($words[$w-1] eq "option")
627 { $l++ ; $lines[$l] = " " x
$tabs ;}
629 my $start = $#lines - 4;
630 if ($start < 0) { $start = 0 } ;
631 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
632 for $l ( $start .. $#lines)
633 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
634 print STDERR
"<--\n";
638 # print a warning message about code from an input file
640 print STDERR
"Warning in $script->{filename} line $script->{line}: "
646 return $name if $option{test
};
647 for my $path ('/sbin', split ':', $ENV{PATH
}) {
648 my $ret = "$path/$name";
649 return $ret if -x
$ret;
651 die "$name not found in PATH\n";
654 sub initialize_domain
{
657 return if exists $domains{$domain}{initialized
};
659 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
661 my @tools = qw(tables);
662 push @tools, qw(tables-save tables-restore)
663 if $domain =~ /^ip6?$/;
665 # determine the location of this domain's tools
666 foreach my $tool (@tools) {
667 $domains{$domain}{tools
}{$tool} = find_tool
("${domain}${tool}");
670 # make tables-save tell us about the state of this domain
671 # (which tables and chains do exist?), also remember the old
672 # save data which may be used later by the rollback function
674 if (!$option{test
} &&
675 exists $domains{$domain}{tools
}{'tables-save'} &&
676 open(SAVE
, "$domains{$domain}{tools}{'tables-save'}|")) {
685 $table_info = $domains{$domain}{tables
}{$table} ||= {};
686 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
688 $table_info->{chains
}{$1}{builtin
} = 1;
689 $table_info->{has_builtin
} = 1;
694 $domains{$domain}{previous
} = $save;
697 $domains{$domain}{initialized
} = 1;
700 # split the an input string into words and delete comments
701 sub tokenize_string
($) {
706 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
707 last if $word eq '#';
714 # shift an array; helper function to be passed to &getvar / &getvalues
715 sub next_array_token
{
720 # read some more tokens from the input file into a buffer
721 sub prepare_tokens
() {
722 my $tokens = $script->{tokens
};
723 while (@
$tokens == 0) {
724 my $handle = $script->{handle
};
725 my $line = <$handle>;
726 return unless defined $line;
730 # the next parser stage eats this
731 push @
$tokens, @
{tokenize_string
($line)};
737 # open a ferm sub script
739 my $filename = shift;
741 for (my $s = $script; defined $s; $s = $s->{parent
}) {
742 mydie
("Circular reference in $script->{filename} line $script->{line}: $filename")
743 if $s->{filename
} eq $filename;
747 open FILE
, "<$filename"
748 or mydie
("Failed to open $filename: $!");
751 $script = { filename
=> $filename,
762 # collect script filenames which are being included
763 sub collect_filenames
(@
) {
766 # determine the current script's parent directory for relative
768 die unless defined $script;
769 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
772 foreach my $pathname (@_) {
773 # non-absolute file names are relative to the parent script's
775 $pathname = $parent_dir . $pathname
776 unless $pathname =~ m
,^/,;
778 if ($pathname =~ m
,/$,) {
779 # include all regular files in a directory
781 error
("'$pathname' is not a directory")
785 opendir DIR
, $pathname
786 or error
("Failed to open directory '$pathname': $!");
787 my @names = readdir DIR
;
790 # sort those names for a well-defined order
791 foreach my $name (sort { $a cmp $b } @names) {
792 # don't include hidden and backup files
795 my $filename = $pathname . $name;
799 } elsif ($pathname =~ m
,\
|$,) {
800 # run a program and use its output
801 push @ret, $pathname;
802 } elsif ($pathname =~ m
,^\
|,) {
803 error
('This kind of pipe is not allowed');
805 # include a regular file
807 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
809 error
("'$pathname' is not a file")
812 push @ret, $pathname;
819 # peek a token from the queue, but don't remove it
821 return unless prepare_tokens
();
822 return $script->{tokens
}[0];
825 # get a token from the queue
827 return unless prepare_tokens
();
828 my $token = shift @
{$script->{tokens
}};
830 # update $script->{past_tokens}
831 my $past_tokens = $script->{past_tokens
};
833 if (@
$past_tokens > 0) {
834 my $prev_token = $past_tokens->[-1][-1];
835 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
836 if $prev_token eq ';';
838 if $prev_token eq '}';
841 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
842 push @
{$past_tokens->[-1]}, $token;
848 sub expect_token
($;$) {
851 my $token = next_token
();
852 error
($msg || "'$expect' expected")
853 unless defined $token and $token eq $expect;
856 # require that another token exists, and that it's not a "special"
857 # token, e.g. ";" and "{"
858 sub require_next_token
{
859 my $code = shift || \
&next_token
;
861 my $token = &$code(@_);
863 error
('unexpected end of file')
864 unless defined $token;
866 error
("'$token' not allowed here")
867 if $token =~ /^[;{}]$/;
872 # return the value of a variable
873 sub variable_value
($) {
877 return $_->{vars
}{$name}
878 if exists $_->{vars
}{$name};
881 return $stack[0]{auto
}{$name}
882 if exists $stack[0]{auto
}{$name};
887 # determine the value of a variable, die if the value is an array
888 sub string_variable_value
($) {
890 my $value = variable_value
($name);
892 error
("variable '$name' must be a string, is an array")
898 # similar to the built-in "join" function, but also handle negated
899 # values in a special way
901 my ($expr, $value) = @_;
903 unless (ref $value) {
905 } elsif (ref $value eq 'ARRAY') {
906 return join($expr, @
$value);
907 } elsif (ref $value eq 'negated') {
908 # bless'negated' is a special marker for negated values
909 $value = join_value
($expr, $value->[0]);
910 return bless [ $value ], 'negated';
916 # returns the next parameter, which may either be a scalar or an array
918 my ($code, $param) = (shift, shift);
921 my $token = require_next_token
($code, $param);
924 # read an array until ")"
928 $token = getvalues
($code, $param,
929 parenthesis_allowed
=> 1,
932 unless (ref $token) {
933 last if $token eq ')';
936 error
('Comma is not allowed within arrays, please use only a space');
940 push @wordlist, $token;
941 } elsif (ref $token eq 'ARRAY') {
942 push @wordlist, @
$token;
944 error
('unknown toke type');
948 error
('empty array not allowed here')
949 unless @wordlist or not $options{non_empty
};
951 return @wordlist == 1
954 } elsif ($token =~ /^\`(.*)\`$/s) {
955 # execute a shell command, insert output
957 my $output = `$command`;
960 error
("failed to execute: $!");
961 } elsif ($?
& 0x7f) {
962 error
("child died with signal " . ($?
& 0x7f));
964 error
("child exited with status " . ($?
>> 8));
969 $output =~ s/#.*//mg;
972 my @tokens = grep { length } split /\s+/s, $output;
976 my $value = getvalues
(\
&next_array_token
, \
@tokens);
977 push @values, to_array
($value);
984 } elsif ($token =~ /^\'(.*)\'$/s) {
985 # single quotes: a string
987 } elsif ($token =~ /^\"(.*)\"$/s) {
988 # double quotes: a string with escapes
990 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
992 } elsif ($token eq '!') {
993 error
('negation is not allowed here')
994 unless $options{allow_negation
};
996 $token = getvalues
($code, $param);
998 error
('it is not possible to negate an array')
999 if ref $token and not $options{allow_array_negation
};
1001 return bless [ $token ], 'negated';
1002 } elsif ($token eq ',') {
1004 if $options{comma_allowed
};
1006 error
('comma is not allowed here');
1007 } elsif ($token eq '=') {
1008 error
('equals operator ("=") is not allowed here');
1009 } elsif ($token eq '$') {
1010 my $name = require_next_token
($code, $param);
1011 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1012 unless $name =~ /^\w+$/;
1014 my $value = variable_value
($name);
1016 error
("no such variable: \$$name")
1017 unless defined $value;
1020 } elsif ($token eq '&') {
1021 error
("function calls are not allowed as keyword parameter");
1022 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1023 error
('Syntax error');
1024 } elsif ($token =~ /^@/) {
1025 if ($token eq '@resolve') {
1026 my @params = get_function_params
();
1027 error
('Usage: @resolve((hostname ...))')
1028 unless @params == 1;
1029 eval { require Net
::DNS
; };
1030 error
('For the @resolve() function, you need the Perl library Net::DNS')
1033 my $resolver = new Net
::DNS
::Resolver
;
1035 foreach my $hostname (to_array
($params[0])) {
1036 my $query = $resolver->search($hostname, $type);
1037 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
1039 foreach my $rr ($query->answer) {
1040 next unless $rr->type eq $type;
1041 push @result, $rr->address;
1046 error
("unknown ferm built-in function");
1053 # returns the next parameter, but only allow a scalar
1055 my $token = getvalues
(@_);
1057 error
('array not allowed here')
1058 if ref $token and ref $token eq 'ARRAY';
1063 sub get_function_params
(%) {
1064 expect_token
('(', 'function name must be followed by "()"');
1066 my $token = peek_token
();
1067 if ($token eq ')') {
1076 $token = require_next_token
();
1080 error
('"," expected')
1081 unless $token eq ',';
1084 push @params, getvalues
(undef, undef, @_);
1090 # collect all tokens in a flat array reference until the end of the
1091 # command is reached
1092 sub collect_tokens
() {
1097 my $keyword = next_token
();
1098 error
('unexpected end of file within function/variable declaration')
1099 unless defined $keyword;
1101 if ($keyword =~ /^[\{\(]$/) {
1102 push @level, $keyword;
1103 } elsif ($keyword =~ /^[\}\)]$/) {
1104 my $expected = $keyword;
1105 $expected =~ tr/\}\)/\{\(/;
1106 my $opener = pop @level;
1107 error
("unmatched '$keyword'")
1108 unless defined $opener and $opener eq $expected;
1109 } elsif ($keyword eq ';' and @level == 0) {
1113 push @tokens, $keyword;
1116 if $keyword eq '}' and @level == 0;
1123 # returns the specified value as an array. dereference arrayrefs
1126 die unless wantarray;
1128 unless (ref $value) {
1130 } elsif (ref $value eq 'ARRAY') {
1137 # evaluate the specified value as bool
1142 unless (ref $value) {
1144 } elsif (ref $value eq 'ARRAY') {
1151 sub is_netfilter_core_target
($) {
1153 die unless defined $target and length $target;
1155 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1158 sub is_netfilter_module_target
($$) {
1159 my ($domain_family, $target) = @_;
1160 die unless defined $target and length $target;
1162 return defined $domain_family &&
1163 exists $target_defs{$domain_family} &&
1164 exists $target_defs{$domain_family}{$target};
1167 sub is_netfilter_builtin_chain
($$) {
1168 my ($table, $chain) = @_;
1170 return grep { $_ eq $chain }
1171 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1174 sub netfilter_canonical_protocol
($) {
1177 if $proto eq 'ipv6-icmp';
1179 if $proto eq 'ipv6-mh';
1183 sub netfilter_protocol_module
($) {
1185 return unless defined $proto;
1187 if $proto eq 'icmpv6';
1191 # escape the string in a way safe for the shell
1192 sub shell_escape
($) {
1195 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1197 if ($option{fast
}) {
1198 # iptables-save/iptables-restore are quite buggy concerning
1199 # escaping and special characters... we're trying our best
1203 $token = '"' . $token . '"'
1204 if $token =~ /[\s\'\\;&]/s;
1207 if $token =~ /^\`.*\`$/;
1208 $token =~ s/'/\\'/g;
1209 $token = '\'' . $token . '\''
1210 if $token =~ /[\s\"\\;<>&|]/s;
1216 # append an option to the shell command line, using information from
1217 # the module definition (see %match_defs etc.)
1218 sub shell_append_option($$$) {
1219 my ($ref, $keyword, $value) = @_;
1222 if (ref $value eq 'negated') {
1223 $value = $value->[0];
1225 } elsif (ref $value eq 'pre_negated') {
1226 $value = $value->[0];
1231 unless (defined $value) {
1232 $$ref .= " --$keyword";
1233 } elsif (ref $value) {
1234 if (ref $value eq 'params') {
1235 $$ref .= " --$keyword ";
1236 $$ref .= join(' ', map { shell_escape($_) } @$value);
1237 } elsif (ref $value eq 'multi') {
1239 $$ref .= " --$keyword " . shell_escape($_);
1245 $$ref .= " --$keyword " . shell_escape($value);
1249 # convert an internal rule structure into an iptables call
1253 my $domain = $rule->{domain};
1254 my $domain_info = $domains{$domain};
1255 $domain_info->{enabled} = 1;
1256 my $domain_family = $rule->{domain_family};
1258 my $table = $rule->{table};
1259 my $table_info = $domain_info->{tables}{$table} ||= {};
1261 my $chain = $rule->{chain};
1262 my $chain_info = $table_info->{chains}{$chain} ||= {};
1263 my $chain_rules = $chain_info->{rules} ||= [];
1265 return if $option{flush};
1267 my $action = $rule->{action};
1269 # mark this chain as "non
-empty
" because we will add stuff to
1270 # it now; this flag is later used to check if a custom chain
1271 # referenced by "jump
" was actually defined
1272 $chain_info->{non_empty} = 1;
1274 # return if this is a declaration-only rule
1276 unless $rule->{has_rule};
1280 # general iptables options
1282 while (my ($keyword, $value) = each %{$rule->{builtin}}) {
1283 shell_append_option(\$rr, $keyword, $value);
1287 # match module options
1292 if (defined $rule->{builtin}{protocol}) {
1293 my $proto = $rule->{builtin}{protocol};
1295 # special case: --dport and --sport for TCP/UDP
1296 if ($domain_family eq 'ip' and
1297 (exists $rule->{dport} or exists $rule->{sport}) and
1298 $proto =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
1299 unless (exists $modules{$proto}) {
1300 $rr .= " -m
$proto";
1301 $modules{$proto} = 1;
1304 shell_append_option(\$rr, 'dport', $rule->{dport})
1305 if exists $rule->{dport};
1306 shell_append_option(\$rr, 'sport', $rule->{sport})
1307 if exists $rule->{sport};
1311 # modules stored in %match_defs
1313 foreach my $match (@{$rule->{match}}) {
1314 my $module_name = $match->{name};
1315 unless (exists $modules{$module_name}) {
1316 $rr .= " -m
$module_name";
1317 $modules{$module_name} = 1;
1320 while (my ($keyword, $value) = each %{$match->{options}}) {
1321 shell_append_option(\$rr, $keyword, $value);
1329 if ($action->{type} eq 'jump') {
1330 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1331 $rr .= " -j
" . $action->{chain};
1332 } elsif ($action->{type} eq 'goto') {
1333 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1334 $rr .= " -g
" . $action->{chain};
1335 } elsif ($action->{type} eq 'target') {
1336 $rr .= " -j
" . $action->{target};
1338 # targets stored in %target_defs
1340 while (my ($keyword, $value) = each %{$rule->{target_options}}) {
1341 shell_append_option(\$rr, $keyword, $value);
1343 } elsif ($action->{type} ne 'nop') {
1348 push @$chain_rules, { rule => $rr,
1349 script => $rule->{script},
1353 sub transform_rule($) {
1356 $rule->{builtin}{protocol} = 'icmpv6'
1357 if $rule->{domain} eq 'ip6' and $rule->{builtin}{protocol} eq 'icmp';
1363 transform_rule($rule);
1365 # prints all rules in a hash
1370 sub check_unfold(\@$$) {
1371 my ($unfold, $parent, $key) = @_;
1373 return unless ref $parent->{$key} and
1374 ref $parent->{$key} eq 'ARRAY';
1376 push @$unfold, $parent, $key, $parent->{$key};
1379 # convert a bunch of internal rule structures in iptables calls,
1380 # unfold arrays during that
1382 # compile the list hashes into rules
1387 foreach my $key (qw(domain table chain)) {
1388 check_unfold
(@unfold, $fw, $key);
1391 foreach my $key (keys %{$fw->{builtin
}}) {
1392 check_unfold
(@unfold, $fw->{builtin
}, $key);
1395 foreach my $match (@
{$fw->{match
}}) {
1396 while (my ($key, $value) = each %{$match->{options
}}) {
1397 check_unfold
(@unfold, $match->{options
}, $key);
1401 check_unfold
(@unfold, $fw, 'sport');
1402 check_unfold
(@unfold, $fw, 'dport');
1411 my ($parent, $key, $values) = (shift, shift, shift);
1413 foreach my $value (@
$values) {
1414 $parent->{$key} = $value;
1427 sub filter_domains
($) {
1428 my $domains = shift;
1431 foreach my $domain (to_array
$domains) {
1432 next if exists $option{domain
}
1433 and $domain ne $option{domain
};
1436 initialize_domain
($domain);
1440 push @
$result, $domain;
1443 return @
$result == 1 ?
$result->[0] : $result;
1446 # parse a keyword from a module definition
1447 sub parse_keyword
($$$$) {
1448 my ($current, $def, $keyword, $negated_ref) = @_;
1450 my $params = $def->{params
};
1455 if ($$negated_ref && exists $def->{pre_negation
}) {
1457 undef $$negated_ref;
1460 unless (defined $params) {
1462 } elsif (ref $params && ref $params eq 'CODE') {
1463 $value = &$params($current);
1464 } elsif ($params eq 'm') {
1465 $value = bless [ to_array getvalues
() ], 'multi';
1466 } elsif ($params =~ /^[a-z]/) {
1467 if (exists $def->{negation
} and not $negated) {
1468 my $token = peek_token
();
1469 if ($token eq '!') {
1476 foreach my $p (split(//, $params)) {
1478 push @params, getvar
();
1479 } elsif ($p eq 'c') {
1480 my @v = to_array getvalues
(undef, undef,
1482 push @params, join(',', @v);
1488 $value = @params == 1
1490 : bless \
@params, 'params';
1491 } elsif ($params == 1) {
1492 if (exists $def->{negation
} and not $negated) {
1493 my $token = peek_token
();
1494 if ($token eq '!') {
1500 $value = getvalues
();
1502 warning
("log-prefix is too long; truncating to 29 characters: '$1'")
1503 if $keyword eq 'log-prefix' && $value =~ s
,^(.{29}).+$,$1,;
1505 if (exists $def->{negation
} and not $negated) {
1506 my $token = peek_token
();
1507 if ($token eq '!') {
1513 $value = bless [ map {
1515 } (1..$params) ], 'params';
1518 $value = bless [ $value ], exists $def->{pre_negation
} ?
'pre_negated' : 'negated'
1524 # parse options of a module
1525 sub parse_option
($$$$$) {
1526 my ($def, $current, $store, $keyword, $negated_ref) = @_;
1528 while (exists $def->{alias
}) {
1529 ($keyword, $def) = @
{$def->{alias
}};
1530 die unless defined $def;
1534 = parse_keyword
($current, $def,
1535 $keyword, $negated_ref);
1536 $current->{has_rule
} = 1;
1540 # parse options for a protocol module definition
1541 sub parse_protocol_options
($$$$) {
1542 my ($current, $proto, $keyword, $negated_ref) = @_;
1544 my $domain_family = $current->{'domain_family'};
1545 my $proto_defs = $proto_defs{$domain_family};
1546 return unless defined $proto_defs;
1548 my $proto_def = $proto_defs->{$proto};
1549 return unless defined $proto_def and
1550 exists $proto_def->{keywords
}{$keyword};
1552 my $module_name = $proto eq 'icmpv6' ?
'icmp6' : $proto;
1553 my $module = { name
=> $module_name,
1557 push @
{$current->{match
}}, $module;
1559 return parse_option
($proto_def->{keywords
}{$keyword},
1560 $current, $module->{options
},
1561 $keyword, $negated_ref);
1564 sub copy_on_write
($$) {
1565 my ($rule, $key) = @_;
1566 return unless exists $rule->{cow
}{$key};
1567 $rule->{$key} = {%{$rule->{$key}}};
1568 delete $rule->{cow
}{$key};
1571 sub clone_match
($) {
1573 return { name
=> $match->{name
},
1574 options
=> { %{$match->{options
}} },
1575 defs
=> $match->{defs
},
1579 sub new_level
(\
%$) {
1580 my ($current, $prev) = @_;
1583 if (defined $prev) {
1584 # copy data from previous level
1585 $current->{cow
} = { keywords
=> 1, };
1586 $current->{keywords
} = $prev->{keywords
};
1587 $current->{builtin
} = { %{$prev->{builtin
}} };
1588 $current->{match
} = [ map { clone_match
($_) } @
{$prev->{match
}} ];
1589 $current->{action
} = { %{$prev->{action
}} };
1590 foreach my $key (qw(domain domain_family table chain sport dport)) {
1591 $current->{$key} = $prev->{$key}
1592 if exists $prev->{$key};
1595 $current->{cow
} = {};
1596 $current->{keywords
} = {};
1597 $current->{builtin
} = {};
1598 $current->{match
} = [];
1599 $current->{action
} = {};
1603 sub rule_defined
(\
%) {
1605 return defined($rule->{domain
}) or
1606 keys(%{$rule->{builtin
}}) > 0 or
1607 keys(%{$rule->{match
}}) > 0 or
1608 keys(%{$rule->{action
}}) > 0;
1611 # the main parser loop: read tokens, convert them into internal rule
1614 my $lev = shift; # current recursion depth
1615 my $prev = shift; # previous rule hash
1617 # enter is the core of the firewall setup, it is a
1618 # simple parser program that recognizes keywords and
1619 # retreives parameters to set up the kernel routing
1622 my $base_level = $script->{base_level
} || 0;
1623 die if $base_level > $lev;
1626 new_level
(%current, $prev);
1628 # read keywords 1 by 1 and dump into parser
1629 while (defined (my $keyword = next_token
())) {
1630 # check if the current rule should be negated
1631 my $negated = $keyword eq '!';
1633 # negation. get the next word which contains the 'real'
1635 $keyword = getvar
();
1637 error
('unexpected end of file after negation')
1638 unless defined $keyword;
1641 # the core: parse all data
1644 # deprecated keyword?
1645 if (exists $deprecated_keywords{$keyword}) {
1646 my $new_keyword = $deprecated_keywords{$keyword};
1647 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1648 $keyword = $new_keyword;
1651 # effectuation operator
1652 if ($keyword eq ';') {
1653 if ($current{has_rule
} and not $current{action
}{type
}) {
1654 # something is wrong when a rule was specifiedd,
1656 error
('No action defined; did you mean "NOP"?');
1659 error
('No chain defined') unless defined $current{chain
};
1661 $current{script
} = { filename
=> $script->{filename
},
1662 line
=> $script->{line
},
1667 # and clean up variables set in this level
1668 new_level
(%current, $prev);
1673 # conditional expression
1674 if ($keyword eq '@if') {
1675 unless (eval_bool
(getvalues
)) {
1677 my $token = peek_token
();
1678 require_next_token
() if $token and $token eq '@else';
1684 if ($keyword eq '@else') {
1685 # hack: if this "else" has not been eaten by the "if"
1686 # handler above, we believe it came from an if clause
1687 # which evaluated "true" - remove the "else" part now.
1692 # hooks for custom shell commands
1693 if ($keyword eq 'hook') {
1694 error
('"hook" must be the first token in a command')
1695 if rule_defined
(%current);
1697 my $position = getvar
();
1699 if ($position eq 'pre') {
1700 $hooks = \
@pre_hooks;
1701 } elsif ($position eq 'post') {
1702 $hooks = \
@post_hooks;
1704 error
("Invalid hook position: '$position'");
1707 push @
$hooks, getvar
();
1713 # recursing operators
1714 if ($keyword eq '{') {
1716 my $old_stack_depth = @stack;
1718 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1721 enter
($lev + 1, \
%current);
1725 die unless @stack == $old_stack_depth;
1727 # after a block, the command is finished, clear this
1729 new_level
(%current, $prev);
1734 if ($keyword eq '}') {
1735 error
('Unmatched "}"')
1736 if $lev <= $base_level;
1738 # consistency check: check if they havn't forgotten
1739 # the ';' before the last statement
1740 error
('Missing semicolon before "}"')
1741 if $current{has_rule
};
1747 # include another file
1748 if ($keyword eq '@include' or $keyword eq 'include') {
1749 my @files = collect_filenames to_array getvalues
;
1750 $keyword = next_token
;
1751 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1752 unless defined $keyword and $keyword eq ';';
1754 foreach my $filename (@files) {
1755 # save old script, open new script
1756 my $old_script = $script;
1757 open_script
($filename);
1758 $script->{base_level
} = $lev + 1;
1761 my $old_stack_depth = @stack;
1766 # include files may set variables for their parent
1767 $stack->{vars
} = ($stack[0]{vars
} ||= {});
1768 $stack->{functions
} = ($stack[0]{functions
} ||= {});
1769 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
1772 unshift @stack, $stack;
1775 enter
($lev + 1, \
%current);
1779 die unless @stack == $old_stack_depth;
1781 # restore old script
1782 $script = $old_script;
1788 # definition of a variable or function
1789 if ($keyword eq '@def' or $keyword eq 'def') {
1790 error
('"def" must be the first token in a command')
1791 if $current{has_rule
};
1793 my $type = require_next_token
();
1795 my $name = require_next_token
();
1796 error
('invalid variable name')
1797 unless $name =~ /^\w+$/;
1801 my $value = getvalues
(undef, undef, allow_negation
=> 1);
1805 $stack[0]{vars
}{$name} = $value
1806 unless exists $stack[-1]{vars
}{$name};
1807 } elsif ($type eq '&') {
1808 my $name = require_next_token
();
1809 error
('invalid function name')
1810 unless $name =~ /^\w+$/;
1812 expect_token
('(', 'function parameter list or "()" expected');
1816 my $token = require_next_token
();
1817 last if $token eq ')';
1820 error
('"," expected')
1821 unless $token eq ',';
1823 $token = require_next_token
();
1826 error
('"$" and parameter name expected')
1827 unless $token eq '$';
1829 $token = require_next_token
();
1830 error
('invalid function parameter name')
1831 unless $token =~ /^\w+$/;
1833 push @params, $token;
1838 $function{params
} = \
@params;
1842 my $tokens = collect_tokens
();
1843 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
1844 $function{tokens
} = $tokens;
1846 $stack[0]{functions
}{$name} = \
%function
1847 unless exists $stack[-1]{functions
}{$name};
1849 error
('"$" (variable) or "&" (function) expected');
1856 if ($keyword eq '$') {
1857 error
('variable references are only allowed as keyword parameter');
1860 if ($keyword eq '&') {
1861 my $name = require_next_token
;
1862 error
('function name expected')
1863 unless $name =~ /^\w+$/;
1867 $function = $_->{functions
}{$name};
1868 last if defined $function;
1870 error
("no such function: \&$name")
1871 unless defined $function;
1873 my $paramdef = $function->{params
};
1874 die unless defined $paramdef;
1876 my @params = get_function_params
(allow_negation
=> 1);
1878 error
("Wrong number of parameters for function '\&$name': "
1879 . @
$paramdef . " expected, " . @params . " given")
1880 unless @params == @
$paramdef;
1883 for (my $i = 0; $i < @params; $i++) {
1884 $vars{$paramdef->[$i]} = $params[$i];
1887 if ($function->{block
}) {
1888 # block {} always ends the current rule, so if the
1889 # function contains a block, we have to require
1890 # the calling rule also ends here
1894 my @tokens = @
{$function->{tokens
}};
1895 for (my $i = 0; $i < @tokens; $i++) {
1896 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1897 exists $vars{$tokens[$i + 1]}) {
1898 my @value = to_array
($vars{$tokens[$i + 1]});
1899 @value = ('(', @value, ')')
1900 unless @tokens == 1;
1901 splice(@tokens, $i, 2, @value);
1903 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
1904 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
1908 unshift @
{$script->{tokens
}}, @tokens;
1913 # where to put the rule?
1914 if ($keyword eq 'domain') {
1915 error
('Domain is already specified')
1916 if exists $current{domain
};
1918 my $domain = getvalues
();
1919 my $filtered_domain = filter_domains
($domain);
1921 unless (ref $domain) {
1922 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1923 } elsif (@
$domain == 0) {
1924 $domain_family = 'none';
1925 } elsif (grep { not /^ip6?$/s } @
$domain) {
1926 error
('Cannot combine non-IP domains');
1928 $domain_family = 'ip';
1930 $current{domain_family
} = $domain_family;
1931 $current{keywords
} = get_builtin_keywords
($domain_family);
1932 delete $current{cow
}{keywords
};
1934 $current{domain
} = $stack[0]{auto
}{DOMAIN
} = $filtered_domain;
1939 if ($keyword eq 'table') {
1940 error
('Table is already specified')
1941 if exists $current{table
};
1942 $current{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
1944 unless (exists $current{domain
}) {
1945 $current{domain
} = filter_domains
('ip');
1946 $current{domain_family
} = 'ip';
1947 $current{keywords
} = get_builtin_keywords
('ip');
1948 delete $current{cow
}{keywords
};
1954 if ($keyword eq 'chain') {
1955 error
('Chain is already specified')
1956 if exists $current{chain
};
1957 $current{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
1959 # ferm 1.1 allowed lower case built-in chain names
1960 foreach (ref $current{chain
} ? @
{$current{chain
}} : $current{chain
}) {
1961 error
('Please write built-in chain names in upper case')
1962 if /^(?:input|forward|output|prerouting|postrouting)$/;
1965 unless (exists $current{domain
}) {
1966 $current{domain
} = filter_domains
('ip');
1967 $current{domain_family
} = 'ip';
1968 $current{keywords
} = get_builtin_keywords
('ip');
1969 delete $current{cow
}{keywords
};
1972 $current{table
} = 'filter'
1973 unless exists $current{table
};
1978 error
('Chain must be specified')
1979 unless exists $current{chain
};
1981 # policy for built-in chain
1982 if ($keyword eq 'policy') {
1983 error
('Cannot specify matches for policy')
1984 if $current{has_rule
};
1986 my $policy = getvar
();
1987 error
("Invalid policy target: $policy")
1988 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1992 foreach my $domain (to_array
$current{domain
}) {
1993 foreach my $table (to_array
$current{table
}) {
1994 foreach my $chain (to_array
$current{chain
}) {
1995 $domains{$domain}{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
2000 new_level
(%current, $prev);
2005 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2006 error
('No rule specified before "@subchain"')
2007 unless $current{has_rule
};
2010 $keyword = next_token
();
2012 if ($keyword =~ /^(["'])(.*)\1$/s) {
2014 $keyword = next_token
();
2016 $subchain = 'ferm_auto_' . ++$auto_chain;
2019 error
('"{" or chain name expected after "sub"')
2020 unless $keyword eq '{';
2022 # create a deep copy of %current, only containing values
2023 # which must be in the subchain
2024 my %inner = ( cow
=> { keywords
=> 1, },
2025 keywords
=> $current{keywords
},
2029 $inner{domain
} = $current{domain
};
2030 $inner{domain_family
} = $current{domain_family
};
2031 $inner{table
} = $current{table
};
2032 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2033 $inner{builtin
}{protocol
} = $current{builtin
}{protocol
}
2034 if exists $current{builtin
}{protocol
};
2039 # now handle the parent - it's a jump to the sub chain
2040 $current{action
} = { type
=> 'jump',
2044 $current{script
} = { filename
=> $script->{filename
},
2045 line
=> $script->{line
},
2050 # and clean up variables set in this level
2051 new_level
(%current, $prev);
2056 # everything else must be part of a "real" rule, not just
2058 $current{has_rule
}++;
2060 # extended parameters:
2061 if ($keyword =~ /^mod(?:ule)?$/) {
2062 foreach my $module (to_array getvalues
) {
2063 next if grep { $_->{name
} eq $module } @
{$current{match
}};
2065 my $domain_family = $current{domain_family
};
2066 my $defs = $match_defs{$domain_family}{$module};
2067 if (not defined $defs and exists $current{builtin
}{protocol
}) {
2068 my $proto = $current{builtin
}{protocol
};
2069 unless (ref $proto) {
2070 $proto = netfilter_canonical_protocol
($current{builtin
}{protocol
});
2071 $defs = $proto_defs{$domain_family}{$proto}
2072 if netfilter_protocol_module
($proto) eq $module;
2076 push @
{$current{match
}}, { name
=> $module,
2081 if (defined $defs) {
2082 copy_on_write
(\
%current, 'keywords');
2083 while (my ($k, $def) = each %{$defs->{keywords
}}) {
2084 $current{keywords
}{$k} = [ 'match', $module, $def ];
2092 # keywords from $current{keywords}
2094 if (exists $current{keywords
}{$keyword}) {
2095 my ($type, $module, $def) = @
{$current{keywords
}{$keyword}};
2097 if ($type eq 'builtin') {
2098 $store = $current{builtin
};
2099 } elsif ($type eq 'match') {
2100 $store = (grep { $_->{name
} eq $module } @
{$current{match
}})[-1]->{options
};
2101 } elsif ($type eq 'target') {
2102 $store = $current{target_options
} ||= {};
2107 parse_option
($def, \
%current, $store, $keyword, \
$negated);
2116 if ($keyword eq 'jump') {
2117 error
('There can only one action per rule')
2118 if defined $current{action
}{type
};
2119 my $chain = getvar
();
2120 if (is_netfilter_core_target
($chain) or
2121 is_netfilter_module_target
($current{domain_family
}, $chain)) {
2122 my $defs = $target_defs{$current{domain_family
}} &&
2123 $target_defs{$current{domain_family
}}{$chain};
2124 $current{action
} = { type
=> 'target',
2129 if (defined $defs) {
2130 copy_on_write
(\
%current, 'keywords');
2131 while (my ($k, $def) = each %{$defs->{keywords
}}) {
2132 $current{keywords
}{$k} = [ 'target', $keyword, $def ];
2136 $current{action
} = { type
=> 'jump',
2144 if ($keyword eq 'realgoto') {
2145 error
('There can only one action per rule')
2146 if defined $current{action
}{type
};
2147 $current{action
} = { type
=> 'goto',
2154 if (is_netfilter_core_target
($keyword)) {
2155 error
('There can only one action per rule')
2156 if defined $current{action
}{type
};
2157 $current{action
} = { type
=> 'target',
2163 if ($keyword eq 'NOP') {
2164 error
('There can only one action per rule')
2165 if defined $current{action
}{type
};
2166 $current{action
} = { type
=> 'nop',
2171 if (is_netfilter_module_target
($current{domain_family
}, $keyword)) {
2172 error
('There can only one action per rule')
2173 if defined $current{action
}{type
};
2175 if ($keyword eq 'TCPMSS') {
2176 my $protos = $current{builtin
}{protocol
};
2177 error
('No protocol specified before TCPMSS')
2178 unless defined $protos;
2179 foreach my $proto (to_array
$protos) {
2180 error
('TCPMSS not available for protocol "$proto"')
2181 unless $proto eq 'tcp';
2185 my $defs = $target_defs{$current{domain_family
}}{$keyword};
2187 $current{action
} = { type
=> 'target',
2192 if (defined $defs) {
2193 copy_on_write
(\
%current, 'keywords');
2194 while (my ($k, $def) = each %{$defs->{keywords
}}) {
2195 $current{keywords
}{$k} = [ 'target', $keyword, $def ];
2202 my $proto = $current{builtin
}{protocol
};
2205 # protocol specific options
2208 if (defined $proto and not ref $proto) {
2209 $proto = netfilter_canonical_protocol
($proto);
2211 if ($proto eq 'icmp') {
2212 my $domains = $current{domain
};
2213 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2216 parse_protocol_options
(\
%current, $proto, $keyword, \
$negated)
2221 if ($keyword =~ /^[sd]port$/) {
2222 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2223 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2225 $current{$keyword} = getvalues
(undef, undef,
2226 allow_negation
=> 1);
2231 error
("Unrecognized keyword: $keyword");
2234 # if the rule didn't reset the negated flag, it's not
2236 error
("Doesn't support negation: $keyword")
2240 error
('Missing "}" at end of file')
2241 if $lev > $base_level;
2243 # consistency check: check if they havn't forgotten
2244 # the ';' before the last statement
2245 error
("Missing semicolon before end of file")
2246 if $current{has_rule
}; # XXX
2250 while (my ($domain_name, $domain) = each %domains) {
2251 while (my ($table_name, $table_info) = each %{$domain->{tables
}}) {
2252 while (my ($chain_name, $chain) = each %{$table_info->{chains
}}) {
2253 warning
("chain $chain_name (domain $domain_name, table $table_name) was referenced, but not declared")
2254 if $chain->{was_created
} and not $chain->{non_empty
};
2260 sub execute_command
{
2261 my ($command, $script) = @_;
2263 print LINES
"$command\n"
2265 return if $option{noexec
};
2267 my $ret = system($_);
2268 unless ($ret == 0) {
2270 print STDERR
"failed to execute: $!\n";
2272 } elsif ($?
& 0x7f) {
2273 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2276 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2285 sub execute_slow
($$) {
2286 my ($domain, $domain_info) = @_;
2288 my $domain_cmd = $domain_info->{tools
}{tables
};
2290 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2291 my $table_cmd = "$domain_cmd -t $table";
2293 # reset chain policies
2294 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2295 next unless $chain_info->{builtin
} or
2296 (not $table_info->{has_builtin
} and
2297 is_netfilter_builtin_chain
($table, $chain));
2298 $status ||= execute_command
("$table_cmd -P $chain ACCEPT");
2302 $status ||= execute_command
("$table_cmd -F");
2303 $status ||= execute_command
("$table_cmd -X");
2305 next if $option{flush
};
2307 # create chains / set policy
2308 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2309 if (exists $chain_info->{policy
}) {
2310 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2311 unless $chain_info->{policy
} eq 'ACCEPT';
2312 } elsif (not is_netfilter_builtin_chain
($table, $chain)) {
2313 $status ||= execute_command
("$table_cmd -N $chain");
2318 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2319 my $chain_cmd = "$table_cmd -A $chain";
2320 foreach my $rule (@
{$chain_info->{rules
}}) {
2321 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2329 sub rules_to_save
($$) {
2330 my ($domain, $domain_info) = @_;
2332 # convert this into an iptables-save text
2333 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2335 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2337 $result .= '*' . $table . "\n";
2339 # create chains / set policy
2340 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2341 my $chain_info = $table_info->{chains
}{$chain};
2342 my $policy = $option{flush
} ?
'ACCEPT' : $chain_info->{policy
};
2343 unless (defined $policy) {
2344 if (is_netfilter_builtin_chain
($table, $chain)) {
2350 $result .= ":$chain $policy\ [0:0]\n";
2353 next if $option{flush
};
2356 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2357 my $chain_info = $table_info->{chains
}{$chain};
2358 foreach my $rule (@
{$chain_info->{rules
}}) {
2359 $result .= "-A $chain$rule->{rule}\n";
2364 $result .= "COMMIT\n";
2370 sub restore_domain
($$) {
2371 my ($domain, $save) = @_;
2373 my $path = $domains{$domain}{tools
}{'tables-restore'};
2376 open RESTORE
, "|$path"
2377 or die "Failed to run $path: $!\n";
2379 print RESTORE
$save;
2382 or die "Failed to run $path\n";
2385 sub execute_fast
($$) {
2386 my ($domain, $domain_info) = @_;
2388 my $save = rules_to_save
($domain, $domain_info);
2390 if ($option{lines
}) {
2391 print LINES
"$domain_info->{tools}{'tables-restore'} <<EOT\n"
2398 return if $option{noexec};
2401 restore_domain($domain, $save);
2413 while (my ($domain, $domain_info) = each %domains) {
2414 next unless $domain_info->{enabled};
2415 unless (defined $domain_info->{tools}{'tables-restore'}) {
2416 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2421 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2422 my $reset_chain = '';
2423 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2424 next unless is_netfilter_builtin_chain($table, $chain);
2425 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2427 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2428 if length $reset_chain;
2431 $reset .= $domain_info->{previous}
2432 if defined $domain_info->{previous};
2434 restore_domain($domain, $reset);
2437 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2442 # do nothing, just interrupt a system call
2445 sub confirm_rules() {
2446 $SIG{ALRM} = \&alrm_handler;
2451 . "ferm has applied the new firewall rules
.\n"
2452 . "Please type
'yes' to confirm
:\n";
2458 STDIN->sysread($line, 3);
2462 POSIX::tcflush(*STDIN, 2);
2464 print STDERR "$@
" if $@;
2466 $SIG{ALRM} = 'DEFAULT';
2468 return $line eq 'yes';
2477 ferm - a firewall rule parser for linux
2481 B<ferm> I<options> I<inputfiles>
2485 -n, --noexec Do not execute the rules, just simulate
2486 -F, --flush Flush all netfilter tables managed by ferm
2487 -l, --lines Show all rules that were created
2488 -i, --interactive Interactive mode: revert if user does not confirm
2489 --remote Remote mode; ignore host specific configuration.
2490 This implies --noexec and --lines.
2491 -V, --version Show current version number
2492 -h, --help Look at this text
2493 --fast Generate an iptables-save file, used by iptables-restore
2494 --shell Generate a shell script which calls iptables-restore
2495 --domain {ip|ip6} Handle only the specified domain
2496 --def '$name=v' Override a variable