4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2010 Max Kellermann, Auke Kok
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 eval { require strict
; import strict
; };
36 # we need no vars.pm if there is not even strict.pm
38 *vars
::import
= sub {};
43 eval { require Getopt
::Long
; import Getopt
::Long
; };
47 use vars
qw($has_strict $has_getopt);
49 use vars qw($VERSION);
54 ## interface variables
55 # %option = command line and other options
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
113 # u32=m an array which renders into multiple iptables options in one
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # add a module definition
139 my $domain_family = shift;
140 my $params_default = shift;
142 die if exists $defs->{$domain_family}{$name};
143 my $def = $defs->{$domain_family}{$name} = {};
148 if ($keyword =~ s,:=(\S+)$,,) {
149 $k = $def->{keywords}{$1} || die;
150 $k->{ferm_name} ||= $keyword;
152 my $params = $params_default;
153 $params = $1 if $keyword =~ s,\*(\d+)$,,;
154 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
155 if ($keyword =~ s,&(\S+)$,,) {
156 $params = eval "\\&$1";
161 $k->{params} = $params if $params;
163 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
164 $k->{negation} = 1 if $keyword =~ s,!$,,;
165 $k->{name} = $keyword;
168 $def->{keywords}{$keyword} = $k;
174 # add a protocol module definition
175 sub add_proto_def_x(@) {
176 my $domain_family = shift;
177 add_def_x(\%proto_defs, $domain_family, 1, @_);
180 # add a match module definition
181 sub add_match_def_x(@) {
182 my $domain_family = shift;
183 add_def_x(\%match_defs, $domain_family, 1, @_);
186 # add a target module definition
187 sub add_target_def_x(@) {
188 my $domain_family = shift;
189 add_def_x(\%target_defs, $domain_family, 's', @_);
194 add_def_x($defs, 'ip', @_);
197 # add a protocol module definition
198 sub add_proto_def(@) {
199 add_def(\%proto_defs, 1, @_);
202 # add a match module definition
203 sub add_match_def(@) {
204 add_def(\%match_defs, 1, @_);
207 # add a target module definition
208 sub add_target_def(@) {
209 add_def(\%target_defs, 's', @_);
212 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
213 add_proto_def
'mh', qw(mh-type!);
214 add_proto_def
'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
215 add_proto_def
'sctp', qw(chunk-types!=sc);
216 add_proto_def
'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
217 add_proto_def
'udp', qw();
220 # --source, --destination
221 qw(source! saddr:=source destination! daddr:=destination),
223 qw(in-interface! interface:=in-interface if:=in-interface),
225 qw(out-interface! outerface:=out-interface of:=out-interface),
228 add_match_def
'account', qw(aaddr=s aname=s ashort*0);
229 add_match_def
'addrtype', qw(!src-type !dst-type),
230 qw(limit-iface-in*0 limit-iface-out*0);
231 add_match_def
'ah', qw(ahspi! ahlen! ahres*0);
232 add_match_def
'comment', qw(comment=s);
233 add_match_def
'condition', qw(condition!);
234 add_match_def
'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
235 add_match_def
'connlimit', qw(!connlimit-above connlimit-mask);
236 add_match_def
'connmark', qw(!mark);
237 add_match_def
'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst!),
238 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
239 add_match_def
'dscp', qw(dscp dscp-class);
240 add_match_def
'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
241 add_match_def
'esp', qw(espspi!);
242 add_match_def
'eui64';
243 add_match_def
'fuzzy', qw(lower-limit=s upper-limit=s);
244 add_match_def
'hbh', qw(hbh-len! hbh-opts=c);
245 add_match_def
'helper', qw(helper);
246 add_match_def
'hl', qw(hl-eq! hl-lt=s hl-gt=s);
247 add_match_def
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
248 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
249 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
250 add_match_def
'iprange', qw(!src-range !dst-range);
251 add_match_def
'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
252 add_match_def
'ipv6header', qw(header!=c soft*0);
253 add_match_def
'length', qw(length!);
254 add_match_def
'limit', qw(limit=s limit-burst=s);
255 add_match_def
'mac', qw(mac-source!);
256 add_match_def
'mark', qw(!mark);
257 add_match_def
'multiport', qw(source-ports!&multiport_params),
258 qw(destination-ports!&multiport_params ports!&multiport_params);
259 add_match_def
'nth', qw(every counter start packet);
260 add_match_def
'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
261 qw(cmd-owner !socket-exists=0);
262 add_match_def
'physdev', qw(physdev-in! physdev-out!),
263 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
264 add_match_def
'pkttype', qw(pkt-type!),
265 add_match_def
'policy',
266 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
267 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
268 qw(psd-lo-ports-weight psd-hi-ports-weight);
269 add_match_def
'quota', qw(quota=s);
270 add_match_def
'random', qw(average);
271 add_match_def
'realm', qw(realm!);
272 add_match_def
'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
273 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
274 add_match_def
'set', qw(!set=sc);
275 add_match_def
'state', qw(!state=c);
276 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
277 add_match_def
'string', qw(algo=s from=s to=s string hex-string);
278 add_match_def
'tcpmss', qw(!mss);
279 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
280 qw(!monthday=c !weekdays=c utc*0 localtz*0);
281 add_match_def
'tos', qw(!tos);
282 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
283 add_match_def
'u32', qw(!u32=m);
285 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
286 add_target_def
'CLASSIFY', qw(set-class);
287 add_target_def
'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
288 add_target_def
'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
289 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
290 add_target_def
'DNAT', qw(to-destination=m to:=to-destination random*0);
291 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
292 add_target_def
'ECN', qw(ecn-tcp-remove*0);
293 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
294 add_target_def
'IPV4OPTSSTRIP';
295 add_target_def
'LOG', qw(log-level log-prefix),
296 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
297 add_target_def
'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
298 add_target_def
'MASQUERADE', qw(to-ports random*0);
299 add_target_def
'MIRROR';
300 add_target_def
'NETMAP', qw(to);
301 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
302 add_target_def
'NFQUEUE', qw(queue-num);
303 add_target_def
'NOTRACK';
304 add_target_def
'REDIRECT', qw(to-ports random*0);
305 add_target_def
'REJECT', qw(reject-with);
306 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
307 add_target_def
'SAME', qw(to nodst*0 random*0);
308 add_target_def
'SECMARK', qw(selctx);
309 add_target_def
'SET', qw(add-set=sc del-set=sc);
310 add_target_def
'SNAT', qw(to-source=m to:=to-source random*0);
311 add_target_def
'TARPIT';
312 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
313 add_target_def
'TOS', qw(set-tos and-tos or-tos xor-tos);
314 add_target_def
'TRACE';
315 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
316 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
318 add_match_def_x
'arp', '',
320 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
322 qw(source-mac! destination-mac!),
324 qw(in-interface! interface:=in-interface if:=in-interface),
326 qw(out-interface! outerface:=out-interface of:=out-interface),
328 qw(h-length=s opcode=s h-type=s proto-type=s),
329 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
331 add_match_def_x
'eb', '',
333 qw(protocol! proto:=protocol),
335 qw(in-interface! interface:=in-interface if:=in-interface),
337 qw(out-interface! outerface:=out-interface of:=out-interface),
339 qw(logical-in! logical-out!),
340 # --source, --destination
341 qw(source! saddr:=source destination! daddr:=destination),
343 qw(802_3-sap! 802_3-type!),
345 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
346 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
348 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
354 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
355 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
356 qw(stp-hello-time! stp-forward-delay!),
358 qw(vlan-id! vlan-prio! vlan-encap!),
360 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
362 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
363 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
364 add_target_def_x
'eb', 'MARK', qw(set-mark mark-target);
365 add_target_def_x
'eb', 'redirect', qw(redirect-target);
366 add_target_def_x
'eb', 'snat', qw(to-source snat-target snat-arp*0);
368 # import-ferm uses the above tables
369 return 1 if $0 =~ /import-ferm$/;
371 # parameter parser for ipt_multiport
372 sub multiport_params
{
375 # multiport only allows 15 ports at a time. For this
376 # reason, we do a little magic here: split the ports
377 # into portions of 15, and handle these portions as
380 my $proto = $rule->{protocol
};
381 error
('To use multiport, you have to specify "proto tcp" or "proto udp" first')
382 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array
($proto);
384 my $value = getvalues
(undef, allow_negation
=> 1,
385 allow_array_negation
=> 1);
386 if (ref $value and ref $value eq 'ARRAY') {
391 push @params, join(',', splice(@value, 0, 15));
398 return join_value
(',', $value);
402 # initialize stack: command line definitions
405 # Get command line stuff
407 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
408 $opt_timeout, $opt_help,
409 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
412 Getopt
::Long
::Configure
('bundling', 'auto_help', 'no_ignore_case',
416 my ($opt, $value) = @_;
417 die 'Invalid --def specification'
418 unless $value =~ /^\$?(\w+)=(.*)$/s;
419 my ($name, $unparsed_value) = ($1, $2);
420 my $tokens = tokenize_string
($unparsed_value);
421 my $value = getvalues
(sub { shift @
$tokens; });
422 die 'Extra tokens after --def'
424 $stack[0]{vars
}{$name} = $value;
427 local $SIG{__WARN__
} = sub { die $_[0]; };
428 GetOptions
('noexec|n' => \
$opt_noexec,
429 'flush|F' => \
$opt_flush,
430 'noflush' => \
$opt_noflush,
431 'lines|l' => \
$opt_lines,
432 'interactive|i' => \
$opt_interactive,
433 'timeout|t=s' => \
$opt_timeout,
434 'help|h' => \
$opt_help,
435 'version|V' => \
$opt_version,
437 remote
=> \
$opt_test,
440 shell
=> \
$opt_shell,
441 'domain=s' => \
$opt_domain,
442 'def=s' => \
&opt_def
,
445 if (defined $opt_help) {
447 Pod
::Usage
::pod2usage
(-exitstatus
=> 0);
450 if (defined $opt_version) {
455 $option{noexec
} = $opt_noexec || $opt_test;
456 $option{flush
} = $opt_flush;
457 $option{noflush
} = $opt_noflush;
458 $option{lines
} = $opt_lines || $opt_test || $opt_shell;
459 $option{interactive
} = $opt_interactive && !$opt_noexec;
460 $option{timeout
} = defined $opt_timeout ?
$opt_timeout : "30";
461 $option{test
} = $opt_test;
462 $option{fast
} = !$opt_slow;
463 $option{shell
} = $opt_shell;
465 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
466 if $option{interactive
} and not -t STDIN
;
467 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
468 if $option{interactive
} and not -t STDERR
;
469 die("ferm timeout has no sense without interactive mode")
470 if not $opt_interactive and defined $opt_timeout;
471 die("invalid timeout. must be an integer")
472 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
474 $option{domain
} = $opt_domain if defined $opt_domain;
476 # tiny getopt emulation for microperl
479 if ($_ eq '--noexec' or $_ eq '-n') {
481 } elsif ($_ eq '--lines' or $_ eq '-l') {
483 } elsif ($_ eq '--fast') {
485 } elsif ($_ eq '--test') {
489 } elsif ($_ eq '--shell') {
490 $option{$_} = 1 foreach qw(shell fast lines);
492 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
499 push @ARGV, $filename;
502 unless (@ARGV == 1) {
504 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
508 open LINES
, ">&STDOUT" if $option{lines
};
509 open STDOUT
, ">&STDERR" if $option{shell
};
511 # microperl can't redirect file handles
514 if ($option{fast
} and not $option{noexec
}) {
515 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
521 open_script
($ARGV[0]);
523 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $ARGV[0] );
524 $stack[0]{auto
}{FILENAME
} = $ARGV[0];
525 $stack[0]{auto
}{FILEBNAME
} = $file;
526 $stack[0]{auto
}{DIRNAME
} = $dirs;
530 # parse all input recursively
532 die unless @stack == 2;
534 # enable/disable hooks depending on --flush
536 if ($option{flush
}) {
543 # execute all generated rules
546 foreach my $cmd (@pre_hooks) {
547 print LINES
"$cmd\n" if $option{lines
};
548 system($cmd) unless $option{noexec
};
551 while (my ($domain, $domain_info) = each %domains) {
552 next unless $domain_info->{enabled
};
553 my $s = $option{fast
} &&
554 defined $domain_info->{tools
}{'tables-restore'}
555 ? execute_fast
($domain_info) : execute_slow
($domain_info);
556 $status = $s if defined $s;
559 foreach my $cmd (@post_hooks, @flush_hooks) {
560 print LINES
"$cmd\n" if $option{lines
};
561 system($cmd) unless $option{noexec
};
564 if (defined $status) {
569 # ask user, and rollback if there is no confirmation
571 if ($option{interactive
}) {
572 if ($option{shell
}) {
573 print LINES
"echo 'ferm has applied the new firewall rules.'\n";
574 print LINES
"echo 'Please press Ctrl-C to confirm.'\n";
575 print LINES
"sleep $option{timeout}\n";
576 while (my ($domain, $domain_info) = each %domains) {
577 my $restore = $domain_info->{tools
}{'tables-restore'};
578 next unless defined $restore;
579 print LINES
"$restore <\$${domain}_tmp\n";
583 confirm_rules
() or rollback
() unless $option{noexec
};
588 # end of program execution!
594 print "ferm $VERSION\n";
595 print "Copyright (C) 2001-2010 Max Kellermann, Auke Kok\n";
596 print "This program is free software released under GPLv2.\n";
597 print "See the included COPYING file for license details.\n";
602 # returns a nice formatted error message, showing the
603 # location of the error.
607 my @words = map { @
$_ } @
{$script->{past_tokens
}};
609 for my $w ( 0 .. $#words ) {
610 if ($words[$w] eq "\x29")
611 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
612 if ($words[$w] eq "\x28")
613 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
614 if ($words[$w] eq "\x7d")
615 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
616 if ($words[$w] eq "\x7b")
617 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
618 if ( $l > $#lines ) { $lines[$l] = "" };
619 $lines[$l] .= $words[$w] . " ";
620 if ($words[$w] eq "\x28")
621 { $l++ ; $lines[$l] = " " x
$tabs ;};
622 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
623 { $l++ ; $lines[$l] = " " x
$tabs ;};
624 if ($words[$w] eq "\x7b")
625 { $l++ ; $lines[$l] = " " x
$tabs ;};
626 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
627 { $l++ ; $lines[$l] = " " x
$tabs ;};
628 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
629 { $l++ ; $lines[$l] = " " x
$tabs ;}
630 if ($words[$w-1] eq "option")
631 { $l++ ; $lines[$l] = " " x
$tabs ;}
633 my $start = $#lines - 4;
634 if ($start < 0) { $start = 0 } ;
635 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
636 for $l ( $start .. $#lines)
637 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
638 print STDERR
"<--\n";
642 # print a warning message about code from an input file
644 print STDERR
"Warning in $script->{filename} line $script->{line}: "
650 return $name if $option{test
};
651 for my $path ('/sbin', split ':', $ENV{PATH
}) {
652 my $ret = "$path/$name";
653 return $ret if -x
$ret;
655 die "$name not found in PATH\n";
658 sub initialize_domain
{
660 my $domain_info = $domains{$domain} ||= {};
662 return if exists $domain_info->{initialized
};
664 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
666 my @tools = qw(tables);
667 push @tools, qw(tables-save tables-restore)
668 if $domain =~ /^ip6?$/;
670 # determine the location of this domain's tools
671 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
672 $domain_info->{tools
} = \
%tools;
674 # make tables-save tell us about the state of this domain
675 # (which tables and chains do exist?), also remember the old
676 # save data which may be used later by the rollback function
678 if (!$option{test
} &&
679 exists $tools{'tables-save'} &&
680 open(SAVE
, "$tools{'tables-save'}|")) {
689 $table_info = $domain_info->{tables
}{$table} ||= {};
690 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
692 $table_info->{chains
}{$1}{builtin
} = 1;
693 $table_info->{has_builtin
} = 1;
698 $domain_info->{previous
} = $save;
701 if ($option{shell
} && $option{interactive
} &&
702 exists $tools{'tables-save'}) {
703 print LINES
"${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
704 print LINES
"$tools{'tables-save'} >\$${domain}_tmp\n";
707 $domain_info->{initialized
} = 1;
710 sub filter_domains
($) {
714 foreach my $domain (to_array
($domains)) {
715 next if exists $option{domain
}
716 and $domain ne $option{domain
};
719 initialize_domain
($domain);
723 push @result, $domain;
726 return @result == 1 ?
@result[0] : \
@result;
729 # split the input string into words and delete comments
730 sub tokenize_string
($) {
735 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
736 last if $word eq '#';
743 # read some more tokens from the input file into a buffer
744 sub prepare_tokens
() {
745 my $tokens = $script->{tokens
};
746 while (@
$tokens == 0) {
747 my $handle = $script->{handle
};
748 my $line = <$handle>;
749 return unless defined $line;
753 # the next parser stage eats this
754 push @
$tokens, @
{tokenize_string
($line)};
760 # open a ferm sub script
762 my $filename = shift;
764 for (my $s = $script; defined $s; $s = $s->{parent
}) {
765 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
766 if $s->{filename
} eq $filename;
770 open FILE
, "$filename" or die("Failed to open $filename: $!\n");
773 $script = { filename
=> $filename,
784 # collect script filenames which are being included
785 sub collect_filenames
(@
) {
788 # determine the current script's parent directory for relative
790 die unless defined $script;
791 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
794 foreach my $pathname (@_) {
795 # non-absolute file names are relative to the parent script's
797 $pathname = $parent_dir . $pathname
798 unless $pathname =~ m
,^/|\
|$,;
800 if ($pathname =~ m
,/$,) {
801 # include all regular files in a directory
803 error
("'$pathname' is not a directory")
807 opendir DIR
, $pathname
808 or error
("Failed to open directory '$pathname': $!");
809 my @names = readdir DIR
;
812 # sort those names for a well-defined order
813 foreach my $name (sort { $a cmp $b } @names) {
814 # ignore dpkg's backup files
815 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
816 # don't include hidden and backup files
817 next if $name =~ /^\.|~$/;
819 my $filename = $pathname . $name;
823 } elsif ($pathname =~ m
,\
|$,) {
824 # run a program and use its output
825 push @ret, $pathname;
826 } elsif ($pathname =~ m
,^\
|,) {
827 error
('This kind of pipe is not allowed');
829 # include a regular file
831 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
833 error
("'$pathname' is not a file")
836 push @ret, $pathname;
843 # peek a token from the queue, but don't remove it
845 return unless prepare_tokens
();
846 return $script->{tokens
}[0];
849 # get a token from the queue
851 return unless prepare_tokens
();
852 my $token = shift @
{$script->{tokens
}};
854 # update $script->{past_tokens}
855 my $past_tokens = $script->{past_tokens
};
857 if (@
$past_tokens > 0) {
858 my $prev_token = $past_tokens->[-1][-1];
859 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
860 if $prev_token eq ';';
861 if ($prev_token eq '}') {
863 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
865 if @
$past_tokens > 0;
869 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
870 push @
{$past_tokens->[-1]}, $token;
876 sub expect_token
($;$) {
879 my $token = next_token
();
880 error
($msg || "'$expect' expected")
881 unless defined $token and $token eq $expect;
884 # require that another token exists, and that it's not a "special"
885 # token, e.g. ";" and "{"
886 sub require_next_token
{
887 my $code = shift || \
&next_token
;
889 my $token = &$code(@_);
891 error
('unexpected end of file')
892 unless defined $token;
894 error
("'$token' not allowed here")
895 if $token =~ /^[;{}]$/;
900 # return the value of a variable
901 sub variable_value
($) {
905 return $_->{vars
}{$name}
906 if exists $_->{vars
}{$name};
909 return $stack[0]{auto
}{$name}
910 if exists $stack[0]{auto
}{$name};
915 # determine the value of a variable, die if the value is an array
916 sub string_variable_value
($) {
918 my $value = variable_value
($name);
920 error
("variable '$name' must be a string, but it is an array")
926 # similar to the built-in "join" function, but also handle negated
927 # values in a special way
929 my ($expr, $value) = @_;
931 unless (ref $value) {
933 } elsif (ref $value eq 'ARRAY') {
934 return join($expr, @
$value);
935 } elsif (ref $value eq 'negated') {
936 # bless'negated' is a special marker for negated values
937 $value = join_value
($expr, $value->[0]);
938 return bless [ $value ], 'negated';
944 sub negate_value
($$;$) {
945 my ($value, $class, $allow_array) = @_;
948 error
('double negation is not allowed')
949 if ref $value eq 'negated' or ref $value eq 'pre_negated';
951 error
('it is not possible to negate an array')
952 if ref $value eq 'ARRAY' and not $allow_array;
955 return bless [ $value ], $class || 'negated';
959 return $_[0] ?
1 : 0;
963 my ($resolver, $names, $type) = @_;
966 foreach my $hostname (@
$names) {
967 my $query = $resolver->search($hostname, $type);
968 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
971 foreach my $rr ($query->answer) {
972 next unless $rr->type eq $type;
975 push @result, $rr->nsdname;
976 } elsif ($type eq 'MX') {
977 push @result, $rr->exchange;
979 push @result, $rr->address;
984 # NS/MX records return host names; resolve these again in the
985 # second pass (IPv4 only currently)
986 @result = resolve
($resolver, \
@result, 'A')
987 if $type eq 'NS' or $type eq 'MX';
992 # returns the next parameter, which may either be a scalar or an array
997 my $token = require_next_token
($code);
1000 # read an array until ")"
1004 $token = getvalues
($code,
1005 parenthesis_allowed
=> 1,
1006 comma_allowed
=> 1);
1008 unless (ref $token) {
1009 last if $token eq ')';
1011 if ($token eq ',') {
1012 error
('Comma is not allowed within arrays, please use only a space');
1016 push @wordlist, $token;
1017 } elsif (ref $token eq 'ARRAY') {
1018 push @wordlist, @
$token;
1020 error
('unknown toke type');
1024 error
('empty array not allowed here')
1025 unless @wordlist or not $options{non_empty
};
1027 return @wordlist == 1
1030 } elsif ($token =~ /^\`(.*)\`$/s) {
1031 # execute a shell command, insert output
1033 my $output = `$command`;
1036 error
("failed to execute: $!");
1037 } elsif ($?
& 0x7f) {
1038 error
("child died with signal " . ($?
& 0x7f));
1040 error
("child exited with status " . ($?
>> 8));
1045 $output =~ s/#.*//mg;
1048 my @tokens = grep { length } split /\s+/s, $output;
1052 my $value = getvalues
(sub { shift @tokens });
1053 push @values, to_array
($value);
1060 } elsif ($token =~ /^\'(.*)\'$/s) {
1061 # single quotes: a string
1063 } elsif ($token =~ /^\"(.*)\"$/s) {
1064 # double quotes: a string with escapes
1066 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
1068 } elsif ($token eq '!') {
1069 error
('negation is not allowed here')
1070 unless $options{allow_negation
};
1072 $token = getvalues
($code);
1074 return negate_value
($token, undef, $options{allow_array_negation
});
1075 } elsif ($token eq ',') {
1077 if $options{comma_allowed
};
1079 error
('comma is not allowed here');
1080 } elsif ($token eq '=') {
1081 error
('equals operator ("=") is not allowed here');
1082 } elsif ($token eq '$') {
1083 my $name = require_next_token
($code);
1084 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1085 unless $name =~ /^\w+$/;
1087 my $value = variable_value
($name);
1089 error
("no such variable: \$$name")
1090 unless defined $value;
1093 } elsif ($token eq '&') {
1094 error
("function calls are not allowed as keyword parameter");
1095 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1096 error
('Syntax error');
1097 } elsif ($token =~ /^@/) {
1098 if ($token eq '@resolve') {
1099 my @params = get_function_params
();
1100 error
('Usage: @resolve((hostname ...), [type])')
1101 unless @params == 1 or @params == 2;
1102 eval { require Net
::DNS
; };
1103 error
('For the @resolve() function, you need the Perl library Net::DNS')
1105 my $type = $params[1] || 'A';
1106 my $resolver = new Net
::DNS
::Resolver
;
1107 my @params = to_array
($params[0]);
1108 return [resolve
($resolver, @params, $type)];
1109 } elsif ($token eq '@eq') {
1110 my @params = get_function_params
();
1111 error
('Usage: @eq(a, b)') unless @params == 2;
1112 return format_bool
($params[0] eq $params[1]);
1113 } elsif ($token eq '@ne') {
1114 my @params = get_function_params
();
1115 error
('Usage: @ne(a, b)') unless @params == 2;
1116 return format_bool
($params[0] ne $params[1]);
1117 } elsif ($token eq '@not') {
1118 my @params = get_function_params
();
1119 error
('Usage: @not(a)') unless @params == 1;
1120 return format_bool
(not $params[0]);
1121 } elsif ($token eq '@cat') {
1123 map { $value .= $_ } get_function_params
();
1125 } elsif ($token eq '@substr') {
1126 my @params = get_function_params
();
1127 error
('Usage: @substr(string, num, num)') unless @params == 3;
1128 return substr($params[0],$params[1],$params[2]);
1129 } elsif ($token eq '@length') {
1130 my @params = get_function_params
();
1131 error
('Usage: @length(string)') unless @params == 1;
1132 return length($params[0]);
1133 } elsif ($token eq '@basename') {
1134 my @params = get_function_params
();
1135 error
('Usage: @basename(path)') unless @params == 1;
1136 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1138 } elsif ($token eq '@dirname') {
1139 my @params = get_function_params
();
1140 error
('Usage: @dirname(path)') unless @params == 1;
1141 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1144 error
("unknown ferm built-in function");
1151 # returns the next parameter, but only allow a scalar
1153 my $token = getvalues
();
1155 error
('array not allowed here')
1156 if ref $token and ref $token eq 'ARRAY';
1161 sub get_function_params
(%) {
1162 expect_token
('(', 'function name must be followed by "()"');
1164 my $token = peek_token
();
1165 if ($token eq ')') {
1166 require_next_token
();
1174 $token = require_next_token
();
1178 error
('"," expected')
1179 unless $token eq ',';
1182 push @params, getvalues
(undef, @_);
1188 # collect all tokens in a flat array reference until the end of the
1189 # command is reached
1190 sub collect_tokens
() {
1195 my $keyword = next_token
();
1196 error
('unexpected end of file within function/variable declaration')
1197 unless defined $keyword;
1199 if ($keyword =~ /^[\{\(]$/) {
1200 push @level, $keyword;
1201 } elsif ($keyword =~ /^[\}\)]$/) {
1202 my $expected = $keyword;
1203 $expected =~ tr/\}\)/\{\(/;
1204 my $opener = pop @level;
1205 error
("unmatched '$keyword'")
1206 unless defined $opener and $opener eq $expected;
1207 } elsif ($keyword eq ';' and @level == 0) {
1211 push @tokens, $keyword;
1214 if $keyword eq '}' and @level == 0;
1221 # returns the specified value as an array. dereference arrayrefs
1224 die unless wantarray;
1226 unless (ref $value) {
1228 } elsif (ref $value eq 'ARRAY') {
1235 # evaluate the specified value as bool
1240 unless (ref $value) {
1242 } elsif (ref $value eq 'ARRAY') {
1249 sub is_netfilter_core_target
($) {
1251 die unless defined $target and length $target;
1252 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1255 sub is_netfilter_module_target
($$) {
1256 my ($domain_family, $target) = @_;
1257 die unless defined $target and length $target;
1259 return defined $domain_family &&
1260 exists $target_defs{$domain_family} &&
1261 $target_defs{$domain_family}{$target};
1264 sub is_netfilter_builtin_chain
($$) {
1265 my ($table, $chain) = @_;
1267 return grep { $_ eq $chain }
1268 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1271 sub netfilter_canonical_protocol
($) {
1274 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1276 if $proto eq 'ipv6-mh';
1280 sub netfilter_protocol_module
($) {
1282 return unless defined $proto;
1284 if $proto eq 'icmpv6';
1288 # escape the string in a way safe for the shell
1289 sub shell_escape
($) {
1292 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1294 if ($option{fast
}) {
1295 # iptables-save/iptables-restore are quite buggy concerning
1296 # escaping and special characters... we're trying our best
1299 $token =~ s
,",\\",g
;
1300 $token = '"' . $token . '"'
1301 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1304 if $token =~ /^\`.*\`$/;
1305 $token =~ s/'/'\\''/g;
1306 $token = '\'' . $token . '\''
1307 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1313 # append an option to the shell command line, using information from
1314 # the module definition (see %match_defs etc.)
1315 sub shell_format_option
($$) {
1316 my ($keyword, $value) = @_;
1320 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1321 $value = $value->[0];
1326 unless (defined $value) {
1327 $cmd .= " --$keyword";
1328 } elsif (ref $value) {
1329 if (ref $value eq 'params') {
1330 $cmd .= " --$keyword ";
1331 $cmd .= join(' ', map { shell_escape
($_) } @
$value);
1332 } elsif (ref $value eq 'multi') {
1334 $cmd .= " --$keyword " . shell_escape
($_);
1340 $cmd .= " --$keyword " . shell_escape
($value);
1346 sub format_option
($$$) {
1347 my ($domain, $name, $value) = @_;
1348 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1349 and $value eq 'icmp';
1350 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1351 return shell_format_option
($name, $value);
1354 sub append_rule
($$) {
1355 my ($chain_rules, $rule) = @_;
1357 my $cmd = join('', map { $_->[2] } @
{$rule->{options
}});
1358 push @
$chain_rules, { rule
=> $cmd,
1359 script
=> $rule->{script
},
1364 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1365 return append_rule
($chain_rules, $rule) unless @_;
1368 my @values = @
{$option->[1]};
1370 foreach my $value (@values) {
1371 $option->[2] = format_option
($domain, $option->[0], $value);
1372 unfold_rule
($domain, $chain_rules, $rule, @_);
1377 my ($domain, $chain_rules, $rule) = @_;
1380 foreach my $option (@
{$rule->{options
}}) {
1381 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1382 push @unfold, $option
1384 $option->[2] = format_option
($domain, $option->[0], $option->[1]);
1388 unfold_rule
($domain, $chain_rules, $rule, @unfold);
1391 # convert a bunch of internal rule structures in iptables calls,
1392 # unfold arrays during that
1396 foreach my $domain (to_array
$rule->{domain
}) {
1397 my $domain_info = $domains{$domain};
1398 $domain_info->{enabled
} = 1;
1400 foreach my $table (to_array
$rule->{table
}) {
1401 my $table_info = $domain_info->{tables
}{$table} ||= {};
1403 foreach my $chain (to_array
$rule->{chain
}) {
1404 my $chain_rules = $table_info->{chains
}{$chain}{rules
} ||= [];
1405 mkrules2
($domain, $chain_rules, $rule)
1406 if $rule->{has_rule
} and not $option{flush
};
1412 # parse a keyword from a module definition
1413 sub parse_keyword
(\
%$$) {
1414 my ($rule, $def, $negated_ref) = @_;
1416 my $params = $def->{params
};
1421 if ($$negated_ref && exists $def->{pre_negation
}) {
1423 undef $$negated_ref;
1426 unless (defined $params) {
1428 } elsif (ref $params && ref $params eq 'CODE') {
1429 $value = &$params($rule);
1430 } elsif ($params eq 'm') {
1431 $value = bless [ to_array getvalues
() ], 'multi';
1432 } elsif ($params =~ /^[a-z]/) {
1433 if (exists $def->{negation
} and not $negated) {
1434 my $token = peek_token
();
1435 if ($token eq '!') {
1436 require_next_token
();
1442 foreach my $p (split(//, $params)) {
1444 push @params, getvar
();
1445 } elsif ($p eq 'c') {
1446 my @v = to_array getvalues
(undef, non_empty
=> 1);
1447 push @params, join(',', @v);
1453 $value = @params == 1
1455 : bless \
@params, 'params';
1456 } elsif ($params == 1) {
1457 if (exists $def->{negation
} and not $negated) {
1458 my $token = peek_token
();
1459 if ($token eq '!') {
1460 require_next_token
();
1465 $value = getvalues
();
1467 warning
("log-prefix is too long; truncating to 29 characters: '$1'")
1468 if $def->{name
} eq 'log-prefix' && $value =~ s
,^(.{29}).+$,$1,;
1470 if (exists $def->{negation
} and not $negated) {
1471 my $token = peek_token
();
1472 if ($token eq '!') {
1473 require_next_token
();
1478 $value = bless [ map {
1480 } (1..$params) ], 'params';
1483 $value = negate_value
($value, exists $def->{pre_negation
} && 'pre_negated')
1489 sub append_option
(\
%$$) {
1490 my ($rule, $name, $value) = @_;
1491 push @
{$rule->{options
}}, [ $name, $value ];
1494 # parse options of a module
1495 sub parse_option
($\
%$) {
1496 my ($def, $rule, $negated_ref) = @_;
1498 append_option
(%$rule, $def->{name
},
1499 parse_keyword
(%$rule, $def, $negated_ref));
1502 sub copy_on_write
($$) {
1503 my ($rule, $key) = @_;
1504 return unless exists $rule->{cow
}{$key};
1505 $rule->{$key} = {%{$rule->{$key}}};
1506 delete $rule->{cow
}{$key};
1509 sub new_level
(\
%$) {
1510 my ($rule, $prev) = @_;
1513 if (defined $prev) {
1514 # copy data from previous level
1515 $rule->{cow
} = { keywords
=> 1, };
1516 $rule->{keywords
} = $prev->{keywords
};
1517 $rule->{match
} = { %{$prev->{match
}} };
1518 $rule->{options
} = [@
{$prev->{options
}}];
1519 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1520 $rule->{$key} = $prev->{$key}
1521 if exists $prev->{$key};
1525 $rule->{keywords
} = {};
1526 $rule->{match
} = {};
1527 $rule->{options
} = [];
1531 sub merge_keywords
(\
%$) {
1532 my ($rule, $keywords) = @_;
1533 copy_on_write
($rule, 'keywords');
1534 while (my ($name, $def) = each %$keywords) {
1535 $rule->{keywords
}{$name} = $def;
1539 sub set_domain
(\
%$) {
1540 my ($rule, $domain) = @_;
1542 my $filtered_domain = filter_domains
($domain);
1544 unless (ref $domain) {
1545 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1546 } elsif (@
$domain == 0) {
1547 $domain_family = 'none';
1548 } elsif (grep { not /^ip6?$/s } @
$domain) {
1549 error
('Cannot combine non-IP domains');
1551 $domain_family = 'ip';
1554 $rule->{domain_family
} = $domain_family;
1555 $rule->{keywords
} = $match_defs{$domain_family}{''}{keywords
};
1556 $rule->{cow
}{keywords
} = 1;
1558 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $filtered_domain;
1561 sub set_target
(\
%$$) {
1562 my ($rule, $name, $value) = @_;
1563 error
('There can only one action per rule')
1564 if exists $rule->{has_action
};
1565 $rule->{has_action
} = 1;
1566 append_option
(%$rule, $name, $value);
1569 sub set_module_target
(\
%$$) {
1570 my ($rule, $name, $defs) = @_;
1572 if ($name eq 'TCPMSS') {
1573 my $protos = $rule->{protocol
};
1574 error
('No protocol specified before TCPMSS')
1575 unless defined $protos;
1576 foreach my $proto (to_array
$protos) {
1577 error
('TCPMSS not available for protocol "$proto"')
1578 unless $proto eq 'tcp';
1582 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1583 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family
} eq 'eb';
1585 set_target
(%$rule, 'jump', $name);
1586 merge_keywords
(%$rule, $defs->{keywords
});
1589 # the main parser loop: read tokens, convert them into internal rule
1592 my $lev = shift; # current recursion depth
1593 my $prev = shift; # previous rule hash
1595 # enter is the core of the firewall setup, it is a
1596 # simple parser program that recognizes keywords and
1597 # retreives parameters to set up the kernel routing
1600 my $base_level = $script->{base_level
} || 0;
1601 die if $base_level > $lev;
1604 new_level
(%rule, $prev);
1606 # read keywords 1 by 1 and dump into parser
1607 while (defined (my $keyword = next_token
())) {
1608 # check if the current rule should be negated
1609 my $negated = $keyword eq '!';
1611 # negation. get the next word which contains the 'real'
1613 $keyword = getvar
();
1615 error
('unexpected end of file after negation')
1616 unless defined $keyword;
1619 # the core: parse all data
1622 # deprecated keyword?
1623 if (exists $deprecated_keywords{$keyword}) {
1624 my $new_keyword = $deprecated_keywords{$keyword};
1625 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1626 $keyword = $new_keyword;
1629 # effectuation operator
1630 if ($keyword eq ';') {
1631 error
('Empty rule before ";" not allowed')
1632 unless $rule{non_empty
};
1634 if ($rule{has_rule
} and not exists $rule{has_action
}) {
1635 # something is wrong when a rule was specified,
1637 error
('No action defined; did you mean "NOP"?');
1640 error
('No chain defined') unless exists $rule{chain
};
1642 $rule{script
} = { filename
=> $script->{filename
},
1643 line
=> $script->{line
},
1648 # and clean up variables set in this level
1649 new_level
(%rule, $prev);
1654 # conditional expression
1655 if ($keyword eq '@if') {
1656 unless (eval_bool
(getvalues
)) {
1658 my $token = peek_token
();
1659 require_next_token
() if $token and $token eq '@else';
1665 if ($keyword eq '@else') {
1666 # hack: if this "else" has not been eaten by the "if"
1667 # handler above, we believe it came from an if clause
1668 # which evaluated "true" - remove the "else" part now.
1673 # hooks for custom shell commands
1674 if ($keyword eq 'hook') {
1675 warning
("'hook' is deprecated, use '\@hook'");
1679 if ($keyword eq '@hook') {
1680 error
('"hook" must be the first token in a command')
1681 if exists $rule{domain
};
1683 my $position = getvar
();
1685 if ($position eq 'pre') {
1686 $hooks = \
@pre_hooks;
1687 } elsif ($position eq 'post') {
1688 $hooks = \
@post_hooks;
1689 } elsif ($position eq 'flush') {
1690 $hooks = \
@flush_hooks;
1692 error
("Invalid hook position: '$position'");
1695 push @
$hooks, getvar
();
1701 # recursing operators
1702 if ($keyword eq '{') {
1704 my $old_stack_depth = @stack;
1706 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1709 enter
($lev + 1, \
%rule);
1713 die unless @stack == $old_stack_depth;
1715 # after a block, the command is finished, clear this
1717 new_level
(%rule, $prev);
1722 if ($keyword eq '}') {
1723 error
('Unmatched "}"')
1724 if $lev <= $base_level;
1726 # consistency check: check if they havn't forgotten
1727 # the ';' after the last statement
1728 error
('Missing semicolon before "}"')
1729 if $rule{non_empty
};
1735 # include another file
1736 if ($keyword eq '@include' or $keyword eq 'include') {
1737 my @files = collect_filenames to_array getvalues
;
1738 $keyword = next_token
;
1739 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1740 unless defined $keyword and $keyword eq ';';
1742 foreach my $filename (@files) {
1743 # save old script, open new script
1744 my $old_script = $script;
1745 open_script
($filename);
1746 $script->{base_level
} = $lev + 1;
1749 my $old_stack_depth = @stack;
1754 # include files may set variables for their parent
1755 $stack->{vars
} = ($stack[0]{vars
} ||= {});
1756 $stack->{functions
} = ($stack[0]{functions
} ||= {});
1757 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
1760 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $filename );
1761 $stack->{auto
}{FILENAME
} = $filename;
1762 $stack->{auto
}{FILEBNAME
} = $file;
1763 $stack->{auto
}{DIRNAME
} = $dirs;
1765 unshift @stack, $stack;
1768 enter
($lev + 1, \
%rule);
1772 die unless @stack == $old_stack_depth;
1774 # restore old script
1775 $script = $old_script;
1781 # definition of a variable or function
1782 if ($keyword eq '@def' or $keyword eq 'def') {
1783 error
('"def" must be the first token in a command')
1784 if $rule{non_empty
};
1786 my $type = require_next_token
();
1788 my $name = require_next_token
();
1789 error
('invalid variable name')
1790 unless $name =~ /^\w+$/;
1794 my $value = getvalues
(undef, allow_negation
=> 1);
1798 $stack[0]{vars
}{$name} = $value
1799 unless exists $stack[-1]{vars
}{$name};
1800 } elsif ($type eq '&') {
1801 my $name = require_next_token
();
1802 error
('invalid function name')
1803 unless $name =~ /^\w+$/;
1805 expect_token
('(', 'function parameter list or "()" expected');
1809 my $token = require_next_token
();
1810 last if $token eq ')';
1813 error
('"," expected')
1814 unless $token eq ',';
1816 $token = require_next_token
();
1819 error
('"$" and parameter name expected')
1820 unless $token eq '$';
1822 $token = require_next_token
();
1823 error
('invalid function parameter name')
1824 unless $token =~ /^\w+$/;
1826 push @params, $token;
1831 $function{params
} = \
@params;
1835 my $tokens = collect_tokens
();
1836 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
1837 $function{tokens
} = $tokens;
1839 $stack[0]{functions
}{$name} = \
%function
1840 unless exists $stack[-1]{functions
}{$name};
1842 error
('"$" (variable) or "&" (function) expected');
1848 # this rule has something which isn't inherited by its
1849 # parent closure. This variable is used in a lot of
1852 $rule{non_empty
} = 1;
1855 if ($keyword eq '$') {
1856 error
('variable references are only allowed as keyword parameter');
1859 if ($keyword eq '&') {
1860 my $name = require_next_token
();
1861 error
('function name expected')
1862 unless $name =~ /^\w+$/;
1866 $function = $_->{functions
}{$name};
1867 last if defined $function;
1869 error
("no such function: \&$name")
1870 unless defined $function;
1872 my $paramdef = $function->{params
};
1873 die unless defined $paramdef;
1875 my @params = get_function_params
(allow_negation
=> 1);
1877 error
("Wrong number of parameters for function '\&$name': "
1878 . @
$paramdef . " expected, " . @params . " given")
1879 unless @params == @
$paramdef;
1882 for (my $i = 0; $i < @params; $i++) {
1883 $vars{$paramdef->[$i]} = $params[$i];
1886 if ($function->{block
}) {
1887 # block {} always ends the current rule, so if the
1888 # function contains a block, we have to require
1889 # the calling rule also ends here
1893 my @tokens = @
{$function->{tokens
}};
1894 for (my $i = 0; $i < @tokens; $i++) {
1895 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1896 exists $vars{$tokens[$i + 1]}) {
1897 my @value = to_array
($vars{$tokens[$i + 1]});
1898 @value = ('(', @value, ')')
1899 unless @tokens == 1;
1900 splice(@tokens, $i, 2, @value);
1902 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
1903 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
1907 unshift @
{$script->{tokens
}}, @tokens;
1912 # where to put the rule?
1913 if ($keyword eq 'domain') {
1914 error
('Domain is already specified')
1915 if exists $rule{domain
};
1917 set_domain
(%rule, getvalues
());
1921 if ($keyword eq 'table') {
1922 warning
('Table is already specified')
1923 if exists $rule{table
};
1924 $rule{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
1926 set_domain
(%rule, 'ip')
1927 unless exists $rule{domain
};
1932 if ($keyword eq 'chain') {
1933 warning
('Chain is already specified')
1934 if exists $rule{chain
};
1936 my $chain = $rule{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
1938 # ferm 1.1 allowed lower case built-in chain names
1939 foreach (ref $rule{chain
} ? @
{$rule{chain
}} : $rule{chain
}) {
1940 error
('Please write built-in chain names in upper case')
1941 if /^(?:input|forward|output|prerouting|postrouting)$/;
1944 set_domain
(%rule, 'ip')
1945 unless exists $rule{domain
};
1947 $rule{table
} = 'filter'
1948 unless exists $rule{table
};
1950 foreach my $domain (to_array
$rule{domain
}) {
1951 foreach my $table (to_array
$rule{table
}) {
1952 foreach my $c (to_array
$chain) {
1953 $domains{$domain}{tables
}{$table}{chains
}{$c} ||= {};
1961 error
('Chain must be specified')
1962 unless exists $rule{chain
};
1964 # policy for built-in chain
1965 if ($keyword eq 'policy') {
1966 error
('Cannot specify matches for policy')
1969 my $policy = getvar
();
1970 error
("Invalid policy target: $policy")
1971 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1975 foreach my $domain (to_array
$rule{domain
}) {
1976 my $domain_info = $domains{$domain};
1977 $domain_info->{enabled
} = 1;
1979 foreach my $table (to_array
$rule{table
}) {
1980 foreach my $chain (to_array
$rule{chain
}) {
1981 $domain_info->{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
1986 new_level
(%rule, $prev);
1991 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1992 error
('Chain must be specified')
1993 unless exists $rule{chain
};
1995 error
('No rule specified before "@subchain"')
1996 unless $rule{has_rule
};
1999 my $token = peek_token
();
2001 if ($token =~ /^(["'])(.*)\1$/s) {
2004 $keyword = next_token
();
2005 } elsif ($token eq '{') {
2006 $keyword = next_token
();
2007 $subchain = 'ferm_auto_' . ++$auto_chain;
2009 $subchain = getvar
();
2010 $keyword = next_token
();
2013 foreach my $domain (to_array
$rule{domain
}) {
2014 foreach my $table (to_array
$rule{table
}) {
2015 $domains{$domain}{tables
}{$table}{chains
}{$subchain} ||= {};
2019 set_target
(%rule, 'jump', $subchain);
2021 error
('"{" or chain name expected after "@subchain"')
2022 unless $keyword eq '{';
2024 # create a deep copy of %rule, only containing values
2025 # which must be in the subchain
2026 my %inner = ( cow
=> { keywords
=> 1, },
2030 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
2031 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2033 if (exists $rule{protocol
}) {
2034 $inner{protocol
} = $rule{protocol
};
2035 append_option
(%inner, 'protocol', $inner{protocol
});
2038 # create a new stack frame
2039 my $old_stack_depth = @stack;
2040 my $stack = { auto
=> { %{$stack[0]{auto
} || {}} } };
2041 $stack->{auto
}{CHAIN
} = $subchain;
2042 unshift @stack, $stack;
2045 enter
($lev + 1, \
%inner);
2049 die unless @stack == $old_stack_depth;
2051 # now handle the parent - it's a jump to the sub chain
2053 filename
=> $script->{filename
},
2054 line
=> $script->{line
},
2059 # and clean up variables set in this level
2060 new_level
(%rule, $prev);
2061 delete $rule{has_rule
};
2066 # everything else must be part of a "real" rule, not just
2068 $rule{has_rule
} = 1;
2070 # extended parameters:
2071 if ($keyword =~ /^mod(?:ule)?$/) {
2072 foreach my $module (to_array getvalues
) {
2073 next if exists $rule{match
}{$module};
2075 my $domain_family = $rule{domain_family
};
2076 my $defs = $match_defs{$domain_family}{$module};
2078 append_option
(%rule, 'match', $module);
2079 $rule{match
}{$module} = 1;
2081 merge_keywords
(%rule, $defs->{keywords
})
2088 # keywords from $rule{keywords}
2090 if (exists $rule{keywords
}{$keyword}) {
2091 my $def = $rule{keywords
}{$keyword};
2092 parse_option
($def, %rule, \
$negated);
2101 if ($keyword eq 'jump') {
2102 set_target
(%rule, 'jump', getvar
());
2107 if ($keyword eq 'realgoto') {
2108 set_target
(%rule, 'goto', getvar
());
2113 if (is_netfilter_core_target
($keyword)) {
2114 set_target
(%rule, 'jump', $keyword);
2118 if ($keyword eq 'NOP') {
2119 error
('There can only one action per rule')
2120 if exists $rule{has_action
};
2121 $rule{has_action
} = 1;
2125 if (my $defs = is_netfilter_module_target
($rule{domain_family
}, $keyword)) {
2126 set_module_target
(%rule, $keyword, $defs);
2131 # protocol specific options
2134 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2135 my $protocol = parse_keyword
(%rule,
2136 { params
=> 1, negation
=> 1 },
2138 $rule{protocol
} = $protocol;
2139 append_option
(%rule, 'protocol', $rule{protocol
});
2141 unless (ref $protocol) {
2142 $protocol = netfilter_canonical_protocol
($protocol);
2143 my $domain_family = $rule{domain_family
};
2144 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2145 merge_keywords
(%rule, $defs->{keywords
});
2146 my $module = netfilter_protocol_module
($protocol);
2147 $rule{match
}{$module} = 1;
2154 if ($keyword =~ /^[sd]port$/) {
2155 my $proto = $rule{protocol
};
2156 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2157 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2159 append_option
(%rule, $keyword,
2160 getvalues
(undef, allow_negation
=> 1));
2165 error
("Unrecognized keyword: $keyword");
2168 # if the rule didn't reset the negated flag, it's not
2170 error
("Doesn't support negation: $keyword")
2174 error
('Missing "}" at end of file')
2175 if $lev > $base_level;
2177 # consistency check: check if they havn't forgotten
2178 # the ';' before the last statement
2179 error
("Missing semicolon before end of file")
2180 if $rule{non_empty
};
2183 sub execute_command
{
2184 my ($command, $script) = @_;
2186 print LINES
"$command\n"
2188 return if $option{noexec
};
2190 my $ret = system($command);
2191 unless ($ret == 0) {
2193 print STDERR
"failed to execute: $!\n";
2195 } elsif ($?
& 0x7f) {
2196 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2199 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2208 sub execute_slow
($) {
2209 my $domain_info = shift;
2211 my $domain_cmd = $domain_info->{tools
}{tables
};
2214 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2215 my $table_cmd = "$domain_cmd -t $table";
2217 # reset chain policies
2218 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2219 next unless $chain_info->{builtin
} or
2220 (not $table_info->{has_builtin
} and
2221 is_netfilter_builtin_chain
($table, $chain));
2222 $status ||= execute_command
("$table_cmd -P $chain ACCEPT")
2223 unless $option{noflush
};
2227 unless ($option{noflush
}) {
2228 $status ||= execute_command
("$table_cmd -F");
2229 $status ||= execute_command
("$table_cmd -X");
2232 next if $option{flush
};
2234 # create chains / set policy
2235 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2236 if (exists $chain_info->{policy
}) {
2237 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2238 unless $chain_info->{policy
} eq 'ACCEPT';
2239 } elsif (not is_netfilter_builtin_chain
($table, $chain)) {
2240 $status ||= execute_command
("$table_cmd -N $chain");
2245 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2246 my $chain_cmd = "$table_cmd -A $chain";
2247 foreach my $rule (@
{$chain_info->{rules
}}) {
2248 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2256 sub table_to_save
($$) {
2257 my ($result_r, $table_info) = @_;
2259 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2260 my $chain_info = $table_info->{chains
}{$chain};
2261 foreach my $rule (@
{$chain_info->{rules
}}) {
2262 $$result_r .= "-A $chain$rule->{rule}\n";
2267 sub rules_to_save
($) {
2268 my ($domain_info) = @_;
2270 # convert this into an iptables-save text
2271 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2273 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2275 $result .= '*' . $table . "\n";
2277 # create chains / set policy
2278 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2279 my $chain_info = $table_info->{chains
}{$chain};
2280 my $policy = $option{flush
} ?
undef : $chain_info->{policy
};
2281 unless (defined $policy) {
2282 if (is_netfilter_builtin_chain
($table, $chain)) {
2285 next if $option{flush
};
2289 $result .= ":$chain $policy\ [0:0]\n";
2292 table_to_save
(\
$result, $table_info)
2293 unless $option{flush
};
2296 $result .= "COMMIT\n";
2302 sub restore_domain
($$) {
2303 my ($domain_info, $save) = @_;
2305 my $path = $domain_info->{tools
}{'tables-restore'};
2308 open RESTORE
, "|$path"
2309 or die "Failed to run $path: $!\n";
2311 print RESTORE
$save;
2314 or die "Failed to run $path\n";
2317 sub execute_fast
($) {
2318 my $domain_info = shift;
2320 my $save = rules_to_save
($domain_info);
2322 if ($option{lines
}) {
2323 print LINES
"$domain_info->{tools}{'tables-restore'} <<EOT\n"
2330 return if $option{noexec};
2333 restore_domain($domain_info, $save);
2345 while (my ($domain, $domain_info) = each %domains) {
2346 next unless $domain_info->{enabled};
2347 unless (defined $domain_info->{tools}{'tables-restore'}) {
2348 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2353 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2354 my $reset_chain = '';
2355 foreach my $chain (keys %{$table_info->{chains}}) {
2356 next unless is_netfilter_builtin_chain($table, $chain);
2357 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2359 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2360 if length $reset_chain;
2363 $reset .= $domain_info->{previous}
2364 if defined $domain_info->{previous};
2366 restore_domain($domain_info, $reset);
2369 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2374 # do nothing, just interrupt a system call
2378 $SIG{ALRM} = \&alrm_handler;
2383 . "ferm has applied the new firewall rules
.\n"
2384 . "Please type
'yes' to confirm
:\n";
2387 alarm($option{timeout});
2390 STDIN->sysread($line, 3);
2394 POSIX::tcflush(*STDIN, 2);
2396 print STDERR "$@
" if $@;
2398 $SIG{ALRM} = 'DEFAULT';
2400 return $line eq 'yes';
2409 ferm - a firewall rule parser for linux
2413 B<ferm> I<options> I<inputfiles>
2417 -n, --noexec Do not execute the rules, just simulate
2418 -F, --flush Flush all netfilter tables managed by ferm
2419 -l, --lines Show all rules that were created
2420 -i, --interactive Interactive mode: revert if user does not confirm
2421 -t, --timeout s Define interactive mode timeout in seconds
2422 --remote Remote mode; ignore host specific configuration.
2423 This implies --noexec and --lines.
2424 -V, --version Show current version number
2425 -h, --help Look at this text
2426 --slow Slow mode, don't use iptables-restore
2427 --shell Generate a shell script which calls iptables-restore
2428 --domain {ip|ip6} Handle only the specified domain
2429 --def '$name=v' Override a variable