4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2008 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 # - tables{$name}: ferm state information about tables
74 # - has_builtin: whether built-in chains have been determined in this table
75 # - chains{$chain}: ferm state information about the chains
76 # - builtin: whether this is a built-in chain
77 use vars qw(%domains);
80 use vars qw(%deprecated_keywords);
82 # keywords from ferm 1.1 which are deprecated, and the new one; these
83 # are automatically replaced, and a warning is printed
84 %deprecated_keywords = ( goto => 'jump',
87 # these hashes provide the Netfilter module definitions
88 use vars qw(%proto_defs %match_defs %target_defs);
91 # This subsubsystem allows you to support (most) new netfilter modules
92 # in ferm. Add a call to one of the "add_XY_def()" functions below.
94 # Ok, now about the cryptic syntax: the function "add_XY_def()"
95 # registers a new module. There are three kinds of modules: protocol
96 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
97 # target modules (e.g. DNAT, MARK).
99 # The first parameter is always the module name which is passed to
100 # iptables with "-p", "-m" or "-j" (depending on which kind of module
103 # After that, you add an encoded string for each option the module
104 # supports. This is where it becomes tricky.
106 # foo defaults to an option with one argument (which may be a ferm
109 # foo*0 option without any arguments
111 # foo=s one argument which must not be a ferm array ('s' stands for
114 # u32=m an array which renders into multiple iptables options in one
117 # ctstate=c one argument, if it's an array, pass it to iptables as a
118 # single comma separated value; example:
119 # ctstate (ESTABLISHED RELATED) translates to:
120 # --ctstate ESTABLISHED,RELATED
122 # foo=sac three arguments: scalar, array, comma separated; you may
123 # concatenate more than one letter code after the '='
125 # foo&bar one argument; call the perl function '&bar()' which parses
128 # !foo negation is allowed and the '!' is written before the keyword
130 # foo! same as above, but '!' is after the keyword and before the
133 # to:=to-destination makes "to" an alias for "to-destination"; you have
134 # to add a declaration for option "to-destination"
137 # add a module definition
140 my $domain_family = shift;
141 my $params_default = shift;
143 die if exists $defs->{$domain_family}{$name};
144 my $def = $defs->{$domain_family}{$name} = {};
149 my $params = $params_default;
150 $params = $1 if $keyword =~ s,\*(\d+)$,,;
151 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
152 if ($keyword =~ s,&(\S+)$,,) {
153 $params = eval "\\&$1";
156 $k->{params} = $params if $params;
158 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
159 $k->{negation} = 1 if $keyword =~ s,!$,,;
161 $k->{alias} = [$1, $def->{keywords}{$1} || die] if $keyword =~ s,:=(\S+)$,,;
163 $def->{keywords}{$keyword} = $k;
169 # add a protocol module definition
170 sub add_proto_def_x(@) {
171 my $domain_family = shift;
172 add_def_x(\%proto_defs, $domain_family, 1, @_);
175 # add a match module definition
176 sub add_match_def_x(@) {
177 my $domain_family = shift;
178 add_def_x(\%match_defs, $domain_family, 1, @_);
181 # add a target module definition
182 sub add_target_def_x(@) {
183 my $domain_family = shift;
184 add_def_x(\%target_defs, $domain_family, 's', @_);
189 add_def_x($defs, 'ip', @_);
192 # add a protocol module definition
193 sub add_proto_def(@) {
194 add_def(\%proto_defs, 1, @_);
197 # add a match module definition
198 sub add_match_def(@) {
199 add_def(\%match_defs, 1, @_);
202 # add a target module definition
203 sub add_target_def(@) {
204 add_def(\%target_defs, 's', @_);
207 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
208 add_proto_def
'mh', qw(mh-type!);
209 add_proto_def
'icmp', qw(icmp-type!);
210 add_proto_def
'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
211 add_proto_def
'sctp', qw(chunk-types!=sc);
212 add_proto_def
'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
213 add_proto_def
'udp', qw();
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
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
243 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
244 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
245 add_match_def
'iprange', qw(!src-range !dst-range);
246 add_match_def
'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
247 add_match_def
'ipv6header', qw(header!=c soft*0);
248 add_match_def
'length', qw(length!);
249 add_match_def
'limit', qw(limit=s limit-burst=s);
250 add_match_def
'mac', qw(mac-source!);
251 add_match_def
'mark', qw(mark);
252 add_match_def
'multiport', qw(source-ports!&multiport_params),
253 qw(destination-ports!&multiport_params ports!&multiport_params);
254 add_match_def
'nth', qw(every counter start packet);
255 add_match_def
'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
256 add_match_def
'physdev', qw(physdev-in! physdev-out!),
257 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
258 add_match_def
'pkttype', qw(pkt-type),
259 add_match_def
'policy',
260 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
261 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
262 qw(psd-lo-ports-weight psd-hi-ports-weight);
263 add_match_def
'quota', qw(quota=s);
264 add_match_def
'random', qw(average);
265 add_match_def
'realm', qw(realm!);
266 add_match_def
'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
267 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
268 add_match_def
'set', qw(set=sc);
269 add_match_def
'state', qw(state=c);
270 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
271 add_match_def
'string', qw(algo=s from=s to=s string hex-string);
272 add_match_def
'tcpmss', qw(!mss);
273 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
274 qw(!monthday=c !weekdays=c utc*0 localtz*0);
275 add_match_def
'tos', qw(!tos);
276 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
277 add_match_def
'u32', qw(!u32=m);
279 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
280 add_target_def
'CLASSIFY', qw(set-class);
281 add_target_def
'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
282 add_target_def
'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
283 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
284 add_target_def
'DNAT', qw(to-destination=m to:=to-destination random*0);
285 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
286 add_target_def
'ECN', qw(ecn-tcp-remove*0);
287 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
288 add_target_def
'IPV4OPTSSTRIP';
289 add_target_def
'LOG', qw(log-level log-prefix),
290 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
291 add_target_def
'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
292 add_target_def
'MASQUERADE', qw(to-ports random*0);
293 add_target_def
'MIRROR';
294 add_target_def
'NETMAP', qw(to);
295 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
296 add_target_def
'NFQUEUE', qw(queue-num);
297 add_target_def
'NOTRACK';
298 add_target_def
'REDIRECT', qw(to-ports random*0);
299 add_target_def
'REJECT', qw(reject-with);
300 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
301 add_target_def
'SAME', qw(to nodst*0 random*0);
302 add_target_def
'SECMARK', qw(selctx);
303 add_target_def
'SET', qw(add-set=sc del-set=sc);
304 add_target_def
'SNAT', qw(to-source=m to:=to-source random*0);
305 add_target_def
'TARPIT';
306 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
307 add_target_def
'TOS', qw(set-tos and-tos or-tos xor-tos);
308 add_target_def
'TRACE';
309 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
310 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
312 add_match_def_x
'arp', '',
314 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
316 qw(source-mac! destination-mac!),
318 qw(in-interface! interface:=in-interface if:=in-interface),
320 qw(out-interface! outerface:=out-interface of:=out-interface),
322 qw(h-length=s opcode=s h-type=s proto-type=s),
323 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
325 add_match_def_x
'eb', '',
327 qw(protocol! proto:=protocol),
329 qw(in-interface! interface:=in-interface if:=in-interface),
331 qw(out-interface! outerface:=out-interface of:=out-interface),
333 qw(logical-in! logical-out!),
334 # --source, --destination
335 qw(source! saddr:=source destination! daddr:=destination),
337 qw(802_3-sap! 802_3-type!),
339 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
340 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
342 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
348 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
349 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
350 qw(stp-hello-time! stp-forward-delay!),
352 qw(vlan-id! vlan-prio! vlan-encap!),
354 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
356 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
357 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
358 add_target_def_x
'eb', 'mark', qw(set-mark mark-target);
359 add_target_def_x
'eb', 'redirect', qw(redirect-target);
360 add_target_def_x
'eb', 'snat', qw(to-source snat-target);
362 # import-ferm uses the above tables
363 return 1 if $0 =~ /import-ferm$/;
365 use vars
qw(%builtin_keywords);
367 sub get_builtin_keywords($) {
368 my $domain_family = shift;
369 return {} unless defined $domain_family;
371 return {%{$builtin_keywords{$domain_family}}}
372 if exists $builtin_keywords{$domain_family};
374 return {} unless exists $match_defs{$domain_family};
375 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
376 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
378 $builtin_keywords{$domain_family} = \%keywords;
382 # parameter parser for ipt_multiport
383 sub multiport_params {
386 # multiport only allows 15 ports at a time. For this
387 # reason, we do a little magic here: split the ports
388 # into portions of 15, and handle these portions as
391 my $proto = $fw->{protocol};
392 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
393 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
395 my $value = getvalues(undef, undef,
397 allow_array_negation => 1);
398 if (ref $value and ref $value eq 'ARRAY') {
403 push @params, join(',', splice(@value, 0, 15));
410 return join_value(',', $value);
414 # initialize stack: command line definitions
417 # Get command line stuff
419 my ($opt_noexec, $opt_flush, $opt_lines, $opt_interactive,
420 $opt_verbose, $opt_debug,
422 $opt_version, $opt_test, $opt_fast, $opt_shell,
425 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
429 my ($opt, $value) = @_;
430 die 'Invalid --def specification'
431 unless $value =~ /^\$?(\w+)=(.*)$/s;
432 my ($name, $unparsed_value) = ($1, $2);
433 my $tokens = tokenize_string($unparsed_value);
434 my $value = getvalues(\&next_array_token, $tokens);
435 die 'Extra tokens after --def'
437 $stack[0]{vars}{$name} = $value;
440 local $SIG{__WARN__} = sub { die $_[0]; };
441 GetOptions('noexec|n' => \$opt_noexec,
442 'flush|F' => \$opt_flush,
443 'lines|l' => \$opt_lines,
444 'interactive|i' => \$opt_interactive,
445 'verbose|v' => \$opt_verbose,
446 'debug|d' => \$opt_debug,
447 'help|h' => \$opt_help,
448 'version|V' => \$opt_version,
450 remote => \$opt_test,
452 shell => \$opt_shell,
453 'domain=s' => \$opt_domain,
454 'def=s' => \&opt_def,
457 if (defined $opt_help) {
459 Pod::Usage::pod2usage(-exitstatus => 0);
462 if (defined $opt_version) {
467 $option{'noexec'} = (defined $opt_noexec);
468 $option{flush} = defined $opt_flush;
469 $option{'lines'} = (defined $opt_lines);
470 $option{interactive} = (defined $opt_interactive);
471 $option{test} = (defined $opt_test);
478 delete $option{interactive} if $option{noexec};
480 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
481 if $option{interactive} and not -t STDIN;
482 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
483 if $option{interactive} and not -t STDERR;
485 $option{fast} = 1 if defined $opt_fast;
487 if (defined $opt_shell) {
488 $option{$_} = 1 foreach qw(shell fast lines);
491 $option{domain
} = $opt_domain if defined $opt_domain;
493 print STDERR
"Warning: ignoring the obsolete --debug option\n"
494 if defined $opt_debug;
495 print STDERR
"Warning: ignoring the obsolete --verbose option\n"
496 if defined $opt_verbose;
498 # tiny getopt emulation for microperl
501 if ($_ eq '--noexec' or $_ eq '-n') {
503 } elsif ($_ eq '--lines' or $_ eq '-l') {
505 } elsif ($_ eq '--fast') {
507 } elsif ($_ eq '--test') {
511 } elsif ($_ eq '--shell') {
512 $option{$_} = 1 foreach qw(shell fast lines);
514 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
521 push @ARGV, $filename;
524 unless (@ARGV == 1) {
526 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
530 open LINES
, ">&STDOUT" if $option{lines
};
531 open STDOUT
, ">&STDERR" if $option{shell
};
533 # microperl can't redirect file handles
536 if ($option{fast
} and not $option{noexec
}) {
537 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
543 open_script
($ARGV[0]);
545 # parse all input recursively
547 die unless @stack == 2;
549 # execute all generated rules
552 foreach my $cmd (@pre_hooks) {
553 print LINES
"$cmd\n" if $option{lines
};
554 system($cmd) unless $option{noexec
};
557 while (my ($domain, $domain_info) = each %domains) {
558 next unless $domain_info->{enabled
};
559 my $s = $option{fast
} &&
560 defined $domain_info->{tools
}{'tables-restore'}
561 ? execute_fast
($domain, $domain_info)
562 : execute_slow
($domain, $domain_info);
563 $status = $s if defined $s;
566 foreach my $cmd (@post_hooks) {
567 print "$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 confirm_rules
() or rollback
() if $option{interactive
};
582 # end of program execution!
588 print "ferm $VERSION\n";
589 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
590 print "This program is free software released under GPLv2.\n";
591 print "See the included COPYING file for license details.\n";
603 # returns a nice formatted error message, showing the
604 # location of the error.
608 my @words = map { @
$_ } @
{$script->{past_tokens
}};
610 for my $w ( 0 .. $#words ) {
611 if ($words[$w] eq "\x29")
612 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
613 if ($words[$w] eq "\x28")
614 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
615 if ($words[$w] eq "\x7d")
616 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
617 if ($words[$w] eq "\x7b")
618 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
619 if ( $l > $#lines ) { $lines[$l] = "" };
620 $lines[$l] .= $words[$w] . " ";
621 if ($words[$w] eq "\x28")
622 { $l++ ; $lines[$l] = " " x
$tabs ;};
623 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
624 { $l++ ; $lines[$l] = " " x
$tabs ;};
625 if ($words[$w] eq "\x7b")
626 { $l++ ; $lines[$l] = " " x
$tabs ;};
627 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
628 { $l++ ; $lines[$l] = " " x
$tabs ;};
629 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
630 { $l++ ; $lines[$l] = " " x
$tabs ;}
631 if ($words[$w-1] eq "option")
632 { $l++ ; $lines[$l] = " " x
$tabs ;}
634 my $start = $#lines - 4;
635 if ($start < 0) { $start = 0 } ;
636 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
637 for $l ( $start .. $#lines)
638 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
639 print STDERR
"<--\n";
643 # print a warning message about code from an input file
645 print STDERR
"Warning in $script->{filename} line $script->{line}: "
651 return $name if $option{test
};
652 for my $path ('/sbin', split ':', $ENV{PATH
}) {
653 my $ret = "$path/$name";
654 return $ret if -x
$ret;
656 die "$name not found in PATH\n";
659 sub initialize_domain
{
661 my $domain_info = $domains{$domain} ||= {};
663 return if exists $domain_info->{initialized
};
665 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
667 my @tools = qw(tables);
668 push @tools, qw(tables-save tables-restore)
669 if $domain =~ /^ip6?$/;
671 # determine the location of this domain's tools
672 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
673 $domain_info->{tools
} = \
%tools;
675 # make tables-save tell us about the state of this domain
676 # (which tables and chains do exist?), also remember the old
677 # save data which may be used later by the rollback function
679 if (!$option{test
} &&
680 exists $tools{'tables-save'} &&
681 open(SAVE
, "$tools{'tables-save'}|")) {
690 $table_info = $domain_info->{tables
}{$table} ||= {};
691 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
693 $table_info->{chains
}{$1}{builtin
} = 1;
694 $table_info->{has_builtin
} = 1;
699 $domain_info->{previous
} = $save;
702 $domain_info->{initialized
} = 1;
705 # split the an input string into words and delete comments
706 sub tokenize_string
($) {
711 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
712 last if $word eq '#';
719 # shift an array; helper function to be passed to &getvar / &getvalues
720 sub next_array_token
{
725 # read some more tokens from the input file into a buffer
726 sub prepare_tokens
() {
727 my $tokens = $script->{tokens
};
728 while (@
$tokens == 0) {
729 my $handle = $script->{handle
};
730 my $line = <$handle>;
731 return unless defined $line;
735 # the next parser stage eats this
736 push @
$tokens, @
{tokenize_string
($line)};
742 # open a ferm sub script
744 my $filename = shift;
746 for (my $s = $script; defined $s; $s = $s->{parent
}) {
747 mydie
("Circular reference in $script->{filename} line $script->{line}: $filename")
748 if $s->{filename
} eq $filename;
752 open FILE
, "<$filename"
753 or mydie
("Failed to open $filename: $!");
756 $script = { filename
=> $filename,
767 # collect script filenames which are being included
768 sub collect_filenames
(@
) {
771 # determine the current script's parent directory for relative
773 die unless defined $script;
774 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
777 foreach my $pathname (@_) {
778 # non-absolute file names are relative to the parent script's
780 $pathname = $parent_dir . $pathname
781 unless $pathname =~ m
,^/,;
783 if ($pathname =~ m
,/$,) {
784 # include all regular files in a directory
786 error
("'$pathname' is not a directory")
790 opendir DIR
, $pathname
791 or error
("Failed to open directory '$pathname': $!");
792 my @names = readdir DIR
;
795 # sort those names for a well-defined order
796 foreach my $name (sort { $a cmp $b } @names) {
797 # don't include hidden and backup files
800 my $filename = $pathname . $name;
804 } elsif ($pathname =~ m
,\
|$,) {
805 # run a program and use its output
806 push @ret, $pathname;
807 } elsif ($pathname =~ m
,^\
|,) {
808 error
('This kind of pipe is not allowed');
810 # include a regular file
812 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
814 error
("'$pathname' is not a file")
817 push @ret, $pathname;
824 # peek a token from the queue, but don't remove it
826 return unless prepare_tokens
();
827 return $script->{tokens
}[0];
830 # get a token from the queue
832 return unless prepare_tokens
();
833 my $token = shift @
{$script->{tokens
}};
835 # update $script->{past_tokens}
836 my $past_tokens = $script->{past_tokens
};
838 if (@
$past_tokens > 0) {
839 my $prev_token = $past_tokens->[-1][-1];
840 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
841 if $prev_token eq ';';
843 if $prev_token eq '}';
846 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
847 push @
{$past_tokens->[-1]}, $token;
853 sub expect_token
($;$) {
856 my $token = next_token
();
857 error
($msg || "'$expect' expected")
858 unless defined $token and $token eq $expect;
861 # require that another token exists, and that it's not a "special"
862 # token, e.g. ";" and "{"
863 sub require_next_token
{
864 my $code = shift || \
&next_token
;
866 my $token = &$code(@_);
868 error
('unexpected end of file')
869 unless defined $token;
871 error
("'$token' not allowed here")
872 if $token =~ /^[;{}]$/;
877 # return the value of a variable
878 sub variable_value
($) {
882 return $_->{vars
}{$name}
883 if exists $_->{vars
}{$name};
886 return $stack[0]{auto
}{$name}
887 if exists $stack[0]{auto
}{$name};
892 # determine the value of a variable, die if the value is an array
893 sub string_variable_value
($) {
895 my $value = variable_value
($name);
897 error
("variable '$name' must be a string, but it is an array")
903 # similar to the built-in "join" function, but also handle negated
904 # values in a special way
906 my ($expr, $value) = @_;
908 unless (ref $value) {
910 } elsif (ref $value eq 'ARRAY') {
911 return join($expr, @
$value);
912 } elsif (ref $value eq 'negated') {
913 # bless'negated' is a special marker for negated values
914 $value = join_value
($expr, $value->[0]);
915 return bless [ $value ], 'negated';
921 # returns the next parameter, which may either be a scalar or an array
923 my ($code, $param) = (shift, shift);
926 my $token = require_next_token
($code, $param);
929 # read an array until ")"
933 $token = getvalues
($code, $param,
934 parenthesis_allowed
=> 1,
937 unless (ref $token) {
938 last if $token eq ')';
941 error
('Comma is not allowed within arrays, please use only a space');
945 push @wordlist, $token;
946 } elsif (ref $token eq 'ARRAY') {
947 push @wordlist, @
$token;
949 error
('unknown toke type');
953 error
('empty array not allowed here')
954 unless @wordlist or not $options{non_empty
};
956 return @wordlist == 1
959 } elsif ($token =~ /^\`(.*)\`$/s) {
960 # execute a shell command, insert output
962 my $output = `$command`;
965 error
("failed to execute: $!");
966 } elsif ($?
& 0x7f) {
967 error
("child died with signal " . ($?
& 0x7f));
969 error
("child exited with status " . ($?
>> 8));
974 $output =~ s/#.*//mg;
977 my @tokens = grep { length } split /\s+/s, $output;
981 my $value = getvalues
(\
&next_array_token
, \
@tokens);
982 push @values, to_array
($value);
989 } elsif ($token =~ /^\'(.*)\'$/s) {
990 # single quotes: a string
992 } elsif ($token =~ /^\"(.*)\"$/s) {
993 # double quotes: a string with escapes
995 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
997 } elsif ($token eq '!') {
998 error
('negation is not allowed here')
999 unless $options{allow_negation
};
1001 $token = getvalues
($code, $param);
1003 error
('it is not possible to negate an array')
1004 if ref $token and not $options{allow_array_negation
};
1006 return bless [ $token ], 'negated';
1007 } elsif ($token eq ',') {
1009 if $options{comma_allowed
};
1011 error
('comma is not allowed here');
1012 } elsif ($token eq '=') {
1013 error
('equals operator ("=") is not allowed here');
1014 } elsif ($token eq '$') {
1015 my $name = require_next_token
($code, $param);
1016 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1017 unless $name =~ /^\w+$/;
1019 my $value = variable_value
($name);
1021 error
("no such variable: \$$name")
1022 unless defined $value;
1025 } elsif ($token eq '&') {
1026 error
("function calls are not allowed as keyword parameter");
1027 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1028 error
('Syntax error');
1029 } elsif ($token =~ /^@/) {
1030 if ($token eq '@resolve') {
1031 my @params = get_function_params
();
1032 error
('Usage: @resolve((hostname ...))')
1033 unless @params == 1;
1034 eval { require Net
::DNS
; };
1035 error
('For the @resolve() function, you need the Perl library Net::DNS')
1038 my $resolver = new Net
::DNS
::Resolver
;
1040 foreach my $hostname (to_array
($params[0])) {
1041 my $query = $resolver->search($hostname, $type);
1042 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
1044 foreach my $rr ($query->answer) {
1045 next unless $rr->type eq $type;
1046 push @result, $rr->address;
1051 error
("unknown ferm built-in function");
1058 # returns the next parameter, but only allow a scalar
1060 my $token = getvalues
(@_);
1062 error
('array not allowed here')
1063 if ref $token and ref $token eq 'ARRAY';
1068 sub get_function_params
(%) {
1069 expect_token
('(', 'function name must be followed by "()"');
1071 my $token = peek_token
();
1072 if ($token eq ')') {
1081 $token = require_next_token
();
1085 error
('"," expected')
1086 unless $token eq ',';
1089 push @params, getvalues
(undef, undef, @_);
1095 # collect all tokens in a flat array reference until the end of the
1096 # command is reached
1097 sub collect_tokens
() {
1102 my $keyword = next_token
();
1103 error
('unexpected end of file within function/variable declaration')
1104 unless defined $keyword;
1106 if ($keyword =~ /^[\{\(]$/) {
1107 push @level, $keyword;
1108 } elsif ($keyword =~ /^[\}\)]$/) {
1109 my $expected = $keyword;
1110 $expected =~ tr/\}\)/\{\(/;
1111 my $opener = pop @level;
1112 error
("unmatched '$keyword'")
1113 unless defined $opener and $opener eq $expected;
1114 } elsif ($keyword eq ';' and @level == 0) {
1118 push @tokens, $keyword;
1121 if $keyword eq '}' and @level == 0;
1128 # returns the specified value as an array. dereference arrayrefs
1131 die unless wantarray;
1133 unless (ref $value) {
1135 } elsif (ref $value eq 'ARRAY') {
1142 # evaluate the specified value as bool
1147 unless (ref $value) {
1149 } elsif (ref $value eq 'ARRAY') {
1156 sub is_netfilter_core_target
($) {
1158 die unless defined $target and length $target;
1160 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1163 sub is_netfilter_module_target
($$) {
1164 my ($domain_family, $target) = @_;
1165 die unless defined $target and length $target;
1167 return defined $domain_family &&
1168 exists $target_defs{$domain_family} &&
1169 $target_defs{$domain_family}{$target};
1172 sub is_netfilter_builtin_chain
($$) {
1173 my ($table, $chain) = @_;
1175 return grep { $_ eq $chain }
1176 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1179 sub netfilter_canonical_protocol
($) {
1182 if $proto eq 'ipv6-icmp';
1184 if $proto eq 'ipv6-mh';
1188 sub netfilter_protocol_module
($) {
1190 return unless defined $proto;
1192 if $proto eq 'icmpv6';
1196 # escape the string in a way safe for the shell
1197 sub shell_escape
($) {
1200 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1202 if ($option{fast
}) {
1203 # iptables-save/iptables-restore are quite buggy concerning
1204 # escaping and special characters... we're trying our best
1208 $token = '"' . $token . '"'
1209 if $token =~ /[\s\'\\;&]/s;
1212 if $token =~ /^\`.*\`$/;
1213 $token =~ s/'/\\'/g;
1214 $token = '\'' . $token . '\''
1215 if $token =~ /[\s\"\\;<>&|]/s;
1221 # append an option to the shell command line, using information from
1222 # the module definition (see %match_defs etc.)
1223 sub shell_append_option($$$) {
1224 my ($ref, $keyword, $value) = @_;
1227 if (ref $value eq 'negated') {
1228 $value = $value->[0];
1230 } elsif (ref $value eq 'pre_negated') {
1231 $value = $value->[0];
1236 unless (defined $value) {
1237 $$ref .= " --$keyword";
1238 } elsif (ref $value) {
1239 if (ref $value eq 'params') {
1240 $$ref .= " --$keyword ";
1241 $$ref .= join(' ', map { shell_escape($_) } @$value);
1242 } elsif (ref $value eq 'multi') {
1244 $$ref .= " --$keyword " . shell_escape($_);
1250 $$ref .= " --$keyword " . shell_escape($value);
1254 # convert an internal rule structure into an iptables call
1256 my ($table_info, $chain_info, $rule) = @_;
1258 return if $option{flush};
1260 # return if this is a declaration-only rule
1262 unless $rule->{has_rule};
1266 # general iptables options
1268 shell_append_option(\$rr, 'protocol', $rule->{protocol})
1269 if exists $rule->{protocol};
1271 while (my ($keyword, $value) = each %{$rule->{builtin}}) {
1272 shell_append_option(\$rr, $keyword, $value);
1276 # match module options
1281 if (defined $rule->{protocol}) {
1282 my $proto = $rule->{protocol};
1284 # special case: --dport and --sport for TCP/UDP
1285 if ($rule->{domain_family} eq 'ip' and
1286 (exists $rule->{dport} or exists $rule->{sport}) and
1287 $proto =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
1288 unless (exists $modules{$proto}) {
1289 $rr .= " -m
$proto";
1290 $modules{$proto} = 1;
1293 shell_append_option(\$rr, 'dport', $rule->{dport})
1294 if exists $rule->{dport};
1295 shell_append_option(\$rr, 'sport', $rule->{sport})
1296 if exists $rule->{sport};
1300 # modules stored in %match_defs
1302 foreach my $match (@{$rule->{match}}) {
1303 my $module_name = $match->{name};
1304 unless (exists $modules{$module_name}) {
1305 $rr .= " -m
$module_name";
1306 $modules{$module_name} = 1;
1309 while (my ($keyword, $value) = each %{$match->{options}}) {
1310 shell_append_option(\$rr, $keyword, $value);
1318 my $action = $rule->{action};
1319 if ($action->{type} eq 'jump') {
1320 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1321 $rr .= " -j
" . $action->{chain};
1322 } elsif ($action->{type} eq 'goto') {
1323 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1324 $rr .= " -g
" . $action->{chain};
1325 } elsif ($action->{type} eq 'target') {
1326 $rr .= " -j
" . $action->{target};
1328 # targets stored in %target_defs
1330 while (my ($keyword, $value) = each %{$rule->{target_options}}) {
1331 shell_append_option(\$rr, $keyword, $value);
1333 } elsif ($action->{type} ne 'nop') {
1338 my $chain_rules = $chain_info->{rules} ||= [];
1339 push @$chain_rules, { rule => $rr,
1340 script => $rule->{script},
1344 sub transform_rule($$) {
1345 my ($domain, $rule) = @_;
1347 $rule->{protocol} = 'icmpv6'
1348 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1351 sub printrule($$$$) {
1352 my ($domain, $table, $chain, $rule) = @_;
1354 transform_rule($domain, $rule);
1356 my $domain_info = $domains{$domain};
1357 $domain_info->{enabled} = 1;
1358 my $table_info = $domain_info->{tables}{$table} ||= {};
1359 my $chain_info = $table_info->{chains}{$chain} ||= {};
1361 # prints all rules in a hash
1362 tables($table_info, $chain_info, $rule);
1366 sub check_unfold(\@$$) {
1367 my ($unfold, $parent, $key) = @_;
1369 return unless ref $parent->{$key} and
1370 ref $parent->{$key} eq 'ARRAY';
1372 push @$unfold, $parent, $key, $parent->{$key};
1375 sub mkrules2($$$$) {
1376 my ($domain, $table, $chain, $fw) = @_;
1380 foreach my $key (keys %{$fw->{builtin}}) {
1381 check_unfold(@unfold, $fw->{builtin}, $key);
1384 foreach my $match (@{$fw->{match}}) {
1385 while (my ($key, $value) = each %{$match->{options}}) {
1386 check_unfold(@unfold, $match->{options}, $key);
1390 check_unfold(@unfold, $fw, 'protocol');
1391 check_unfold(@unfold, $fw, 'sport');
1392 check_unfold(@unfold, $fw, 'dport');
1395 printrule($domain, $table, $chain, $fw);
1401 my ($domain, $table, $chain) = (shift, shift, shift);
1402 my ($parent, $key, $values) = (shift, shift, shift);
1404 foreach my $value (@$values) {
1405 $parent->{$key} = $value;
1408 dofr($fw, $domain, $table, $chain, @_);
1410 printrule($domain, $table, $chain, $fw);
1415 dofr($fw, $domain, $table, $chain, @unfold);
1418 # convert a bunch of internal rule structures in iptables calls,
1419 # unfold arrays during that
1423 foreach my $domain (to_array $fw->{domain}) {
1424 foreach my $table (to_array $fw->{table}) {
1425 foreach my $chain (to_array $fw->{chain}) {
1426 mkrules2($domain, $table, $chain, $fw);
1432 sub filter_domains($) {
1433 my $domains = shift;
1436 foreach my $domain (to_array $domains) {
1437 next if exists $option{domain}
1438 and $domain ne $option{domain};
1441 initialize_domain($domain);
1445 push @$result, $domain;
1448 return @$result == 1 ? $result->[0] : $result;
1451 # parse a keyword from a module definition
1452 sub parse_keyword($$$$) {
1453 my ($current, $def, $keyword, $negated_ref) = @_;
1455 my $params = $def->{params};
1460 if ($$negated_ref && exists $def->{pre_negation}) {
1462 undef $$negated_ref;
1465 unless (defined $params) {
1467 } elsif (ref $params && ref $params eq 'CODE') {
1468 $value = &$params($current);
1469 } elsif ($params eq 'm') {
1470 $value = bless [ to_array getvalues() ], 'multi';
1471 } elsif ($params =~ /^[a-z]/) {
1472 if (exists $def->{negation} and not $negated) {
1473 my $token = peek_token();
1474 if ($token eq '!') {
1481 foreach my $p (split(//, $params)) {
1483 push @params, getvar();
1484 } elsif ($p eq 'c') {
1485 my @v = to_array getvalues(undef, undef,
1487 push @params, join(',', @v);
1493 $value = @params == 1
1495 : bless \@params, 'params';
1496 } elsif ($params == 1) {
1497 if (exists $def->{negation} and not $negated) {
1498 my $token = peek_token();
1499 if ($token eq '!') {
1505 $value = getvalues();
1507 warning("log-prefix is too long
; truncating to
29 characters
: '$1'")
1508 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1510 if (exists $def->{negation} and not $negated) {
1511 my $token = peek_token();
1512 if ($token eq '!') {
1518 $value = bless [ map {
1520 } (1..$params) ], 'params';
1523 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1529 # parse options of a module
1530 sub parse_option($$$$$) {
1531 my ($def, $current, $store, $keyword, $negated_ref) = @_;
1533 while (exists $def->{alias}) {
1534 ($keyword, $def) = @{$def->{alias}};
1535 die unless defined $def;
1539 = parse_keyword($current, $def,
1540 $keyword, $negated_ref);
1544 # parse options for a protocol module definition
1545 sub parse_protocol_options($$$$) {
1546 my ($current, $proto, $keyword, $negated_ref) = @_;
1548 my $domain_family = $current->{'domain_family'};
1549 my $proto_defs = $proto_defs{$domain_family};
1550 return unless defined $proto_defs;
1552 my $proto_def = $proto_defs->{$proto};
1553 return unless defined $proto_def and
1554 exists $proto_def->{keywords}{$keyword};
1556 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1557 my $module = { name => $module_name,
1560 push @{$current->{match}}, $module;
1562 return parse_option($proto_def->{keywords}{$keyword},
1563 $current, $module->{options},
1564 $keyword, $negated_ref);
1567 sub copy_on_write($$) {
1568 my ($rule, $key) = @_;
1569 return unless exists $rule->{cow}{$key};
1570 $rule->{$key} = {%{$rule->{$key}}};
1571 delete $rule->{cow}{$key};
1574 sub clone_match($) {
1576 return { name => $match->{name},
1577 options => { %{$match->{options}} },
1581 sub new_level(\%$) {
1582 my ($current, $prev) = @_;
1585 if (defined $prev) {
1586 # copy data from previous level
1587 $current->{cow} = { keywords => 1, };
1588 $current->{keywords} = $prev->{keywords};
1589 $current->{builtin} = { %{$prev->{builtin}} };
1590 $current->{match} = [ map { clone_match($_) } @{$prev->{match}} ];
1591 $current->{action} = { %{$prev->{action}} };
1592 foreach my $key (qw(domain domain_family table chain protocol sport dport)) {
1593 $current->{$key} = $prev->{$key}
1594 if exists $prev->{$key};
1597 $current->{cow
} = {};
1598 $current->{keywords
} = {};
1599 $current->{builtin
} = {};
1600 $current->{match
} = [];
1601 $current->{action
} = {};
1605 sub merge_keywords
(\
%$$$) {
1606 my ($rule, $type, $module, $keywords) = @_;
1607 copy_on_write
($rule, 'keywords');
1608 while (my ($name, $def) = each %$keywords) {
1609 $rule->{keywords
}{$name} = [ $type, $module, $def ];
1613 sub set_domain
(\
%$) {
1614 my ($rule, $domain) = @_;
1616 my $filtered_domain = filter_domains
($domain);
1618 unless (ref $domain) {
1619 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1620 } elsif (@
$domain == 0) {
1621 $domain_family = 'none';
1622 } elsif (grep { not /^ip6?$/s } @
$domain) {
1623 error
('Cannot combine non-IP domains');
1625 $domain_family = 'ip';
1628 $rule->{domain_family
} = $domain_family;
1629 $rule->{keywords
} = get_builtin_keywords
($domain_family);
1630 delete $rule->{cow
}{keywords
};
1632 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $filtered_domain;
1635 sub set_module_target
(\
%$$) {
1636 my ($rule, $name, $defs) = @_;
1638 if ($name eq 'TCPMSS') {
1639 my $protos = $rule->{protocol
};
1640 error
('No protocol specified before TCPMSS')
1641 unless defined $protos;
1642 foreach my $proto (to_array
$protos) {
1643 error
('TCPMSS not available for protocol "$proto"')
1644 unless $proto eq 'tcp';
1653 merge_keywords
(%$rule, 'target', $name, $defs->{keywords
});
1656 # the main parser loop: read tokens, convert them into internal rule
1659 my $lev = shift; # current recursion depth
1660 my $prev = shift; # previous rule hash
1662 # enter is the core of the firewall setup, it is a
1663 # simple parser program that recognizes keywords and
1664 # retreives parameters to set up the kernel routing
1667 my $base_level = $script->{base_level
} || 0;
1668 die if $base_level > $lev;
1671 new_level
(%current, $prev);
1673 # read keywords 1 by 1 and dump into parser
1674 while (defined (my $keyword = next_token
())) {
1675 # check if the current rule should be negated
1676 my $negated = $keyword eq '!';
1678 # negation. get the next word which contains the 'real'
1680 $keyword = getvar
();
1682 error
('unexpected end of file after negation')
1683 unless defined $keyword;
1686 # the core: parse all data
1689 # deprecated keyword?
1690 if (exists $deprecated_keywords{$keyword}) {
1691 my $new_keyword = $deprecated_keywords{$keyword};
1692 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1693 $keyword = $new_keyword;
1696 # effectuation operator
1697 if ($keyword eq ';') {
1698 if ($current{has_rule
} and not $current{action
}{type
}) {
1699 # something is wrong when a rule was specifiedd,
1701 error
('No action defined; did you mean "NOP"?');
1704 error
('No chain defined') unless exists $current{chain
};
1706 $current{script
} = { filename
=> $script->{filename
},
1707 line
=> $script->{line
},
1712 # and clean up variables set in this level
1713 new_level
(%current, $prev);
1718 # conditional expression
1719 if ($keyword eq '@if') {
1720 unless (eval_bool
(getvalues
)) {
1722 my $token = peek_token
();
1723 require_next_token
() if $token and $token eq '@else';
1729 if ($keyword eq '@else') {
1730 # hack: if this "else" has not been eaten by the "if"
1731 # handler above, we believe it came from an if clause
1732 # which evaluated "true" - remove the "else" part now.
1737 # hooks for custom shell commands
1738 if ($keyword eq 'hook') {
1739 error
('"hook" must be the first token in a command')
1740 if exists $current{domain
};
1742 my $position = getvar
();
1744 if ($position eq 'pre') {
1745 $hooks = \
@pre_hooks;
1746 } elsif ($position eq 'post') {
1747 $hooks = \
@post_hooks;
1749 error
("Invalid hook position: '$position'");
1752 push @
$hooks, getvar
();
1758 # recursing operators
1759 if ($keyword eq '{') {
1761 my $old_stack_depth = @stack;
1763 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1766 enter
($lev + 1, \
%current);
1770 die unless @stack == $old_stack_depth;
1772 # after a block, the command is finished, clear this
1774 new_level
(%current, $prev);
1779 if ($keyword eq '}') {
1780 error
('Unmatched "}"')
1781 if $lev <= $base_level;
1783 # consistency check: check if they havn't forgotten
1784 # the ';' before the last statement
1785 error
('Missing semicolon before "}"')
1786 if $current{has_rule
};
1792 # include another file
1793 if ($keyword eq '@include' or $keyword eq 'include') {
1794 my @files = collect_filenames to_array getvalues
;
1795 $keyword = next_token
;
1796 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1797 unless defined $keyword and $keyword eq ';';
1799 foreach my $filename (@files) {
1800 # save old script, open new script
1801 my $old_script = $script;
1802 open_script
($filename);
1803 $script->{base_level
} = $lev + 1;
1806 my $old_stack_depth = @stack;
1811 # include files may set variables for their parent
1812 $stack->{vars
} = ($stack[0]{vars
} ||= {});
1813 $stack->{functions
} = ($stack[0]{functions
} ||= {});
1814 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
1817 unshift @stack, $stack;
1820 enter
($lev + 1, \
%current);
1824 die unless @stack == $old_stack_depth;
1826 # restore old script
1827 $script = $old_script;
1833 # definition of a variable or function
1834 if ($keyword eq '@def' or $keyword eq 'def') {
1835 error
('"def" must be the first token in a command')
1836 if $current{has_rule
};
1838 my $type = require_next_token
();
1840 my $name = require_next_token
();
1841 error
('invalid variable name')
1842 unless $name =~ /^\w+$/;
1846 my $value = getvalues
(undef, undef, allow_negation
=> 1);
1850 $stack[0]{vars
}{$name} = $value
1851 unless exists $stack[-1]{vars
}{$name};
1852 } elsif ($type eq '&') {
1853 my $name = require_next_token
();
1854 error
('invalid function name')
1855 unless $name =~ /^\w+$/;
1857 expect_token
('(', 'function parameter list or "()" expected');
1861 my $token = require_next_token
();
1862 last if $token eq ')';
1865 error
('"," expected')
1866 unless $token eq ',';
1868 $token = require_next_token
();
1871 error
('"$" and parameter name expected')
1872 unless $token eq '$';
1874 $token = require_next_token
();
1875 error
('invalid function parameter name')
1876 unless $token =~ /^\w+$/;
1878 push @params, $token;
1883 $function{params
} = \
@params;
1887 my $tokens = collect_tokens
();
1888 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
1889 $function{tokens
} = $tokens;
1891 $stack[0]{functions
}{$name} = \
%function
1892 unless exists $stack[-1]{functions
}{$name};
1894 error
('"$" (variable) or "&" (function) expected');
1901 if ($keyword eq '$') {
1902 error
('variable references are only allowed as keyword parameter');
1905 if ($keyword eq '&') {
1906 my $name = require_next_token
;
1907 error
('function name expected')
1908 unless $name =~ /^\w+$/;
1912 $function = $_->{functions
}{$name};
1913 last if defined $function;
1915 error
("no such function: \&$name")
1916 unless defined $function;
1918 my $paramdef = $function->{params
};
1919 die unless defined $paramdef;
1921 my @params = get_function_params
(allow_negation
=> 1);
1923 error
("Wrong number of parameters for function '\&$name': "
1924 . @
$paramdef . " expected, " . @params . " given")
1925 unless @params == @
$paramdef;
1928 for (my $i = 0; $i < @params; $i++) {
1929 $vars{$paramdef->[$i]} = $params[$i];
1932 if ($function->{block
}) {
1933 # block {} always ends the current rule, so if the
1934 # function contains a block, we have to require
1935 # the calling rule also ends here
1939 my @tokens = @
{$function->{tokens
}};
1940 for (my $i = 0; $i < @tokens; $i++) {
1941 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1942 exists $vars{$tokens[$i + 1]}) {
1943 my @value = to_array
($vars{$tokens[$i + 1]});
1944 @value = ('(', @value, ')')
1945 unless @tokens == 1;
1946 splice(@tokens, $i, 2, @value);
1948 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
1949 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
1953 unshift @
{$script->{tokens
}}, @tokens;
1958 # where to put the rule?
1959 if ($keyword eq 'domain') {
1960 error
('Domain is already specified')
1961 if exists $current{domain
};
1963 set_domain
(%current, getvalues
());
1967 if ($keyword eq 'table') {
1968 error
('Table is already specified')
1969 if exists $current{table
};
1970 $current{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
1972 set_domain
(%current, 'ip')
1973 unless exists $current{domain
};
1978 if ($keyword eq 'chain') {
1979 error
('Chain is already specified')
1980 if exists $current{chain
};
1981 $current{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
1983 # ferm 1.1 allowed lower case built-in chain names
1984 foreach (ref $current{chain
} ? @
{$current{chain
}} : $current{chain
}) {
1985 error
('Please write built-in chain names in upper case')
1986 if /^(?:input|forward|output|prerouting|postrouting)$/;
1989 set_domain
(%current, 'ip')
1990 unless exists $current{domain
};
1992 $current{table
} = 'filter'
1993 unless exists $current{table
};
1998 error
('Chain must be specified')
1999 unless exists $current{chain
};
2001 # policy for built-in chain
2002 if ($keyword eq 'policy') {
2003 error
('Cannot specify matches for policy')
2004 if $current{has_rule
};
2006 my $policy = getvar
();
2007 error
("Invalid policy target: $policy")
2008 unless $policy =~ /^(?:ACCEPT|DROP)$/;
2012 foreach my $domain (to_array
$current{domain
}) {
2013 foreach my $table (to_array
$current{table
}) {
2014 foreach my $chain (to_array
$current{chain
}) {
2015 $domains{$domain}{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
2020 new_level
(%current, $prev);
2025 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2026 error
('Chain must be specified')
2027 unless exists $current{chain
};
2029 error
('No rule specified before "@subchain"')
2030 unless $current{has_rule
};
2033 $keyword = next_token
();
2035 if ($keyword =~ /^(["'])(.*)\1$/s) {
2037 $keyword = next_token
();
2039 $subchain = 'ferm_auto_' . ++$auto_chain;
2042 error
('"{" or chain name expected after "@subchain"')
2043 unless $keyword eq '{';
2045 # create a deep copy of %current, only containing values
2046 # which must be in the subchain
2047 my %inner = ( cow
=> { keywords
=> 1, },
2048 keywords
=> $current{keywords
},
2052 $inner{domain
} = $current{domain
};
2053 $inner{domain_family
} = $current{domain_family
};
2054 $inner{table
} = $current{table
};
2055 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2056 $inner{protocol
} = $current{protocol
}
2057 if exists $current{protocol
};
2062 # now handle the parent - it's a jump to the sub chain
2063 $current{action
} = { type
=> 'jump',
2067 $current{script
} = { filename
=> $script->{filename
},
2068 line
=> $script->{line
},
2073 # and clean up variables set in this level
2074 new_level
(%current, $prev);
2079 # everything else must be part of a "real" rule, not just
2081 $current{has_rule
}++;
2083 # extended parameters:
2084 if ($keyword =~ /^mod(?:ule)?$/) {
2085 foreach my $module (to_array getvalues
) {
2086 next if grep { $_->{name
} eq $module } @
{$current{match
}};
2088 my $domain_family = $current{domain_family
};
2089 my $defs = $match_defs{$domain_family}{$module};
2090 if (not defined $defs and exists $current{protocol
}) {
2091 my $proto = $current{protocol
};
2092 unless (ref $proto) {
2093 $proto = netfilter_canonical_protocol
($current{protocol
});
2094 $defs = $proto_defs{$domain_family}{$proto}
2095 if netfilter_protocol_module
($proto) eq $module;
2099 push @
{$current{match
}}, { name
=> $module,
2103 merge_keywords
(%current, 'match', $module, $defs->{keywords
})
2110 # keywords from $current{keywords}
2112 if (exists $current{keywords
}{$keyword}) {
2113 my ($type, $module, $def) = @
{$current{keywords
}{$keyword}};
2115 if ($type eq 'builtin') {
2116 $store = $current{builtin
};
2117 } elsif ($type eq 'match') {
2118 $store = (grep { $_->{name
} eq $module } @
{$current{match
}})[-1]->{options
};
2119 } elsif ($type eq 'target') {
2120 $store = $current{target_options
} ||= {};
2125 parse_option
($def, \
%current, $store, $keyword, \
$negated);
2134 if ($keyword eq 'jump') {
2135 error
('There can only one action per rule')
2136 if defined $current{action
}{type
};
2137 my $chain = getvar
();
2138 if (is_netfilter_core_target
($chain)) {
2139 $current{action
} = {
2143 } elsif (my $defs = is_netfilter_module_target
($current{domain_family
}, $chain)) {
2144 set_module_target
(%current, $chain, $defs);
2146 $current{action
} = { type
=> 'jump',
2154 if ($keyword eq 'realgoto') {
2155 error
('There can only one action per rule')
2156 if defined $current{action
}{type
};
2157 $current{action
} = { type
=> 'goto',
2164 if (is_netfilter_core_target
($keyword)) {
2165 error
('There can only one action per rule')
2166 if defined $current{action
}{type
};
2167 $current{action
} = { type
=> 'target',
2173 if ($keyword eq 'NOP') {
2174 error
('There can only one action per rule')
2175 if defined $current{action
}{type
};
2176 $current{action
} = { type
=> 'nop',
2181 if (my $defs = is_netfilter_module_target
($current{domain_family
}, $keyword)) {
2182 error
('There can only one action per rule')
2183 if defined $current{action
}{type
};
2185 set_module_target
(%current, $keyword, $defs);
2189 my $proto = $current{protocol
};
2192 # protocol specific options
2195 if (defined $proto and not ref $proto) {
2196 $proto = netfilter_canonical_protocol
($proto);
2198 if ($proto eq 'icmp') {
2199 my $domains = $current{domain
};
2200 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2203 parse_protocol_options
(\
%current, $proto, $keyword, \
$negated)
2207 if ($keyword eq 'proto') {
2208 $current{protocol
} = parse_keyword
(\
%current,
2211 'proto', \
$negated);
2216 if ($keyword =~ /^[sd]port$/) {
2217 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2218 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2220 $current{$keyword} = getvalues
(undef, undef,
2221 allow_negation
=> 1);
2226 error
("Unrecognized keyword: $keyword");
2229 # if the rule didn't reset the negated flag, it's not
2231 error
("Doesn't support negation: $keyword")
2235 error
('Missing "}" at end of file')
2236 if $lev > $base_level;
2238 # consistency check: check if they havn't forgotten
2239 # the ';' before the last statement
2240 error
("Missing semicolon before end of file")
2241 if exists $current{domain
};
2244 sub execute_command
{
2245 my ($command, $script) = @_;
2247 print LINES
"$command\n"
2249 return if $option{noexec
};
2251 my $ret = system($command);
2252 unless ($ret == 0) {
2254 print STDERR
"failed to execute: $!\n";
2256 } elsif ($?
& 0x7f) {
2257 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2260 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2269 sub execute_slow
($$) {
2270 my ($domain, $domain_info) = @_;
2272 my $domain_cmd = $domain_info->{tools
}{tables
};
2275 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2276 my $table_cmd = "$domain_cmd -t $table";
2278 # reset chain policies
2279 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2280 next unless $chain_info->{builtin
} or
2281 (not $table_info->{has_builtin
} and
2282 is_netfilter_builtin_chain
($table, $chain));
2283 $status ||= execute_command
("$table_cmd -P $chain ACCEPT");
2287 $status ||= execute_command
("$table_cmd -F");
2288 $status ||= execute_command
("$table_cmd -X");
2290 next if $option{flush
};
2292 # create chains / set policy
2293 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2294 if (exists $chain_info->{policy
}) {
2295 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2296 unless $chain_info->{policy
} eq 'ACCEPT';
2297 } elsif (not is_netfilter_builtin_chain
($table, $chain)) {
2298 $status ||= execute_command
("$table_cmd -N $chain");
2303 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2304 my $chain_cmd = "$table_cmd -A $chain";
2305 foreach my $rule (@
{$chain_info->{rules
}}) {
2306 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2314 sub rules_to_save
($$) {
2315 my ($domain, $domain_info) = @_;
2317 # convert this into an iptables-save text
2318 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2320 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2322 $result .= '*' . $table . "\n";
2324 # create chains / set policy
2325 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2326 my $chain_info = $table_info->{chains
}{$chain};
2327 my $policy = $option{flush
} ?
'ACCEPT' : $chain_info->{policy
};
2328 unless (defined $policy) {
2329 if (is_netfilter_builtin_chain
($table, $chain)) {
2335 $result .= ":$chain $policy\ [0:0]\n";
2338 next if $option{flush
};
2341 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2342 my $chain_info = $table_info->{chains
}{$chain};
2343 foreach my $rule (@
{$chain_info->{rules
}}) {
2344 $result .= "-A $chain$rule->{rule}\n";
2349 $result .= "COMMIT\n";
2355 sub restore_domain
($$) {
2356 my ($domain, $save) = @_;
2358 my $path = $domains{$domain}{tools
}{'tables-restore'};
2361 open RESTORE
, "|$path"
2362 or die "Failed to run $path: $!\n";
2364 print RESTORE
$save;
2367 or die "Failed to run $path\n";
2370 sub execute_fast
($$) {
2371 my ($domain, $domain_info) = @_;
2373 my $save = rules_to_save
($domain, $domain_info);
2375 if ($option{lines
}) {
2376 print LINES
"$domain_info->{tools}{'tables-restore'} <<EOT\n"
2383 return if $option{noexec};
2386 restore_domain($domain, $save);
2398 while (my ($domain, $domain_info) = each %domains) {
2399 next unless $domain_info->{enabled};
2400 unless (defined $domain_info->{tools}{'tables-restore'}) {
2401 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2406 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2407 my $reset_chain = '';
2408 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2409 next unless is_netfilter_builtin_chain($table, $chain);
2410 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2412 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2413 if length $reset_chain;
2416 $reset .= $domain_info->{previous}
2417 if defined $domain_info->{previous};
2419 restore_domain($domain, $reset);
2422 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2427 # do nothing, just interrupt a system call
2430 sub confirm_rules() {
2431 $SIG{ALRM} = \&alrm_handler;
2436 . "ferm has applied the new firewall rules
.\n"
2437 . "Please type
'yes' to confirm
:\n";
2443 STDIN->sysread($line, 3);
2447 POSIX::tcflush(*STDIN, 2);
2449 print STDERR "$@
" if $@;
2451 $SIG{ALRM} = 'DEFAULT';
2453 return $line eq 'yes';
2462 ferm - a firewall rule parser for linux
2466 B<ferm> I<options> I<inputfiles>
2470 -n, --noexec Do not execute the rules, just simulate
2471 -F, --flush Flush all netfilter tables managed by ferm
2472 -l, --lines Show all rules that were created
2473 -i, --interactive Interactive mode: revert if user does not confirm
2474 --remote Remote mode; ignore host specific configuration.
2475 This implies --noexec and --lines.
2476 -V, --version Show current version number
2477 -h, --help Look at this text
2478 --fast Generate an iptables-save file, used by iptables-restore
2479 --shell Generate a shell script which calls iptables-restore
2480 --domain {ip|ip6} Handle only the specified domain
2481 --def '$name=v' Override a variable