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 # parameter parser for ipt_multiport
366 sub multiport_params
{
369 # multiport only allows 15 ports at a time. For this
370 # reason, we do a little magic here: split the ports
371 # into portions of 15, and handle these portions as
374 my $proto = $fw->{protocol
};
375 error
('To use multiport, you have to specify "proto tcp" or "proto udp" first')
376 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array
($proto);
378 my $value = getvalues
(undef, undef,
380 allow_array_negation
=> 1);
381 if (ref $value and ref $value eq 'ARRAY') {
386 push @params, join(',', splice(@value, 0, 15));
393 return join_value
(',', $value);
397 # initialize stack: command line definitions
400 # Get command line stuff
402 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
403 $opt_verbose, $opt_debug,
405 $opt_version, $opt_test, $opt_fast, $opt_shell,
408 Getopt
::Long
::Configure
('bundling', 'auto_help', 'no_ignore_case',
412 my ($opt, $value) = @_;
413 die 'Invalid --def specification'
414 unless $value =~ /^\$?(\w+)=(.*)$/s;
415 my ($name, $unparsed_value) = ($1, $2);
416 my $tokens = tokenize_string
($unparsed_value);
417 my $value = getvalues
(\
&next_array_token
, $tokens);
418 die 'Extra tokens after --def'
420 $stack[0]{vars
}{$name} = $value;
423 local $SIG{__WARN__
} = sub { die $_[0]; };
424 GetOptions
('noexec|n' => \
$opt_noexec,
425 'flush|F' => \
$opt_flush,
426 'noflush' => \
$opt_noflush,
427 'lines|l' => \
$opt_lines,
428 'interactive|i' => \
$opt_interactive,
429 'verbose|v' => \
$opt_verbose,
430 'debug|d' => \
$opt_debug,
431 'help|h' => \
$opt_help,
432 'version|V' => \
$opt_version,
434 remote
=> \
$opt_test,
436 shell
=> \
$opt_shell,
437 'domain=s' => \
$opt_domain,
438 'def=s' => \
&opt_def
,
441 if (defined $opt_help) {
443 Pod
::Usage
::pod2usage
(-exitstatus
=> 0);
446 if (defined $opt_version) {
451 $option{'noexec'} = (defined $opt_noexec);
452 $option{flush
} = defined $opt_flush;
453 $option{noflush
} = defined $opt_noflush;
454 $option{'lines'} = (defined $opt_lines);
455 $option{interactive
} = (defined $opt_interactive);
456 $option{test
} = (defined $opt_test);
463 delete $option{interactive
} if $option{noexec
};
465 mydie
('ferm interactive mode not possible: /dev/stdin is not a tty')
466 if $option{interactive
} and not -t STDIN
;
467 mydie
('ferm interactive mode not possible: /dev/stderr is not a tty')
468 if $option{interactive
} and not -t STDERR
;
470 $option{fast
} = 1 if defined $opt_fast;
472 if (defined $opt_shell) {
473 $option{$_} = 1 foreach qw(shell fast lines);
476 $option{domain
} = $opt_domain if defined $opt_domain;
478 print STDERR
"Warning: ignoring the obsolete --debug option\n"
479 if defined $opt_debug;
480 print STDERR
"Warning: ignoring the obsolete --verbose option\n"
481 if defined $opt_verbose;
483 # tiny getopt emulation for microperl
486 if ($_ eq '--noexec' or $_ eq '-n') {
488 } elsif ($_ eq '--lines' or $_ eq '-l') {
490 } elsif ($_ eq '--fast') {
492 } elsif ($_ eq '--test') {
496 } elsif ($_ eq '--shell') {
497 $option{$_} = 1 foreach qw(shell fast lines);
499 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
506 push @ARGV, $filename;
509 unless (@ARGV == 1) {
511 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
515 open LINES
, ">&STDOUT" if $option{lines
};
516 open STDOUT
, ">&STDERR" if $option{shell
};
518 # microperl can't redirect file handles
521 if ($option{fast
} and not $option{noexec
}) {
522 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
528 open_script
($ARGV[0]);
530 # parse all input recursively
532 die unless @stack == 2;
534 # execute all generated rules
537 foreach my $cmd (@pre_hooks) {
538 print LINES
"$cmd\n" if $option{lines
};
539 system($cmd) unless $option{noexec
};
542 while (my ($domain, $domain_info) = each %domains) {
543 next unless $domain_info->{enabled
};
544 my $s = $option{fast
} &&
545 defined $domain_info->{tools
}{'tables-restore'}
546 ? execute_fast
($domain, $domain_info)
547 : execute_slow
($domain, $domain_info);
548 $status = $s if defined $s;
551 foreach my $cmd (@post_hooks) {
552 print "$cmd\n" if $option{lines
};
553 system($cmd) unless $option{noexec
};
556 if (defined $status) {
561 # ask user, and rollback if there is no confirmation
563 confirm_rules
() or rollback
() if $option{interactive
};
567 # end of program execution!
573 print "ferm $VERSION\n";
574 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
575 print "This program is free software released under GPLv2.\n";
576 print "See the included COPYING file for license details.\n";
588 # returns a nice formatted error message, showing the
589 # location of the error.
593 my @words = map { @
$_ } @
{$script->{past_tokens
}};
595 for my $w ( 0 .. $#words ) {
596 if ($words[$w] eq "\x29")
597 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
598 if ($words[$w] eq "\x28")
599 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
600 if ($words[$w] eq "\x7d")
601 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
602 if ($words[$w] eq "\x7b")
603 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
604 if ( $l > $#lines ) { $lines[$l] = "" };
605 $lines[$l] .= $words[$w] . " ";
606 if ($words[$w] eq "\x28")
607 { $l++ ; $lines[$l] = " " x
$tabs ;};
608 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
609 { $l++ ; $lines[$l] = " " x
$tabs ;};
610 if ($words[$w] eq "\x7b")
611 { $l++ ; $lines[$l] = " " x
$tabs ;};
612 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
613 { $l++ ; $lines[$l] = " " x
$tabs ;};
614 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
615 { $l++ ; $lines[$l] = " " x
$tabs ;}
616 if ($words[$w-1] eq "option")
617 { $l++ ; $lines[$l] = " " x
$tabs ;}
619 my $start = $#lines - 4;
620 if ($start < 0) { $start = 0 } ;
621 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
622 for $l ( $start .. $#lines)
623 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
624 print STDERR
"<--\n";
628 # print a warning message about code from an input file
630 print STDERR
"Warning in $script->{filename} line $script->{line}: "
636 return $name if $option{test
};
637 for my $path ('/sbin', split ':', $ENV{PATH
}) {
638 my $ret = "$path/$name";
639 return $ret if -x
$ret;
641 die "$name not found in PATH\n";
644 sub initialize_domain
{
646 my $domain_info = $domains{$domain} ||= {};
648 return if exists $domain_info->{initialized
};
650 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
652 my @tools = qw(tables);
653 push @tools, qw(tables-save tables-restore)
654 if $domain =~ /^ip6?$/;
656 # determine the location of this domain's tools
657 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
658 $domain_info->{tools
} = \
%tools;
660 # make tables-save tell us about the state of this domain
661 # (which tables and chains do exist?), also remember the old
662 # save data which may be used later by the rollback function
664 if (!$option{test
} &&
665 exists $tools{'tables-save'} &&
666 open(SAVE
, "$tools{'tables-save'}|")) {
675 $table_info = $domain_info->{tables
}{$table} ||= {};
676 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
678 $table_info->{chains
}{$1}{builtin
} = 1;
679 $table_info->{has_builtin
} = 1;
684 $domain_info->{previous
} = $save;
687 $domain_info->{initialized
} = 1;
690 # split the an input string into words and delete comments
691 sub tokenize_string
($) {
696 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
697 last if $word eq '#';
704 # shift an array; helper function to be passed to &getvar / &getvalues
705 sub next_array_token
{
710 # read some more tokens from the input file into a buffer
711 sub prepare_tokens
() {
712 my $tokens = $script->{tokens
};
713 while (@
$tokens == 0) {
714 my $handle = $script->{handle
};
715 my $line = <$handle>;
716 return unless defined $line;
720 # the next parser stage eats this
721 push @
$tokens, @
{tokenize_string
($line)};
727 # open a ferm sub script
729 my $filename = shift;
731 for (my $s = $script; defined $s; $s = $s->{parent
}) {
732 mydie
("Circular reference in $script->{filename} line $script->{line}: $filename")
733 if $s->{filename
} eq $filename;
737 open FILE
, "<$filename"
738 or mydie
("Failed to open $filename: $!");
741 $script = { filename
=> $filename,
752 # collect script filenames which are being included
753 sub collect_filenames
(@
) {
756 # determine the current script's parent directory for relative
758 die unless defined $script;
759 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
762 foreach my $pathname (@_) {
763 # non-absolute file names are relative to the parent script's
765 $pathname = $parent_dir . $pathname
766 unless $pathname =~ m
,^/,;
768 if ($pathname =~ m
,/$,) {
769 # include all regular files in a directory
771 error
("'$pathname' is not a directory")
775 opendir DIR
, $pathname
776 or error
("Failed to open directory '$pathname': $!");
777 my @names = readdir DIR
;
780 # sort those names for a well-defined order
781 foreach my $name (sort { $a cmp $b } @names) {
782 # don't include hidden and backup files
785 my $filename = $pathname . $name;
789 } elsif ($pathname =~ m
,\
|$,) {
790 # run a program and use its output
791 push @ret, $pathname;
792 } elsif ($pathname =~ m
,^\
|,) {
793 error
('This kind of pipe is not allowed');
795 # include a regular file
797 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
799 error
("'$pathname' is not a file")
802 push @ret, $pathname;
809 # peek a token from the queue, but don't remove it
811 return unless prepare_tokens
();
812 return $script->{tokens
}[0];
815 # get a token from the queue
817 return unless prepare_tokens
();
818 my $token = shift @
{$script->{tokens
}};
820 # update $script->{past_tokens}
821 my $past_tokens = $script->{past_tokens
};
823 if (@
$past_tokens > 0) {
824 my $prev_token = $past_tokens->[-1][-1];
825 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
826 if $prev_token eq ';';
828 if $prev_token eq '}';
831 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
832 push @
{$past_tokens->[-1]}, $token;
838 sub expect_token
($;$) {
841 my $token = next_token
();
842 error
($msg || "'$expect' expected")
843 unless defined $token and $token eq $expect;
846 # require that another token exists, and that it's not a "special"
847 # token, e.g. ";" and "{"
848 sub require_next_token
{
849 my $code = shift || \
&next_token
;
851 my $token = &$code(@_);
853 error
('unexpected end of file')
854 unless defined $token;
856 error
("'$token' not allowed here")
857 if $token =~ /^[;{}]$/;
862 # return the value of a variable
863 sub variable_value
($) {
867 return $_->{vars
}{$name}
868 if exists $_->{vars
}{$name};
871 return $stack[0]{auto
}{$name}
872 if exists $stack[0]{auto
}{$name};
877 # determine the value of a variable, die if the value is an array
878 sub string_variable_value
($) {
880 my $value = variable_value
($name);
882 error
("variable '$name' must be a string, but it is an array")
888 # similar to the built-in "join" function, but also handle negated
889 # values in a special way
891 my ($expr, $value) = @_;
893 unless (ref $value) {
895 } elsif (ref $value eq 'ARRAY') {
896 return join($expr, @
$value);
897 } elsif (ref $value eq 'negated') {
898 # bless'negated' is a special marker for negated values
899 $value = join_value
($expr, $value->[0]);
900 return bless [ $value ], 'negated';
906 # returns the next parameter, which may either be a scalar or an array
908 my ($code, $param) = (shift, shift);
911 my $token = require_next_token
($code, $param);
914 # read an array until ")"
918 $token = getvalues
($code, $param,
919 parenthesis_allowed
=> 1,
922 unless (ref $token) {
923 last if $token eq ')';
926 error
('Comma is not allowed within arrays, please use only a space');
930 push @wordlist, $token;
931 } elsif (ref $token eq 'ARRAY') {
932 push @wordlist, @
$token;
934 error
('unknown toke type');
938 error
('empty array not allowed here')
939 unless @wordlist or not $options{non_empty
};
941 return @wordlist == 1
944 } elsif ($token =~ /^\`(.*)\`$/s) {
945 # execute a shell command, insert output
947 my $output = `$command`;
950 error
("failed to execute: $!");
951 } elsif ($?
& 0x7f) {
952 error
("child died with signal " . ($?
& 0x7f));
954 error
("child exited with status " . ($?
>> 8));
959 $output =~ s/#.*//mg;
962 my @tokens = grep { length } split /\s+/s, $output;
966 my $value = getvalues
(\
&next_array_token
, \
@tokens);
967 push @values, to_array
($value);
974 } elsif ($token =~ /^\'(.*)\'$/s) {
975 # single quotes: a string
977 } elsif ($token =~ /^\"(.*)\"$/s) {
978 # double quotes: a string with escapes
980 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
982 } elsif ($token eq '!') {
983 error
('negation is not allowed here')
984 unless $options{allow_negation
};
986 $token = getvalues
($code, $param);
988 error
('it is not possible to negate an array')
989 if ref $token and not $options{allow_array_negation
};
991 return bless [ $token ], 'negated';
992 } elsif ($token eq ',') {
994 if $options{comma_allowed
};
996 error
('comma is not allowed here');
997 } elsif ($token eq '=') {
998 error
('equals operator ("=") is not allowed here');
999 } elsif ($token eq '$') {
1000 my $name = require_next_token
($code, $param);
1001 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1002 unless $name =~ /^\w+$/;
1004 my $value = variable_value
($name);
1006 error
("no such variable: \$$name")
1007 unless defined $value;
1010 } elsif ($token eq '&') {
1011 error
("function calls are not allowed as keyword parameter");
1012 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1013 error
('Syntax error');
1014 } elsif ($token =~ /^@/) {
1015 if ($token eq '@resolve') {
1016 my @params = get_function_params
();
1017 error
('Usage: @resolve((hostname ...))')
1018 unless @params == 1;
1019 eval { require Net
::DNS
; };
1020 error
('For the @resolve() function, you need the Perl library Net::DNS')
1023 my $resolver = new Net
::DNS
::Resolver
;
1025 foreach my $hostname (to_array
($params[0])) {
1026 my $query = $resolver->search($hostname, $type);
1027 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
1029 foreach my $rr ($query->answer) {
1030 next unless $rr->type eq $type;
1031 push @result, $rr->address;
1036 error
("unknown ferm built-in function");
1043 # returns the next parameter, but only allow a scalar
1045 my $token = getvalues
(@_);
1047 error
('array not allowed here')
1048 if ref $token and ref $token eq 'ARRAY';
1053 sub get_function_params
(%) {
1054 expect_token
('(', 'function name must be followed by "()"');
1056 my $token = peek_token
();
1057 if ($token eq ')') {
1066 $token = require_next_token
();
1070 error
('"," expected')
1071 unless $token eq ',';
1074 push @params, getvalues
(undef, undef, @_);
1080 # collect all tokens in a flat array reference until the end of the
1081 # command is reached
1082 sub collect_tokens
() {
1087 my $keyword = next_token
();
1088 error
('unexpected end of file within function/variable declaration')
1089 unless defined $keyword;
1091 if ($keyword =~ /^[\{\(]$/) {
1092 push @level, $keyword;
1093 } elsif ($keyword =~ /^[\}\)]$/) {
1094 my $expected = $keyword;
1095 $expected =~ tr/\}\)/\{\(/;
1096 my $opener = pop @level;
1097 error
("unmatched '$keyword'")
1098 unless defined $opener and $opener eq $expected;
1099 } elsif ($keyword eq ';' and @level == 0) {
1103 push @tokens, $keyword;
1106 if $keyword eq '}' and @level == 0;
1113 # returns the specified value as an array. dereference arrayrefs
1116 die unless wantarray;
1118 unless (ref $value) {
1120 } elsif (ref $value eq 'ARRAY') {
1127 # evaluate the specified value as bool
1132 unless (ref $value) {
1134 } elsif (ref $value eq 'ARRAY') {
1141 sub is_netfilter_core_target
($) {
1143 die unless defined $target and length $target;
1145 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1148 sub is_netfilter_module_target
($$) {
1149 my ($domain_family, $target) = @_;
1150 die unless defined $target and length $target;
1152 return defined $domain_family &&
1153 exists $target_defs{$domain_family} &&
1154 $target_defs{$domain_family}{$target};
1157 sub is_netfilter_builtin_chain
($$) {
1158 my ($table, $chain) = @_;
1160 return grep { $_ eq $chain }
1161 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1164 sub netfilter_canonical_protocol
($) {
1167 if $proto eq 'ipv6-icmp';
1169 if $proto eq 'ipv6-mh';
1173 sub netfilter_protocol_module
($) {
1175 return unless defined $proto;
1177 if $proto eq 'icmpv6';
1181 # escape the string in a way safe for the shell
1182 sub shell_escape
($) {
1185 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1187 if ($option{fast
}) {
1188 # iptables-save/iptables-restore are quite buggy concerning
1189 # escaping and special characters... we're trying our best
1193 $token = '"' . $token . '"'
1194 if $token =~ /[\s\'\\;&]/s;
1197 if $token =~ /^\`.*\`$/;
1198 $token =~ s/'/\\'/g;
1199 $token = '\'' . $token . '\''
1200 if $token =~ /[\s\"\\;<>&|]/s;
1206 # append an option to the shell command line, using information from
1207 # the module definition (see %match_defs etc.)
1208 sub shell_append_option($$$) {
1209 my ($ref, $keyword, $value) = @_;
1212 if (ref $value eq 'negated') {
1213 $value = $value->[0];
1215 } elsif (ref $value eq 'pre_negated') {
1216 $value = $value->[0];
1221 unless (defined $value) {
1222 $$ref .= " --$keyword";
1223 } elsif (ref $value) {
1224 if (ref $value eq 'params') {
1225 $$ref .= " --$keyword ";
1226 $$ref .= join(' ', map { shell_escape($_) } @$value);
1227 } elsif (ref $value eq 'multi') {
1229 $$ref .= " --$keyword " . shell_escape($_);
1235 $$ref .= " --$keyword " . shell_escape($value);
1239 # convert an internal rule structure into an iptables call
1241 my ($table_info, $chain_info, $rule) = @_;
1243 return if $option{flush};
1245 # return if this is a declaration-only rule
1247 unless $rule->{has_rule};
1251 # general iptables options
1253 foreach my $option (@{$rule->{options}}) {
1254 shell_append_option(\$rr, $option->[0], $option->[1]);
1258 my $chain_rules = $chain_info->{rules} ||= [];
1259 push @$chain_rules, { rule => $rr,
1260 script => $rule->{script},
1264 sub transform_rule($$) {
1265 my ($domain, $rule) = @_;
1267 $rule->{options}[$rule->{protocol_index}][1] = 'icmpv6'
1268 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1271 sub printrule($$$$) {
1272 my ($domain, $table, $chain, $rule) = @_;
1274 transform_rule($domain, $rule);
1276 my $domain_info = $domains{$domain};
1277 $domain_info->{enabled} = 1;
1278 my $table_info = $domain_info->{tables}{$table} ||= {};
1279 my $chain_info = $table_info->{chains}{$chain} ||= {};
1281 # prints all rules in a hash
1282 tables($table_info, $chain_info, $rule);
1286 sub check_unfold(\@$$) {
1287 my ($unfold, $parent, $key) = @_;
1289 return unless ref $parent->{$key} and
1290 ref $parent->{$key} eq 'ARRAY';
1292 push @$unfold, $parent, $key, $parent->{$key};
1295 sub mkrules2($$$$) {
1296 my ($domain, $table, $chain, $fw) = @_;
1299 foreach my $option (@{$fw->{options}}) {
1300 push @unfold, $option
1301 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1305 printrule($domain, $table, $chain, $fw);
1311 my ($domain, $table, $chain) = (shift, shift, shift);
1313 my @values = @{$option->[1]};
1315 foreach my $value (@values) {
1316 $option->[1] = $value;
1317 $fw->{protocol} = $value if $option->[0] eq 'protocol';
1320 dofr($fw, $domain, $table, $chain, @_);
1322 printrule($domain, $table, $chain, $fw);
1327 dofr($fw, $domain, $table, $chain, @unfold);
1330 # convert a bunch of internal rule structures in iptables calls,
1331 # unfold arrays during that
1335 foreach my $domain (to_array $fw->{domain}) {
1336 foreach my $table (to_array $fw->{table}) {
1337 foreach my $chain (to_array $fw->{chain}) {
1338 mkrules2($domain, $table, $chain, $fw);
1344 sub filter_domains($) {
1345 my $domains = shift;
1348 foreach my $domain (to_array $domains) {
1349 next if exists $option{domain}
1350 and $domain ne $option{domain};
1353 initialize_domain($domain);
1357 push @$result, $domain;
1360 return @$result == 1 ? $result->[0] : $result;
1363 # parse a keyword from a module definition
1364 sub parse_keyword($$$$) {
1365 my ($current, $def, $keyword, $negated_ref) = @_;
1367 my $params = $def->{params};
1372 if ($$negated_ref && exists $def->{pre_negation}) {
1374 undef $$negated_ref;
1377 unless (defined $params) {
1379 } elsif (ref $params && ref $params eq 'CODE') {
1380 $value = &$params($current);
1381 } elsif ($params eq 'm') {
1382 $value = bless [ to_array getvalues() ], 'multi';
1383 } elsif ($params =~ /^[a-z]/) {
1384 if (exists $def->{negation} and not $negated) {
1385 my $token = peek_token();
1386 if ($token eq '!') {
1393 foreach my $p (split(//, $params)) {
1395 push @params, getvar();
1396 } elsif ($p eq 'c') {
1397 my @v = to_array getvalues(undef, undef,
1399 push @params, join(',', @v);
1405 $value = @params == 1
1407 : bless \@params, 'params';
1408 } elsif ($params == 1) {
1409 if (exists $def->{negation} and not $negated) {
1410 my $token = peek_token();
1411 if ($token eq '!') {
1417 $value = getvalues();
1419 warning("log-prefix is too long
; truncating to
29 characters
: '$1'")
1420 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1422 if (exists $def->{negation} and not $negated) {
1423 my $token = peek_token();
1424 if ($token eq '!') {
1430 $value = bless [ map {
1432 } (1..$params) ], 'params';
1435 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1441 sub append_option(\%$$) {
1442 my ($rule, $name, $value) = @_;
1443 push @{$rule->{options}}, [ $name, $value ];
1446 # parse options of a module
1447 sub parse_option($$$$) {
1448 my ($def, $current, $keyword, $negated_ref) = @_;
1450 while (exists $def->{alias}) {
1451 ($keyword, $def) = @{$def->{alias}};
1452 die unless defined $def;
1455 append_option(%$current, $keyword,
1456 parse_keyword($current, $def, $keyword, $negated_ref));
1460 sub copy_on_write($$) {
1461 my ($rule, $key) = @_;
1462 return unless exists $rule->{cow}{$key};
1463 $rule->{$key} = {%{$rule->{$key}}};
1464 delete $rule->{cow}{$key};
1467 sub new_level(\%$) {
1468 my ($current, $prev) = @_;
1471 if (defined $prev) {
1472 # copy data from previous level
1473 $current->{cow} = { keywords => 1, };
1474 $current->{keywords} = $prev->{keywords};
1475 $current->{match} = { %{$prev->{match}} };
1476 $current->{options} = [@{$prev->{options}}];
1477 foreach my $key (qw(domain domain_family table chain protocol protocol_index has_action)) {
1478 $current->{$key} = $prev->{$key}
1479 if exists $prev->{$key};
1482 $current->{cow
} = {};
1483 $current->{keywords
} = {};
1484 $current->{match
} = {};
1485 $current->{options
} = [];
1489 sub merge_keywords
(\
%$) {
1490 my ($rule, $keywords) = @_;
1491 copy_on_write
($rule, 'keywords');
1492 while (my ($name, $def) = each %$keywords) {
1493 $rule->{keywords
}{$name} = $def;
1497 sub set_domain
(\
%$) {
1498 my ($rule, $domain) = @_;
1500 my $filtered_domain = filter_domains
($domain);
1502 unless (ref $domain) {
1503 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1504 } elsif (@
$domain == 0) {
1505 $domain_family = 'none';
1506 } elsif (grep { not /^ip6?$/s } @
$domain) {
1507 error
('Cannot combine non-IP domains');
1509 $domain_family = 'ip';
1512 $rule->{domain_family
} = $domain_family;
1513 $rule->{keywords
} = {%{$match_defs{$domain_family}{''}{keywords
}}};
1514 delete $rule->{cow
}{keywords
};
1516 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $filtered_domain;
1519 sub set_module_target
(\
%$$) {
1520 my ($rule, $name, $defs) = @_;
1522 if ($name eq 'TCPMSS') {
1523 my $protos = $rule->{protocol
};
1524 error
('No protocol specified before TCPMSS')
1525 unless defined $protos;
1526 foreach my $proto (to_array
$protos) {
1527 error
('TCPMSS not available for protocol "$proto"')
1528 unless $proto eq 'tcp';
1532 merge_keywords
(%$rule, $defs->{keywords
});
1535 # the main parser loop: read tokens, convert them into internal rule
1538 my $lev = shift; # current recursion depth
1539 my $prev = shift; # previous rule hash
1541 # enter is the core of the firewall setup, it is a
1542 # simple parser program that recognizes keywords and
1543 # retreives parameters to set up the kernel routing
1546 my $base_level = $script->{base_level
} || 0;
1547 die if $base_level > $lev;
1550 new_level
(%current, $prev);
1552 # read keywords 1 by 1 and dump into parser
1553 while (defined (my $keyword = next_token
())) {
1554 # check if the current rule should be negated
1555 my $negated = $keyword eq '!';
1557 # negation. get the next word which contains the 'real'
1559 $keyword = getvar
();
1561 error
('unexpected end of file after negation')
1562 unless defined $keyword;
1565 # the core: parse all data
1568 # deprecated keyword?
1569 if (exists $deprecated_keywords{$keyword}) {
1570 my $new_keyword = $deprecated_keywords{$keyword};
1571 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1572 $keyword = $new_keyword;
1575 # effectuation operator
1576 if ($keyword eq ';') {
1577 if ($current{has_rule
} and not exists $current{has_action
}) {
1578 # something is wrong when a rule was specifiedd,
1580 error
('No action defined; did you mean "NOP"?');
1583 error
('No chain defined') unless exists $current{chain
};
1585 $current{script
} = { filename
=> $script->{filename
},
1586 line
=> $script->{line
},
1591 # and clean up variables set in this level
1592 new_level
(%current, $prev);
1597 # conditional expression
1598 if ($keyword eq '@if') {
1599 unless (eval_bool
(getvalues
)) {
1601 my $token = peek_token
();
1602 require_next_token
() if $token and $token eq '@else';
1608 if ($keyword eq '@else') {
1609 # hack: if this "else" has not been eaten by the "if"
1610 # handler above, we believe it came from an if clause
1611 # which evaluated "true" - remove the "else" part now.
1616 # hooks for custom shell commands
1617 if ($keyword eq 'hook') {
1618 error
('"hook" must be the first token in a command')
1619 if exists $current{domain
};
1621 my $position = getvar
();
1623 if ($position eq 'pre') {
1624 $hooks = \
@pre_hooks;
1625 } elsif ($position eq 'post') {
1626 $hooks = \
@post_hooks;
1628 error
("Invalid hook position: '$position'");
1631 push @
$hooks, getvar
();
1637 # recursing operators
1638 if ($keyword eq '{') {
1640 my $old_stack_depth = @stack;
1642 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1645 enter
($lev + 1, \
%current);
1649 die unless @stack == $old_stack_depth;
1651 # after a block, the command is finished, clear this
1653 new_level
(%current, $prev);
1658 if ($keyword eq '}') {
1659 error
('Unmatched "}"')
1660 if $lev <= $base_level;
1662 # consistency check: check if they havn't forgotten
1663 # the ';' before the last statement
1664 error
('Missing semicolon before "}"')
1665 if $current{has_rule
};
1671 # include another file
1672 if ($keyword eq '@include' or $keyword eq 'include') {
1673 my @files = collect_filenames to_array getvalues
;
1674 $keyword = next_token
;
1675 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1676 unless defined $keyword and $keyword eq ';';
1678 foreach my $filename (@files) {
1679 # save old script, open new script
1680 my $old_script = $script;
1681 open_script
($filename);
1682 $script->{base_level
} = $lev + 1;
1685 my $old_stack_depth = @stack;
1690 # include files may set variables for their parent
1691 $stack->{vars
} = ($stack[0]{vars
} ||= {});
1692 $stack->{functions
} = ($stack[0]{functions
} ||= {});
1693 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
1696 unshift @stack, $stack;
1699 enter
($lev + 1, \
%current);
1703 die unless @stack == $old_stack_depth;
1705 # restore old script
1706 $script = $old_script;
1712 # definition of a variable or function
1713 if ($keyword eq '@def' or $keyword eq 'def') {
1714 error
('"def" must be the first token in a command')
1715 if $current{has_rule
};
1717 my $type = require_next_token
();
1719 my $name = require_next_token
();
1720 error
('invalid variable name')
1721 unless $name =~ /^\w+$/;
1725 my $value = getvalues
(undef, undef, allow_negation
=> 1);
1729 $stack[0]{vars
}{$name} = $value
1730 unless exists $stack[-1]{vars
}{$name};
1731 } elsif ($type eq '&') {
1732 my $name = require_next_token
();
1733 error
('invalid function name')
1734 unless $name =~ /^\w+$/;
1736 expect_token
('(', 'function parameter list or "()" expected');
1740 my $token = require_next_token
();
1741 last if $token eq ')';
1744 error
('"," expected')
1745 unless $token eq ',';
1747 $token = require_next_token
();
1750 error
('"$" and parameter name expected')
1751 unless $token eq '$';
1753 $token = require_next_token
();
1754 error
('invalid function parameter name')
1755 unless $token =~ /^\w+$/;
1757 push @params, $token;
1762 $function{params
} = \
@params;
1766 my $tokens = collect_tokens
();
1767 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
1768 $function{tokens
} = $tokens;
1770 $stack[0]{functions
}{$name} = \
%function
1771 unless exists $stack[-1]{functions
}{$name};
1773 error
('"$" (variable) or "&" (function) expected');
1780 if ($keyword eq '$') {
1781 error
('variable references are only allowed as keyword parameter');
1784 if ($keyword eq '&') {
1785 my $name = require_next_token
;
1786 error
('function name expected')
1787 unless $name =~ /^\w+$/;
1791 $function = $_->{functions
}{$name};
1792 last if defined $function;
1794 error
("no such function: \&$name")
1795 unless defined $function;
1797 my $paramdef = $function->{params
};
1798 die unless defined $paramdef;
1800 my @params = get_function_params
(allow_negation
=> 1);
1802 error
("Wrong number of parameters for function '\&$name': "
1803 . @
$paramdef . " expected, " . @params . " given")
1804 unless @params == @
$paramdef;
1807 for (my $i = 0; $i < @params; $i++) {
1808 $vars{$paramdef->[$i]} = $params[$i];
1811 if ($function->{block
}) {
1812 # block {} always ends the current rule, so if the
1813 # function contains a block, we have to require
1814 # the calling rule also ends here
1818 my @tokens = @
{$function->{tokens
}};
1819 for (my $i = 0; $i < @tokens; $i++) {
1820 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1821 exists $vars{$tokens[$i + 1]}) {
1822 my @value = to_array
($vars{$tokens[$i + 1]});
1823 @value = ('(', @value, ')')
1824 unless @tokens == 1;
1825 splice(@tokens, $i, 2, @value);
1827 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
1828 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
1832 unshift @
{$script->{tokens
}}, @tokens;
1837 # where to put the rule?
1838 if ($keyword eq 'domain') {
1839 error
('Domain is already specified')
1840 if exists $current{domain
};
1842 set_domain
(%current, getvalues
());
1846 if ($keyword eq 'table') {
1847 error
('Table is already specified')
1848 if exists $current{table
};
1849 $current{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
1851 set_domain
(%current, 'ip')
1852 unless exists $current{domain
};
1857 if ($keyword eq 'chain') {
1858 error
('Chain is already specified')
1859 if exists $current{chain
};
1860 $current{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
1862 # ferm 1.1 allowed lower case built-in chain names
1863 foreach (ref $current{chain
} ? @
{$current{chain
}} : $current{chain
}) {
1864 error
('Please write built-in chain names in upper case')
1865 if /^(?:input|forward|output|prerouting|postrouting)$/;
1868 set_domain
(%current, 'ip')
1869 unless exists $current{domain
};
1871 $current{table
} = 'filter'
1872 unless exists $current{table
};
1877 error
('Chain must be specified')
1878 unless exists $current{chain
};
1880 # policy for built-in chain
1881 if ($keyword eq 'policy') {
1882 error
('Cannot specify matches for policy')
1883 if $current{has_rule
};
1885 my $policy = getvar
();
1886 error
("Invalid policy target: $policy")
1887 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1891 foreach my $domain (to_array
$current{domain
}) {
1892 foreach my $table (to_array
$current{table
}) {
1893 foreach my $chain (to_array
$current{chain
}) {
1894 $domains{$domain}{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
1899 new_level
(%current, $prev);
1904 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1905 error
('Chain must be specified')
1906 unless exists $current{chain
};
1908 error
('No rule specified before "@subchain"')
1909 unless $current{has_rule
};
1912 $keyword = next_token
();
1914 if ($keyword =~ /^(["'])(.*)\1$/s) {
1916 $keyword = next_token
();
1918 $subchain = 'ferm_auto_' . ++$auto_chain;
1921 error
('"{" or chain name expected after "@subchain"')
1922 unless $keyword eq '{';
1924 # create a deep copy of %current, only containing values
1925 # which must be in the subchain
1926 my %inner = ( cow
=> { keywords
=> 1, },
1927 keywords
=> $current{keywords
},
1931 $inner{domain
} = $current{domain
};
1932 $inner{domain_family
} = $current{domain_family
};
1933 $inner{table
} = $current{table
};
1934 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
1936 if (exists $current{protocol
}) {
1937 $inner{protocol
} = $current{protocol
};
1938 $inner{protocol_index
} = 0;
1939 append_option
(%inner, 'protocol', $inner{protocol
});
1945 # now handle the parent - it's a jump to the sub chain
1946 $current{has_action
} = 1;
1947 append_option
(%current, 'jump', $subchain);
1949 $current{script
} = { filename
=> $script->{filename
},
1950 line
=> $script->{line
},
1955 # and clean up variables set in this level
1956 new_level
(%current, $prev);
1961 # everything else must be part of a "real" rule, not just
1963 $current{has_rule
}++;
1965 # extended parameters:
1966 if ($keyword =~ /^mod(?:ule)?$/) {
1967 foreach my $module (to_array getvalues
) {
1968 next if exists $current{match
}{$module};
1970 my $domain_family = $current{domain_family
};
1971 my $defs = $match_defs{$domain_family}{$module};
1973 append_option
(%current, 'match', $module);
1974 $current{match
}{$module} = 1;
1976 merge_keywords
(%current, $defs->{keywords
})
1983 # keywords from $current{keywords}
1985 if (exists $current{keywords
}{$keyword}) {
1986 my $def = $current{keywords
}{$keyword};
1987 parse_option
($def, \
%current, $keyword, \
$negated);
1996 if ($keyword eq 'jump') {
1997 error
('There can only one action per rule')
1998 if exists $current{has_action
};
1999 my $chain = getvar
();
2000 if (my $defs = is_netfilter_module_target
($current{domain_family
}, $chain)) {
2001 set_module_target
(%current, $chain, $defs);
2003 $current{has_action
} = 1;
2004 append_option
(%current, 'jump', $chain);
2009 if ($keyword eq 'realgoto') {
2010 error
('There can only one action per rule')
2011 if exists $current{has_action
};
2012 append_option
(%current, 'goto', getvar
());
2013 $current{has_action
} = 1;
2018 if (is_netfilter_core_target
($keyword)) {
2019 error
('There can only one action per rule')
2020 if exists $current{has_action
};
2021 $current{has_action
} = 1;
2022 append_option
(%current, 'jump', $keyword);
2026 if ($keyword eq 'NOP') {
2027 error
('There can only one action per rule')
2028 if exists $current{has_action
};
2029 $current{has_action
} = 1;
2033 if (my $defs = is_netfilter_module_target
($current{domain_family
}, $keyword)) {
2034 error
('There can only one action per rule')
2035 if exists $current{has_action
};
2037 set_module_target
(%current, $keyword, $defs);
2038 $current{has_action
} = 1;
2039 append_option
(%current, 'jump', $keyword);
2043 my $proto = $current{protocol
};
2046 # protocol specific options
2049 if ($keyword eq 'proto') {
2050 my $protocol = parse_keyword
(\
%current,
2051 { params
=> 1, negation
=> 1 },
2052 'proto', \
$negated);
2053 $current{protocol
} = $protocol;
2054 $current{protocol_index
} = scalar(@
{$current{options
}});
2055 append_option
(%current, 'protocol', $current{protocol
});
2057 unless (ref $protocol) {
2058 $protocol = netfilter_canonical_protocol
($protocol);
2059 my $domain_family = $current{domain_family
};
2060 my $defs = $proto_defs{$domain_family}{$protocol};
2061 if (defined $defs) {
2062 merge_keywords
(%current, $defs->{keywords
});
2063 my $module = netfilter_protocol_module
($protocol);
2064 $current{match
}{$module} = 1;
2071 if ($keyword =~ /^[sd]port$/) {
2072 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2073 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2075 append_option
(%current, $keyword,
2076 getvalues
(undef, undef,
2077 allow_negation
=> 1));
2082 error
("Unrecognized keyword: $keyword");
2085 # if the rule didn't reset the negated flag, it's not
2087 error
("Doesn't support negation: $keyword")
2091 error
('Missing "}" at end of file')
2092 if $lev > $base_level;
2094 # consistency check: check if they havn't forgotten
2095 # the ';' before the last statement
2096 error
("Missing semicolon before end of file")
2097 if exists $current{domain
};
2100 sub execute_command
{
2101 my ($command, $script) = @_;
2103 print LINES
"$command\n"
2105 return if $option{noexec
};
2107 my $ret = system($command);
2108 unless ($ret == 0) {
2110 print STDERR
"failed to execute: $!\n";
2112 } elsif ($?
& 0x7f) {
2113 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2116 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2125 sub execute_slow
($$) {
2126 my ($domain, $domain_info) = @_;
2128 my $domain_cmd = $domain_info->{tools
}{tables
};
2131 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2132 my $table_cmd = "$domain_cmd -t $table";
2134 # reset chain policies
2135 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2136 next unless $chain_info->{builtin
} or
2137 (not $table_info->{has_builtin
} and
2138 is_netfilter_builtin_chain
($table, $chain));
2139 $status ||= execute_command
("$table_cmd -P $chain ACCEPT")
2140 unless $option{noflush
};
2144 unless ($option{noflush
}) {
2145 $status ||= execute_command
("$table_cmd -F");
2146 $status ||= execute_command
("$table_cmd -X");
2149 next if $option{flush
};
2151 # create chains / set policy
2152 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2153 if (exists $chain_info->{policy
}) {
2154 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2155 unless $chain_info->{policy
} eq 'ACCEPT';
2156 } elsif (not is_netfilter_builtin_chain
($table, $chain)) {
2157 $status ||= execute_command
("$table_cmd -N $chain");
2162 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2163 my $chain_cmd = "$table_cmd -A $chain";
2164 foreach my $rule (@
{$chain_info->{rules
}}) {
2165 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2173 sub rules_to_save
($$) {
2174 my ($domain, $domain_info) = @_;
2176 # convert this into an iptables-save text
2177 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2179 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2181 $result .= '*' . $table . "\n";
2183 # create chains / set policy
2184 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2185 my $chain_info = $table_info->{chains
}{$chain};
2186 my $policy = $option{flush
} ?
'ACCEPT' : $chain_info->{policy
};
2187 unless (defined $policy) {
2188 if (is_netfilter_builtin_chain
($table, $chain)) {
2194 $result .= ":$chain $policy\ [0:0]\n";
2197 next if $option{flush
};
2200 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2201 my $chain_info = $table_info->{chains
}{$chain};
2202 foreach my $rule (@
{$chain_info->{rules
}}) {
2203 $result .= "-A $chain$rule->{rule}\n";
2208 $result .= "COMMIT\n";
2214 sub restore_domain
($$) {
2215 my ($domain, $save) = @_;
2217 my $path = $domains{$domain}{tools
}{'tables-restore'};
2220 open RESTORE
, "|$path"
2221 or die "Failed to run $path: $!\n";
2223 print RESTORE
$save;
2226 or die "Failed to run $path\n";
2229 sub execute_fast
($$) {
2230 my ($domain, $domain_info) = @_;
2232 my $save = rules_to_save
($domain, $domain_info);
2234 if ($option{lines
}) {
2235 print LINES
"$domain_info->{tools}{'tables-restore'} <<EOT\n"
2242 return if $option{noexec};
2245 restore_domain($domain, $save);
2257 while (my ($domain, $domain_info) = each %domains) {
2258 next unless $domain_info->{enabled};
2259 unless (defined $domain_info->{tools}{'tables-restore'}) {
2260 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2265 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2266 my $reset_chain = '';
2267 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2268 next unless is_netfilter_builtin_chain($table, $chain);
2269 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2271 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2272 if length $reset_chain;
2275 $reset .= $domain_info->{previous}
2276 if defined $domain_info->{previous};
2278 restore_domain($domain, $reset);
2281 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2286 # do nothing, just interrupt a system call
2289 sub confirm_rules() {
2290 $SIG{ALRM} = \&alrm_handler;
2295 . "ferm has applied the new firewall rules
.\n"
2296 . "Please type
'yes' to confirm
:\n";
2302 STDIN->sysread($line, 3);
2306 POSIX::tcflush(*STDIN, 2);
2308 print STDERR "$@
" if $@;
2310 $SIG{ALRM} = 'DEFAULT';
2312 return $line eq 'yes';
2321 ferm - a firewall rule parser for linux
2325 B<ferm> I<options> I<inputfiles>
2329 -n, --noexec Do not execute the rules, just simulate
2330 -F, --flush Flush all netfilter tables managed by ferm
2331 -l, --lines Show all rules that were created
2332 -i, --interactive Interactive mode: revert if user does not confirm
2333 --remote Remote mode; ignore host specific configuration.
2334 This implies --noexec and --lines.
2335 -V, --version Show current version number
2336 -h, --help Look at this text
2337 --fast Generate an iptables-save file, used by iptables-restore
2338 --shell Generate a shell script which calls iptables-restore
2339 --domain {ip|ip6} Handle only the specified domain
2340 --def '$name=v' Override a variable