removed canonical.pl from test suite, do raw diff -u, many changes to test suite...
[ferm.git] / src / ferm
blob9563661689d1cd164216f1b5342bea763795cbab
1 #!/usr/bin/perl
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
28 # $Id$
30 BEGIN {
31 eval { require strict; import strict; };
32 $has_strict = not $@;
33 if ($@) {
34 # we need no vars.pm if there is not even strict.pm
35 $INC{'vars.pm'} = 1;
36 *vars::import = sub {};
37 } else {
38 require IO::Handle;
41 eval { require Getopt::Long; import Getopt::Long; };
42 $has_getopt = not $@;
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 : '';
52 $VERSION = '2.0';
53 $VERSION .= '~svn' . $DATE;
55 ## interface variables
56 # %option = command line and other options
57 use vars qw(%option);
59 ## hooks
60 use vars qw(@pre_hooks @post_hooks);
62 ## parser variables
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);
79 ## constants
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
101 # this is).
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
107 # array)
109 # foo*0 option without any arguments
111 # foo=s one argument which must not be a ferm array ('s' stands for
112 # 'scalar')
114 # u32=m an array which renders into multiple iptables options in one
115 # rule
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
126 # the argument
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
131 # parameters
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
138 sub add_def_x {
139 my $defs = shift;
140 my $domain_family = shift;
141 my $params_default = shift;
142 my $name = shift;
143 die if exists $defs->{$domain_family}{$name};
144 my $def = $defs->{$domain_family}{$name} = {};
145 foreach (@_) {
146 my $keyword = $_;
147 my $k = {};
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";
154 die $@ if $@;
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;
166 return $def;
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', @_);
187 sub add_def {
188 my $defs = shift;
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();
215 add_match_def '',
216 # --source, --destination
217 qw(source! saddr:=source destination! daddr:=destination),
218 # --in-interface
219 qw(in-interface! interface:=in-interface if:=in-interface),
220 # --out-interface
221 qw(out-interface! outerface:=out-interface of:=out-interface),
222 # --fragment
223 qw(!fragment*0);
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', '',
313 # ip
314 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
315 # mac
316 qw(source-mac! destination-mac!),
317 # --in-interface
318 qw(in-interface! interface:=in-interface if:=in-interface),
319 # --out-interface
320 qw(out-interface! outerface:=out-interface of:=out-interface),
321 # misc
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', '',
326 # protocol
327 qw(protocol! proto:=protocol),
328 # --in-interface
329 qw(in-interface! interface:=in-interface if:=in-interface),
330 # --out-interface
331 qw(out-interface! outerface:=out-interface of:=out-interface),
332 # logical interface
333 qw(logical-in! logical-out!),
334 # --source, --destination
335 qw(source! saddr:=source destination! daddr:=destination),
336 # 802.3
337 qw(802_3-sap! 802_3-type!),
338 # arp
339 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
340 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
341 # ip
342 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
343 # mark_m
344 qw(mark!),
345 # pkttype
346 qw(pkttype-type!),
347 # stp
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!),
351 # vlan
352 qw(vlan-id! vlan-prio! vlan-encap!),
353 # log
354 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
356 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
357 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
358 add_target_def_x 'eb', 'mark', qw(set-mark mark-target);
359 add_target_def_x 'eb', 'redirect', qw(redirect-target);
360 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
362 # import-ferm uses the above tables
363 return 1 if $0 =~ /import-ferm$/;
365 use vars qw(%builtin_keywords);
367 sub get_builtin_keywords($) {
368 my $domain_family = shift;
369 return {} unless defined $domain_family;
371 return {%{$builtin_keywords{$domain_family}}}
372 if exists $builtin_keywords{$domain_family};
374 return {} unless exists $match_defs{$domain_family};
375 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
376 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
378 $builtin_keywords{$domain_family} = \%keywords;
379 return {%keywords};
382 # parameter parser for ipt_multiport
383 sub multiport_params {
384 my $fw = shift;
386 # multiport only allows 15 ports at a time. For this
387 # reason, we do a little magic here: split the ports
388 # into portions of 15, and handle these portions as
389 # array elements
391 my $proto = $fw->{protocol};
392 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
393 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
395 my $value = getvalues(undef, undef,
396 allow_negation => 1,
397 allow_array_negation => 1);
398 if (ref $value and ref $value eq 'ARRAY') {
399 my @value = @$value;
400 my @params;
402 while (@value) {
403 push @params, join(',', splice(@value, 0, 15));
406 return @params == 1
407 ? $params[0]
408 : \@params;
409 } else {
410 return join_value(',', $value);
414 # initialize stack: command line definitions
415 unshift @stack, {};
417 # Get command line stuff
418 if ($has_getopt) {
419 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
420 $opt_verbose, $opt_debug,
421 $opt_help,
422 $opt_version, $opt_test, $opt_fast, $opt_shell,
423 $opt_domain);
425 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
426 'no_auto_abbrev');
428 sub opt_def {
429 my ($opt, $value) = @_;
430 die 'Invalid --def specification'
431 unless $value =~ /^\$?(\w+)=(.*)$/s;
432 my ($name, $unparsed_value) = ($1, $2);
433 my $tokens = tokenize_string($unparsed_value);
434 my $value = getvalues(\&next_array_token, $tokens);
435 die 'Extra tokens after --def'
436 if @$tokens > 0;
437 $stack[0]{vars}{$name} = $value;
440 local $SIG{__WARN__} = sub { die $_[0]; };
441 GetOptions('noexec|n' => \$opt_noexec,
442 'flush|F' => \$opt_flush,
443 'noflush' => \$opt_noflush,
444 'lines|l' => \$opt_lines,
445 'interactive|i' => \$opt_interactive,
446 'verbose|v' => \$opt_verbose,
447 'debug|d' => \$opt_debug,
448 'help|h' => \$opt_help,
449 'version|V' => \$opt_version,
450 test => \$opt_test,
451 remote => \$opt_test,
452 fast => \$opt_fast,
453 shell => \$opt_shell,
454 'domain=s' => \$opt_domain,
455 'def=s' => \&opt_def,
458 if (defined $opt_help) {
459 require Pod::Usage;
460 Pod::Usage::pod2usage(-exitstatus => 0);
463 if (defined $opt_version) {
464 printversion();
465 exit 0;
468 $option{'noexec'} = (defined $opt_noexec);
469 $option{flush} = defined $opt_flush;
470 $option{noflush} = defined $opt_noflush;
471 $option{'lines'} = (defined $opt_lines);
472 $option{interactive} = (defined $opt_interactive);
473 $option{test} = (defined $opt_test);
475 if ($option{test}) {
476 $option{noexec} = 1;
477 $option{lines} = 1;
480 delete $option{interactive} if $option{noexec};
482 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
483 if $option{interactive} and not -t STDIN;
484 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
485 if $option{interactive} and not -t STDERR;
487 $option{fast} = 1 if defined $opt_fast;
489 if (defined $opt_shell) {
490 $option{$_} = 1 foreach qw(shell fast lines);
493 $option{domain} = $opt_domain if defined $opt_domain;
495 print STDERR "Warning: ignoring the obsolete --debug option\n"
496 if defined $opt_debug;
497 print STDERR "Warning: ignoring the obsolete --verbose option\n"
498 if defined $opt_verbose;
499 } else {
500 # tiny getopt emulation for microperl
501 my $filename;
502 foreach (@ARGV) {
503 if ($_ eq '--noexec' or $_ eq '-n') {
504 $option{noexec} = 1;
505 } elsif ($_ eq '--lines' or $_ eq '-l') {
506 $option{lines} = 1;
507 } elsif ($_ eq '--fast') {
508 $option{fast} = 1;
509 } elsif ($_ eq '--test') {
510 $option{test} = 1;
511 $option{noexec} = 1;
512 $option{lines} = 1;
513 } elsif ($_ eq '--shell') {
514 $option{$_} = 1 foreach qw(shell fast lines);
515 } elsif (/^-/) {
516 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
517 exit 1;
518 } else {
519 $filename = $_;
522 undef @ARGV;
523 push @ARGV, $filename;
526 unless (@ARGV == 1) {
527 require Pod::Usage;
528 Pod::Usage::pod2usage(-exitstatus => 1);
531 if ($has_strict) {
532 open LINES, ">&STDOUT" if $option{lines};
533 open STDOUT, ">&STDERR" if $option{shell};
534 } else {
535 # microperl can't redirect file handles
536 *LINES = *STDOUT;
538 if ($option{fast} and not $option{noexec}) {
539 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
540 exit 1
544 unshift @stack, {};
545 open_script($ARGV[0]);
547 # parse all input recursively
548 enter(0);
549 die unless @stack == 2;
551 # execute all generated rules
552 my $status;
554 foreach my $cmd (@pre_hooks) {
555 print LINES "$cmd\n" if $option{lines};
556 system($cmd) unless $option{noexec};
559 while (my ($domain, $domain_info) = each %domains) {
560 next unless $domain_info->{enabled};
561 my $s = $option{fast} &&
562 defined $domain_info->{tools}{'tables-restore'}
563 ? execute_fast($domain, $domain_info)
564 : execute_slow($domain, $domain_info);
565 $status = $s if defined $s;
568 foreach my $cmd (@post_hooks) {
569 print "$cmd\n" if $option{lines};
570 system($cmd) unless $option{noexec};
573 if (defined $status) {
574 rollback();
575 exit $status;
578 # ask user, and rollback if there is no confirmation
580 confirm_rules() or rollback() if $option{interactive};
582 exit 0;
584 # end of program execution!
587 # funcs
589 sub printversion {
590 print "ferm $VERSION\n";
591 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
592 print "This program is free software released under GPLv2.\n";
593 print "See the included COPYING file for license details.\n";
597 sub mydie {
598 print STDERR @_;
599 print STDERR "\n";
600 exit 1;
604 sub error {
605 # returns a nice formatted error message, showing the
606 # location of the error.
607 my $tabs = 0;
608 my @lines;
609 my $l = 0;
610 my @words = map { @$_ } @{$script->{past_tokens}};
612 for my $w ( 0 .. $#words ) {
613 if ($words[$w] eq "\x29")
614 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
615 if ($words[$w] eq "\x28")
616 { $l++ ; $lines[$l] = " " x $tabs++ ;};
617 if ($words[$w] eq "\x7d")
618 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
619 if ($words[$w] eq "\x7b")
620 { $l++ ; $lines[$l] = " " x $tabs++ ;};
621 if ( $l > $#lines ) { $lines[$l] = "" };
622 $lines[$l] .= $words[$w] . " ";
623 if ($words[$w] eq "\x28")
624 { $l++ ; $lines[$l] = " " x $tabs ;};
625 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
626 { $l++ ; $lines[$l] = " " x $tabs ;};
627 if ($words[$w] eq "\x7b")
628 { $l++ ; $lines[$l] = " " x $tabs ;};
629 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
630 { $l++ ; $lines[$l] = " " x $tabs ;};
631 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
632 { $l++ ; $lines[$l] = " " x $tabs ;}
633 if ($words[$w-1] eq "option")
634 { $l++ ; $lines[$l] = " " x $tabs ;}
636 my $start = $#lines - 4;
637 if ($start < 0) { $start = 0 } ;
638 print STDERR "Error in $script->{filename} line $script->{line}:\n";
639 for $l ( $start .. $#lines)
640 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
641 print STDERR "<--\n";
642 mydie(@_);
645 # print a warning message about code from an input file
646 sub warning {
647 print STDERR "Warning in $script->{filename} line $script->{line}: "
648 . (shift) . "\n";
651 sub find_tool($) {
652 my $name = shift;
653 return $name if $option{test};
654 for my $path ('/sbin', split ':', $ENV{PATH}) {
655 my $ret = "$path/$name";
656 return $ret if -x $ret;
658 die "$name not found in PATH\n";
661 sub initialize_domain {
662 my $domain = shift;
663 my $domain_info = $domains{$domain} ||= {};
665 return if exists $domain_info->{initialized};
667 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
669 my @tools = qw(tables);
670 push @tools, qw(tables-save tables-restore)
671 if $domain =~ /^ip6?$/;
673 # determine the location of this domain's tools
674 my %tools = map { $_ => find_tool($domain . $_) } @tools;
675 $domain_info->{tools} = \%tools;
677 # make tables-save tell us about the state of this domain
678 # (which tables and chains do exist?), also remember the old
679 # save data which may be used later by the rollback function
680 local *SAVE;
681 if (!$option{test} &&
682 exists $tools{'tables-save'} &&
683 open(SAVE, "$tools{'tables-save'}|")) {
684 my $save = '';
686 my $table_info;
687 while (<SAVE>) {
688 $save .= $_;
690 if (/^\*(\w+)/) {
691 my $table = $1;
692 $table_info = $domain_info->{tables}{$table} ||= {};
693 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
694 and $2 ne '-') {
695 $table_info->{chains}{$1}{builtin} = 1;
696 $table_info->{has_builtin} = 1;
700 # for rollback
701 $domain_info->{previous} = $save;
704 $domain_info->{initialized} = 1;
707 # split the an input string into words and delete comments
708 sub tokenize_string($) {
709 my $string = shift;
711 my @ret;
713 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
714 last if $word eq '#';
715 push @ret, $word;
718 return \@ret;
721 # shift an array; helper function to be passed to &getvar / &getvalues
722 sub next_array_token {
723 my $array = shift;
724 shift @$array;
727 # read some more tokens from the input file into a buffer
728 sub prepare_tokens() {
729 my $tokens = $script->{tokens};
730 while (@$tokens == 0) {
731 my $handle = $script->{handle};
732 my $line = <$handle>;
733 return unless defined $line;
735 $script->{line} ++;
737 # the next parser stage eats this
738 push @$tokens, @{tokenize_string($line)};
741 return 1;
744 # open a ferm sub script
745 sub open_script($) {
746 my $filename = shift;
748 for (my $s = $script; defined $s; $s = $s->{parent}) {
749 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
750 if $s->{filename} eq $filename;
753 local *FILE;
754 open FILE, "<$filename"
755 or mydie("Failed to open $filename: $!");
756 my $handle = *FILE;
758 $script = { filename => $filename,
759 handle => $handle,
760 line => 0,
761 past_tokens => [],
762 tokens => [],
763 parent => $script,
766 return $script;
769 # collect script filenames which are being included
770 sub collect_filenames(@) {
771 my @ret;
773 # determine the current script's parent directory for relative
774 # file names
775 die unless defined $script;
776 my $parent_dir = $script->{filename} =~ m,^(.*/),
777 ? $1 : './';
779 foreach my $pathname (@_) {
780 # non-absolute file names are relative to the parent script's
781 # file name
782 $pathname = $parent_dir . $pathname
783 unless $pathname =~ m,^/,;
785 if ($pathname =~ m,/$,) {
786 # include all regular files in a directory
788 error("'$pathname' is not a directory")
789 unless -d $pathname;
791 local *DIR;
792 opendir DIR, $pathname
793 or error("Failed to open directory '$pathname': $!");
794 my @names = readdir DIR;
795 closedir DIR;
797 # sort those names for a well-defined order
798 foreach my $name (sort { $a cmp $b } @names) {
799 # don't include hidden and backup files
800 next if /^\.|~$/;
802 my $filename = $pathname . $name;
803 push @ret, $filename
804 if -f $filename;
806 } elsif ($pathname =~ m,\|$,) {
807 # run a program and use its output
808 push @ret, $pathname;
809 } elsif ($pathname =~ m,^\|,) {
810 error('This kind of pipe is not allowed');
811 } else {
812 # include a regular file
814 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
815 if -d $pathname;
816 error("'$pathname' is not a file")
817 unless -f $pathname;
819 push @ret, $pathname;
823 return @ret;
826 # peek a token from the queue, but don't remove it
827 sub peek_token() {
828 return unless prepare_tokens();
829 return $script->{tokens}[0];
832 # get a token from the queue
833 sub next_token() {
834 return unless prepare_tokens();
835 my $token = shift @{$script->{tokens}};
837 # update $script->{past_tokens}
838 my $past_tokens = $script->{past_tokens};
840 if (@$past_tokens > 0) {
841 my $prev_token = $past_tokens->[-1][-1];
842 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
843 if $prev_token eq ';';
844 pop @$past_tokens
845 if $prev_token eq '}';
848 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
849 push @{$past_tokens->[-1]}, $token;
851 # return
852 return $token;
855 sub expect_token($;$) {
856 my $expect = shift;
857 my $msg = shift;
858 my $token = next_token();
859 error($msg || "'$expect' expected")
860 unless defined $token and $token eq $expect;
863 # require that another token exists, and that it's not a "special"
864 # token, e.g. ";" and "{"
865 sub require_next_token {
866 my $code = shift || \&next_token;
868 my $token = &$code(@_);
870 error('unexpected end of file')
871 unless defined $token;
873 error("'$token' not allowed here")
874 if $token =~ /^[;{}]$/;
876 return $token;
879 # return the value of a variable
880 sub variable_value($) {
881 my $name = shift;
883 foreach (@stack) {
884 return $_->{vars}{$name}
885 if exists $_->{vars}{$name};
888 return $stack[0]{auto}{$name}
889 if exists $stack[0]{auto}{$name};
891 return;
894 # determine the value of a variable, die if the value is an array
895 sub string_variable_value($) {
896 my $name = shift;
897 my $value = variable_value($name);
899 error("variable '$name' must be a string, but it is an array")
900 if ref $value;
902 return $value;
905 # similar to the built-in "join" function, but also handle negated
906 # values in a special way
907 sub join_value($$) {
908 my ($expr, $value) = @_;
910 unless (ref $value) {
911 return $value;
912 } elsif (ref $value eq 'ARRAY') {
913 return join($expr, @$value);
914 } elsif (ref $value eq 'negated') {
915 # bless'negated' is a special marker for negated values
916 $value = join_value($expr, $value->[0]);
917 return bless [ $value ], 'negated';
918 } else {
919 die;
923 # returns the next parameter, which may either be a scalar or an array
924 sub getvalues {
925 my ($code, $param) = (shift, shift);
926 my %options = @_;
928 my $token = require_next_token($code, $param);
930 if ($token eq '(') {
931 # read an array until ")"
932 my @wordlist;
934 for (;;) {
935 $token = getvalues($code, $param,
936 parenthesis_allowed => 1,
937 comma_allowed => 1);
939 unless (ref $token) {
940 last if $token eq ')';
942 if ($token eq ',') {
943 error('Comma is not allowed within arrays, please use only a space');
944 next;
947 push @wordlist, $token;
948 } elsif (ref $token eq 'ARRAY') {
949 push @wordlist, @$token;
950 } else {
951 error('unknown toke type');
955 error('empty array not allowed here')
956 unless @wordlist or not $options{non_empty};
958 return @wordlist == 1
959 ? $wordlist[0]
960 : \@wordlist;
961 } elsif ($token =~ /^\`(.*)\`$/s) {
962 # execute a shell command, insert output
963 my $command = $1;
964 my $output = `$command`;
965 unless ($? == 0) {
966 if ($? == -1) {
967 error("failed to execute: $!");
968 } elsif ($? & 0x7f) {
969 error("child died with signal " . ($? & 0x7f));
970 } elsif ($? >> 8) {
971 error("child exited with status " . ($? >> 8));
975 # remove comments
976 $output =~ s/#.*//mg;
978 # tokenize
979 my @tokens = grep { length } split /\s+/s, $output;
981 my @values;
982 while (@tokens) {
983 my $value = getvalues(\&next_array_token, \@tokens);
984 push @values, to_array($value);
987 # and recurse
988 return @values == 1
989 ? $values[0]
990 : \@values;
991 } elsif ($token =~ /^\'(.*)\'$/s) {
992 # single quotes: a string
993 return $1;
994 } elsif ($token =~ /^\"(.*)\"$/s) {
995 # double quotes: a string with escapes
996 $token = $1;
997 $token =~ s,\$(\w+),string_variable_value($1),eg;
998 return $token;
999 } elsif ($token eq '!') {
1000 error('negation is not allowed here')
1001 unless $options{allow_negation};
1003 $token = getvalues($code, $param);
1005 error('it is not possible to negate an array')
1006 if ref $token and not $options{allow_array_negation};
1008 return bless [ $token ], 'negated';
1009 } elsif ($token eq ',') {
1010 return $token
1011 if $options{comma_allowed};
1013 error('comma is not allowed here');
1014 } elsif ($token eq '=') {
1015 error('equals operator ("=") is not allowed here');
1016 } elsif ($token eq '$') {
1017 my $name = require_next_token($code, $param);
1018 error('variable name expected - if you want to concatenate strings, try using double quotes')
1019 unless $name =~ /^\w+$/;
1021 my $value = variable_value($name);
1023 error("no such variable: \$$name")
1024 unless defined $value;
1026 return $value;
1027 } elsif ($token eq '&') {
1028 error("function calls are not allowed as keyword parameter");
1029 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1030 error('Syntax error');
1031 } elsif ($token =~ /^@/) {
1032 if ($token eq '@resolve') {
1033 my @params = get_function_params();
1034 error('Usage: @resolve((hostname ...))')
1035 unless @params == 1;
1036 eval { require Net::DNS; };
1037 error('For the @resolve() function, you need the Perl library Net::DNS')
1038 if $@;
1039 my $type = 'A';
1040 my $resolver = new Net::DNS::Resolver;
1041 my @result;
1042 foreach my $hostname (to_array($params[0])) {
1043 my $query = $resolver->search($hostname, $type);
1044 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1045 unless $query;
1046 foreach my $rr ($query->answer) {
1047 next unless $rr->type eq $type;
1048 push @result, $rr->address;
1051 return \@result;
1052 } else {
1053 error("unknown ferm built-in function");
1055 } else {
1056 return $token;
1060 # returns the next parameter, but only allow a scalar
1061 sub getvar {
1062 my $token = getvalues(@_);
1064 error('array not allowed here')
1065 if ref $token and ref $token eq 'ARRAY';
1067 return $token;
1070 sub get_function_params(%) {
1071 expect_token('(', 'function name must be followed by "()"');
1073 my $token = peek_token();
1074 if ($token eq ')') {
1075 require_next_token;
1076 return;
1079 my @params;
1081 while (1) {
1082 if (@params > 0) {
1083 $token = require_next_token();
1084 last
1085 if $token eq ')';
1087 error('"," expected')
1088 unless $token eq ',';
1091 push @params, getvalues(undef, undef, @_);
1094 return @params;
1097 # collect all tokens in a flat array reference until the end of the
1098 # command is reached
1099 sub collect_tokens() {
1100 my @level;
1101 my @tokens;
1103 while (1) {
1104 my $keyword = next_token();
1105 error('unexpected end of file within function/variable declaration')
1106 unless defined $keyword;
1108 if ($keyword =~ /^[\{\(]$/) {
1109 push @level, $keyword;
1110 } elsif ($keyword =~ /^[\}\)]$/) {
1111 my $expected = $keyword;
1112 $expected =~ tr/\}\)/\{\(/;
1113 my $opener = pop @level;
1114 error("unmatched '$keyword'")
1115 unless defined $opener and $opener eq $expected;
1116 } elsif ($keyword eq ';' and @level == 0) {
1117 last;
1120 push @tokens, $keyword;
1122 last
1123 if $keyword eq '}' and @level == 0;
1126 return \@tokens;
1130 # returns the specified value as an array. dereference arrayrefs
1131 sub to_array($) {
1132 my $value = shift;
1133 die unless wantarray;
1134 die if @_;
1135 unless (ref $value) {
1136 return $value;
1137 } elsif (ref $value eq 'ARRAY') {
1138 return @$value;
1139 } else {
1140 die;
1144 # evaluate the specified value as bool
1145 sub eval_bool($) {
1146 my $value = shift;
1147 die if wantarray;
1148 die if @_;
1149 unless (ref $value) {
1150 return $value;
1151 } elsif (ref $value eq 'ARRAY') {
1152 return @$value > 0;
1153 } else {
1154 die;
1158 sub is_netfilter_core_target($) {
1159 my $target = shift;
1160 die unless defined $target and length $target;
1162 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1165 sub is_netfilter_module_target($$) {
1166 my ($domain_family, $target) = @_;
1167 die unless defined $target and length $target;
1169 return defined $domain_family &&
1170 exists $target_defs{$domain_family} &&
1171 $target_defs{$domain_family}{$target};
1174 sub is_netfilter_builtin_chain($$) {
1175 my ($table, $chain) = @_;
1177 return grep { $_ eq $chain }
1178 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1181 sub netfilter_canonical_protocol($) {
1182 my $proto = shift;
1183 return 'icmpv6'
1184 if $proto eq 'ipv6-icmp';
1185 return 'mh'
1186 if $proto eq 'ipv6-mh';
1187 return $proto;
1190 sub netfilter_protocol_module($) {
1191 my $proto = shift;
1192 return unless defined $proto;
1193 return 'icmp6'
1194 if $proto eq 'icmpv6';
1195 return $proto;
1198 # escape the string in a way safe for the shell
1199 sub shell_escape($) {
1200 my $token = shift;
1202 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1204 if ($option{fast}) {
1205 # iptables-save/iptables-restore are quite buggy concerning
1206 # escaping and special characters... we're trying our best
1207 # here
1209 $token =~ s,",',g;
1210 $token = '"' . $token . '"'
1211 if $token =~ /[\s\'\\;&]/s;
1212 } else {
1213 return $token
1214 if $token =~ /^\`.*\`$/;
1215 $token =~ s/'/\\'/g;
1216 $token = '\'' . $token . '\''
1217 if $token =~ /[\s\"\\;<>&|]/s;
1220 return $token;
1223 # append an option to the shell command line, using information from
1224 # the module definition (see %match_defs etc.)
1225 sub shell_append_option($$$) {
1226 my ($ref, $keyword, $value) = @_;
1228 if (ref $value) {
1229 if (ref $value eq 'negated') {
1230 $value = $value->[0];
1231 $keyword .= ' !';
1232 } elsif (ref $value eq 'pre_negated') {
1233 $value = $value->[0];
1234 $$ref .= ' !';
1238 unless (defined $value) {
1239 $$ref .= " --$keyword";
1240 } elsif (ref $value) {
1241 if (ref $value eq 'params') {
1242 $$ref .= " --$keyword ";
1243 $$ref .= join(' ', map { shell_escape($_) } @$value);
1244 } elsif (ref $value eq 'multi') {
1245 foreach (@$value) {
1246 $$ref .= " --$keyword " . shell_escape($_);
1248 } else {
1249 die;
1251 } else {
1252 $$ref .= " --$keyword " . shell_escape($value);
1256 # convert an internal rule structure into an iptables call
1257 sub tables($$$) {
1258 my ($table_info, $chain_info, $rule) = @_;
1260 return if $option{flush};
1262 # return if this is a declaration-only rule
1263 return
1264 unless $rule->{has_rule};
1266 my $rr = '';
1268 # general iptables options
1270 my $protocol_module = $rule->{protocol_module};
1272 foreach my $option (@{$rule->{options}}) {
1273 shell_append_option(\$rr, $option->[0], $option->[1]);
1275 if ($protocol_module and $option->[0] eq 'protocol') {
1276 $rr .= " --match $option->[1]"
1277 unless exists $rule->{match}{$option->[1]};
1278 undef $protocol_module;
1282 # this line is done
1283 my $chain_rules = $chain_info->{rules} ||= [];
1284 push @$chain_rules, { rule => $rr,
1285 script => $rule->{script},
1289 sub transform_rule($$) {
1290 my ($domain, $rule) = @_;
1292 $rule->{options}[$rule->{protocol_index}][1] = 'icmpv6'
1293 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1296 sub printrule($$$$) {
1297 my ($domain, $table, $chain, $rule) = @_;
1299 transform_rule($domain, $rule);
1301 my $domain_info = $domains{$domain};
1302 $domain_info->{enabled} = 1;
1303 my $table_info = $domain_info->{tables}{$table} ||= {};
1304 my $chain_info = $table_info->{chains}{$chain} ||= {};
1306 # prints all rules in a hash
1307 tables($table_info, $chain_info, $rule);
1311 sub check_unfold(\@$$) {
1312 my ($unfold, $parent, $key) = @_;
1314 return unless ref $parent->{$key} and
1315 ref $parent->{$key} eq 'ARRAY';
1317 push @$unfold, $parent, $key, $parent->{$key};
1320 sub mkrules2($$$$) {
1321 my ($domain, $table, $chain, $fw) = @_;
1323 my @unfold;
1324 foreach my $option (@{$fw->{options}}) {
1325 push @unfold, $option
1326 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1329 if (@unfold == 0) {
1330 printrule($domain, $table, $chain, $fw);
1331 return;
1334 sub dofr {
1335 my $fw = shift;
1336 my ($domain, $table, $chain) = (shift, shift, shift);
1337 my $option = shift;
1338 my @values = @{$option->[1]};
1340 foreach my $value (@values) {
1341 $option->[1] = $value;
1342 $fw->{protocol} = $value if $option->[0] eq 'protocol';
1344 if (@_) {
1345 dofr($fw, $domain, $table, $chain, @_);
1346 } else {
1347 printrule($domain, $table, $chain, $fw);
1352 dofr($fw, $domain, $table, $chain, @unfold);
1355 # convert a bunch of internal rule structures in iptables calls,
1356 # unfold arrays during that
1357 sub mkrules($) {
1358 my $fw = shift;
1360 foreach my $domain (to_array $fw->{domain}) {
1361 foreach my $table (to_array $fw->{table}) {
1362 foreach my $chain (to_array $fw->{chain}) {
1363 mkrules2($domain, $table, $chain, $fw);
1369 sub filter_domains($) {
1370 my $domains = shift;
1371 my $result = [];
1373 foreach my $domain (to_array $domains) {
1374 next if exists $option{domain}
1375 and $domain ne $option{domain};
1377 eval {
1378 initialize_domain($domain);
1380 error($@) if $@;
1382 push @$result, $domain;
1385 return @$result == 1 ? $result->[0] : $result;
1388 # parse a keyword from a module definition
1389 sub parse_keyword($$$$) {
1390 my ($current, $def, $keyword, $negated_ref) = @_;
1392 my $params = $def->{params};
1394 my $value;
1396 my $negated;
1397 if ($$negated_ref && exists $def->{pre_negation}) {
1398 $negated = 1;
1399 undef $$negated_ref;
1402 unless (defined $params) {
1403 undef $value;
1404 } elsif (ref $params && ref $params eq 'CODE') {
1405 $value = &$params($current);
1406 } elsif ($params eq 'm') {
1407 $value = bless [ to_array getvalues() ], 'multi';
1408 } elsif ($params =~ /^[a-z]/) {
1409 if (exists $def->{negation} and not $negated) {
1410 my $token = peek_token();
1411 if ($token eq '!') {
1412 require_next_token;
1413 $negated = 1;
1417 my @params;
1418 foreach my $p (split(//, $params)) {
1419 if ($p eq 's') {
1420 push @params, getvar();
1421 } elsif ($p eq 'c') {
1422 my @v = to_array getvalues(undef, undef,
1423 non_empty => 1);
1424 push @params, join(',', @v);
1425 } else {
1426 die;
1430 $value = @params == 1
1431 ? $params[0]
1432 : bless \@params, 'params';
1433 } elsif ($params == 1) {
1434 if (exists $def->{negation} and not $negated) {
1435 my $token = peek_token();
1436 if ($token eq '!') {
1437 require_next_token;
1438 $negated = 1;
1442 $value = getvalues();
1444 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1445 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1446 } else {
1447 if (exists $def->{negation} and not $negated) {
1448 my $token = peek_token();
1449 if ($token eq '!') {
1450 require_next_token;
1451 $negated = 1;
1455 $value = bless [ map {
1456 getvar()
1457 } (1..$params) ], 'params';
1460 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1461 if $negated;
1463 return $value;
1466 sub append_option(\%$$) {
1467 my ($rule, $name, $value) = @_;
1468 push @{$rule->{options}}, [ $name, $value ];
1471 # parse options of a module
1472 sub parse_option($$$$) {
1473 my ($def, $current, $keyword, $negated_ref) = @_;
1475 while (exists $def->{alias}) {
1476 ($keyword, $def) = @{$def->{alias}};
1477 die unless defined $def;
1480 append_option(%$current, $keyword,
1481 parse_keyword($current, $def, $keyword, $negated_ref));
1482 return 1;
1485 # parse options for a protocol module definition
1486 sub parse_protocol_options($$$$) {
1487 my ($current, $proto, $keyword, $negated_ref) = @_;
1489 my $domain_family = $current->{'domain_family'};
1490 my $proto_defs = $proto_defs{$domain_family};
1491 return unless defined $proto_defs;
1493 my $proto_def = $proto_defs->{$proto};
1494 return unless defined $proto_def and
1495 exists $proto_def->{keywords}{$keyword};
1497 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1498 unless (exists $current->{match}{$module_name}) {
1499 append_option(%$current, 'match', $module_name);
1500 $current->{match}{$module_name} = 1;
1503 return parse_option($proto_def->{keywords}{$keyword},
1504 $current,
1505 $keyword, $negated_ref);
1508 sub copy_on_write($$) {
1509 my ($rule, $key) = @_;
1510 return unless exists $rule->{cow}{$key};
1511 $rule->{$key} = {%{$rule->{$key}}};
1512 delete $rule->{cow}{$key};
1515 sub new_level(\%$) {
1516 my ($current, $prev) = @_;
1518 %$current = ();
1519 if (defined $prev) {
1520 # copy data from previous level
1521 $current->{cow} = { keywords => 1, };
1522 $current->{keywords} = $prev->{keywords};
1523 $current->{match} = { %{$prev->{match}} };
1524 $current->{options} = [@{$prev->{options}}];
1525 foreach my $key (qw(domain domain_family table chain protocol protocol_index protocol_module has_action)) {
1526 $current->{$key} = $prev->{$key}
1527 if exists $prev->{$key};
1529 } else {
1530 $current->{cow} = {};
1531 $current->{keywords} = {};
1532 $current->{match} = {};
1533 $current->{options} = [];
1537 sub merge_keywords(\%$$$) {
1538 my ($rule, $type, $module, $keywords) = @_;
1539 copy_on_write($rule, 'keywords');
1540 while (my ($name, $def) = each %$keywords) {
1541 $rule->{keywords}{$name} = [ $type, $module, $def ];
1545 sub set_domain(\%$) {
1546 my ($rule, $domain) = @_;
1548 my $filtered_domain = filter_domains($domain);
1549 my $domain_family;
1550 unless (ref $domain) {
1551 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1552 } elsif (@$domain == 0) {
1553 $domain_family = 'none';
1554 } elsif (grep { not /^ip6?$/s } @$domain) {
1555 error('Cannot combine non-IP domains');
1556 } else {
1557 $domain_family = 'ip';
1560 $rule->{domain_family} = $domain_family;
1561 $rule->{keywords} = get_builtin_keywords($domain_family);
1562 delete $rule->{cow}{keywords};
1564 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1567 sub set_module_target(\%$$) {
1568 my ($rule, $name, $defs) = @_;
1570 if ($name eq 'TCPMSS') {
1571 my $protos = $rule->{protocol};
1572 error('No protocol specified before TCPMSS')
1573 unless defined $protos;
1574 foreach my $proto (to_array $protos) {
1575 error('TCPMSS not available for protocol "$proto"')
1576 unless $proto eq 'tcp';
1580 merge_keywords(%$rule, 'target', $name, $defs->{keywords});
1583 # the main parser loop: read tokens, convert them into internal rule
1584 # structures
1585 sub enter($$) {
1586 my $lev = shift; # current recursion depth
1587 my $prev = shift; # previous rule hash
1589 # enter is the core of the firewall setup, it is a
1590 # simple parser program that recognizes keywords and
1591 # retreives parameters to set up the kernel routing
1592 # chains
1594 my $base_level = $script->{base_level} || 0;
1595 die if $base_level > $lev;
1597 my %current;
1598 new_level(%current, $prev);
1600 # read keywords 1 by 1 and dump into parser
1601 while (defined (my $keyword = next_token())) {
1602 # check if the current rule should be negated
1603 my $negated = $keyword eq '!';
1604 if ($negated) {
1605 # negation. get the next word which contains the 'real'
1606 # rule
1607 $keyword = getvar();
1609 error('unexpected end of file after negation')
1610 unless defined $keyword;
1613 # the core: parse all data
1614 for ($keyword)
1616 # deprecated keyword?
1617 if (exists $deprecated_keywords{$keyword}) {
1618 my $new_keyword = $deprecated_keywords{$keyword};
1619 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1620 $keyword = $new_keyword;
1623 # effectuation operator
1624 if ($keyword eq ';') {
1625 if ($current{has_rule} and not exists $current{has_action}) {
1626 # something is wrong when a rule was specifiedd,
1627 # but no action
1628 error('No action defined; did you mean "NOP"?');
1631 error('No chain defined') unless exists $current{chain};
1633 $current{script} = { filename => $script->{filename},
1634 line => $script->{line},
1637 mkrules(\%current);
1639 # and clean up variables set in this level
1640 new_level(%current, $prev);
1642 next;
1645 # conditional expression
1646 if ($keyword eq '@if') {
1647 unless (eval_bool(getvalues)) {
1648 collect_tokens;
1649 my $token = peek_token();
1650 require_next_token() if $token and $token eq '@else';
1653 next;
1656 if ($keyword eq '@else') {
1657 # hack: if this "else" has not been eaten by the "if"
1658 # handler above, we believe it came from an if clause
1659 # which evaluated "true" - remove the "else" part now.
1660 collect_tokens;
1661 next;
1664 # hooks for custom shell commands
1665 if ($keyword eq 'hook') {
1666 error('"hook" must be the first token in a command')
1667 if exists $current{domain};
1669 my $position = getvar();
1670 my $hooks;
1671 if ($position eq 'pre') {
1672 $hooks = \@pre_hooks;
1673 } elsif ($position eq 'post') {
1674 $hooks = \@post_hooks;
1675 } else {
1676 error("Invalid hook position: '$position'");
1679 push @$hooks, getvar();
1681 expect_token(';');
1682 next;
1685 # recursing operators
1686 if ($keyword eq '{') {
1687 # push stack
1688 my $old_stack_depth = @stack;
1690 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1692 # recurse
1693 enter($lev + 1, \%current);
1695 # pop stack
1696 shift @stack;
1697 die unless @stack == $old_stack_depth;
1699 # after a block, the command is finished, clear this
1700 # level
1701 new_level(%current, $prev);
1703 next;
1706 if ($keyword eq '}') {
1707 error('Unmatched "}"')
1708 if $lev <= $base_level;
1710 # consistency check: check if they havn't forgotten
1711 # the ';' before the last statement
1712 error('Missing semicolon before "}"')
1713 if $current{has_rule};
1715 # and exit
1716 return;
1719 # include another file
1720 if ($keyword eq '@include' or $keyword eq 'include') {
1721 my @files = collect_filenames to_array getvalues;
1722 $keyword = next_token;
1723 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1724 unless defined $keyword and $keyword eq ';';
1726 foreach my $filename (@files) {
1727 # save old script, open new script
1728 my $old_script = $script;
1729 open_script($filename);
1730 $script->{base_level} = $lev + 1;
1732 # push stack
1733 my $old_stack_depth = @stack;
1735 my $stack = {};
1737 if (@stack > 0) {
1738 # include files may set variables for their parent
1739 $stack->{vars} = ($stack[0]{vars} ||= {});
1740 $stack->{functions} = ($stack[0]{functions} ||= {});
1741 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1744 unshift @stack, $stack;
1746 # parse the script
1747 enter($lev + 1, \%current);
1749 # pop stack
1750 shift @stack;
1751 die unless @stack == $old_stack_depth;
1753 # restore old script
1754 $script = $old_script;
1757 next;
1760 # definition of a variable or function
1761 if ($keyword eq '@def' or $keyword eq 'def') {
1762 error('"def" must be the first token in a command')
1763 if $current{has_rule};
1765 my $type = require_next_token();
1766 if ($type eq '$') {
1767 my $name = require_next_token();
1768 error('invalid variable name')
1769 unless $name =~ /^\w+$/;
1771 expect_token('=');
1773 my $value = getvalues(undef, undef, allow_negation => 1);
1775 expect_token(';');
1777 $stack[0]{vars}{$name} = $value
1778 unless exists $stack[-1]{vars}{$name};
1779 } elsif ($type eq '&') {
1780 my $name = require_next_token();
1781 error('invalid function name')
1782 unless $name =~ /^\w+$/;
1784 expect_token('(', 'function parameter list or "()" expected');
1786 my @params;
1787 while (1) {
1788 my $token = require_next_token();
1789 last if $token eq ')';
1791 if (@params > 0) {
1792 error('"," expected')
1793 unless $token eq ',';
1795 $token = require_next_token();
1798 error('"$" and parameter name expected')
1799 unless $token eq '$';
1801 $token = require_next_token();
1802 error('invalid function parameter name')
1803 unless $token =~ /^\w+$/;
1805 push @params, $token;
1808 my %function;
1810 $function{params} = \@params;
1812 expect_token('=');
1814 my $tokens = collect_tokens();
1815 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1816 $function{tokens} = $tokens;
1818 $stack[0]{functions}{$name} = \%function
1819 unless exists $stack[-1]{functions}{$name};
1820 } else {
1821 error('"$" (variable) or "&" (function) expected');
1824 next;
1827 # def references
1828 if ($keyword eq '$') {
1829 error('variable references are only allowed as keyword parameter');
1832 if ($keyword eq '&') {
1833 my $name = require_next_token;
1834 error('function name expected')
1835 unless $name =~ /^\w+$/;
1837 my $function;
1838 foreach (@stack) {
1839 $function = $_->{functions}{$name};
1840 last if defined $function;
1842 error("no such function: \&$name")
1843 unless defined $function;
1845 my $paramdef = $function->{params};
1846 die unless defined $paramdef;
1848 my @params = get_function_params(allow_negation => 1);
1850 error("Wrong number of parameters for function '\&$name': "
1851 . @$paramdef . " expected, " . @params . " given")
1852 unless @params == @$paramdef;
1854 my %vars;
1855 for (my $i = 0; $i < @params; $i++) {
1856 $vars{$paramdef->[$i]} = $params[$i];
1859 if ($function->{block}) {
1860 # block {} always ends the current rule, so if the
1861 # function contains a block, we have to require
1862 # the calling rule also ends here
1863 expect_token(';');
1866 my @tokens = @{$function->{tokens}};
1867 for (my $i = 0; $i < @tokens; $i++) {
1868 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1869 exists $vars{$tokens[$i + 1]}) {
1870 my @value = to_array($vars{$tokens[$i + 1]});
1871 @value = ('(', @value, ')')
1872 unless @tokens == 1;
1873 splice(@tokens, $i, 2, @value);
1874 $i += @value - 2;
1875 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1876 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1880 unshift @{$script->{tokens}}, @tokens;
1882 next;
1885 # where to put the rule?
1886 if ($keyword eq 'domain') {
1887 error('Domain is already specified')
1888 if exists $current{domain};
1890 set_domain(%current, getvalues());
1891 next;
1894 if ($keyword eq 'table') {
1895 error('Table is already specified')
1896 if exists $current{table};
1897 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1899 set_domain(%current, 'ip')
1900 unless exists $current{domain};
1902 next;
1905 if ($keyword eq 'chain') {
1906 error('Chain is already specified')
1907 if exists $current{chain};
1908 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1910 # ferm 1.1 allowed lower case built-in chain names
1911 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1912 error('Please write built-in chain names in upper case')
1913 if /^(?:input|forward|output|prerouting|postrouting)$/;
1916 set_domain(%current, 'ip')
1917 unless exists $current{domain};
1919 $current{table} = 'filter'
1920 unless exists $current{table};
1922 next;
1925 error('Chain must be specified')
1926 unless exists $current{chain};
1928 # policy for built-in chain
1929 if ($keyword eq 'policy') {
1930 error('Cannot specify matches for policy')
1931 if $current{has_rule};
1933 my $policy = getvar();
1934 error("Invalid policy target: $policy")
1935 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1937 expect_token(';');
1939 foreach my $domain (to_array $current{domain}) {
1940 foreach my $table (to_array $current{table}) {
1941 foreach my $chain (to_array $current{chain}) {
1942 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1947 new_level(%current, $prev);
1948 next;
1951 # create a subchain
1952 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1953 error('Chain must be specified')
1954 unless exists $current{chain};
1956 error('No rule specified before "@subchain"')
1957 unless $current{has_rule};
1959 my $subchain;
1960 $keyword = next_token();
1962 if ($keyword =~ /^(["'])(.*)\1$/s) {
1963 $subchain = $2;
1964 $keyword = next_token();
1965 } else {
1966 $subchain = 'ferm_auto_' . ++$auto_chain;
1969 error('"{" or chain name expected after "@subchain"')
1970 unless $keyword eq '{';
1972 # create a deep copy of %current, only containing values
1973 # which must be in the subchain
1974 my %inner = ( cow => { keywords => 1, },
1975 keywords => $current{keywords},
1976 match => {},
1977 options => [],
1979 $inner{domain} = $current{domain};
1980 $inner{domain_family} = $current{domain_family};
1981 $inner{table} = $current{table};
1982 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1984 if (exists $current{protocol}) {
1985 $inner{protocol} = $current{protocol};
1986 $inner{protocol_index} = 0;
1987 append_option(%inner, 'protocol', $inner{protocol});
1990 # enter the block
1991 enter(1, \%inner);
1993 # now handle the parent - it's a jump to the sub chain
1994 $current{has_action} = 1;
1995 append_option(%current, 'jump', $subchain);
1997 $current{script} = { filename => $script->{filename},
1998 line => $script->{line},
2001 mkrules(\%current);
2003 # and clean up variables set in this level
2004 new_level(%current, $prev);
2006 next;
2009 # everything else must be part of a "real" rule, not just
2010 # "policy only"
2011 $current{has_rule}++;
2013 # extended parameters:
2014 if ($keyword =~ /^mod(?:ule)?$/) {
2015 foreach my $module (to_array getvalues) {
2016 next if exists $current{match}{$module};
2018 my $domain_family = $current{domain_family};
2019 my $defs = $match_defs{$domain_family}{$module};
2020 if (not defined $defs and exists $current{protocol}) {
2021 my $proto = $current{protocol};
2022 unless (ref $proto) {
2023 $proto = netfilter_canonical_protocol($current{protocol});
2024 $defs = $proto_defs{$domain_family}{$proto}
2025 if netfilter_protocol_module($proto) eq $module;
2029 $current{match}{$module} = 1;
2031 merge_keywords(%current, 'match', $module, $defs->{keywords})
2032 if defined $defs;
2034 append_option(%current, 'match', $module);
2037 next;
2040 # keywords from $current{keywords}
2042 if (exists $current{keywords}{$keyword}) {
2043 my ($type, $module, $def) = @{$current{keywords}{$keyword}};
2044 parse_option($def, \%current, $keyword, \$negated);
2045 next;
2049 # actions
2052 # jump action
2053 if ($keyword eq 'jump') {
2054 error('There can only one action per rule')
2055 if exists $current{has_action};
2056 my $chain = getvar();
2057 if (my $defs = is_netfilter_module_target($current{domain_family}, $chain)) {
2058 set_module_target(%current, $chain, $defs);
2060 $current{has_action} = 1;
2061 append_option(%current, 'jump', $chain);
2062 next;
2065 # goto action
2066 if ($keyword eq 'realgoto') {
2067 error('There can only one action per rule')
2068 if exists $current{has_action};
2069 append_option(%current, 'goto', getvar());
2070 $current{has_action} = 1;
2071 next;
2074 # action keywords
2075 if (is_netfilter_core_target($keyword)) {
2076 error('There can only one action per rule')
2077 if exists $current{has_action};
2078 $current{has_action} = 1;
2079 append_option(%current, 'jump', $keyword);
2080 next;
2083 if ($keyword eq 'NOP') {
2084 error('There can only one action per rule')
2085 if exists $current{has_action};
2086 $current{has_action} = 1;
2087 next;
2090 if (my $defs = is_netfilter_module_target($current{domain_family}, $keyword)) {
2091 error('There can only one action per rule')
2092 if exists $current{has_action};
2094 set_module_target(%current, $keyword, $defs);
2095 $current{has_action} = 1;
2096 append_option(%current, 'jump', $keyword);
2097 next;
2100 my $proto = $current{protocol};
2103 # protocol specific options
2106 if (defined $proto and not ref $proto) {
2107 $proto = netfilter_canonical_protocol($proto);
2109 if ($proto eq 'icmp') {
2110 my $domains = $current{domain};
2111 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2114 parse_protocol_options(\%current, $proto, $keyword, \$negated)
2115 and next;
2118 if ($keyword eq 'proto') {
2119 $current{protocol} = parse_keyword(\%current,
2120 { params => 1,
2121 negation => 1 },
2122 'proto', \$negated);
2123 $current{protocol_index} = scalar(@{$current{options}});
2124 append_option(%current, 'protocol', $current{protocol});
2125 next;
2128 # port switches
2129 if ($keyword =~ /^[sd]port$/) {
2130 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2131 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2133 append_option(%current, $keyword,
2134 getvalues(undef, undef,
2135 allow_negation => 1));
2136 $current{protocol_module} = 1;
2137 next;
2140 # default
2141 error("Unrecognized keyword: $keyword");
2144 # if the rule didn't reset the negated flag, it's not
2145 # supported
2146 error("Doesn't support negation: $keyword")
2147 if $negated;
2150 error('Missing "}" at end of file')
2151 if $lev > $base_level;
2153 # consistency check: check if they havn't forgotten
2154 # the ';' before the last statement
2155 error("Missing semicolon before end of file")
2156 if exists $current{domain};
2159 sub execute_command {
2160 my ($command, $script) = @_;
2162 print LINES "$command\n"
2163 if $option{lines};
2164 return if $option{noexec};
2166 my $ret = system($command);
2167 unless ($ret == 0) {
2168 if ($? == -1) {
2169 print STDERR "failed to execute: $!\n";
2170 exit 1;
2171 } elsif ($? & 0x7f) {
2172 printf STDERR "child died with signal %d\n", $? & 0x7f;
2173 return 1;
2174 } else {
2175 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2176 if defined $script;
2177 return $? >> 8;
2181 return;
2184 sub execute_slow($$) {
2185 my ($domain, $domain_info) = @_;
2187 my $domain_cmd = $domain_info->{tools}{tables};
2189 my $status;
2190 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2191 my $table_cmd = "$domain_cmd -t $table";
2193 # reset chain policies
2194 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2195 next unless $chain_info->{builtin} or
2196 (not $table_info->{has_builtin} and
2197 is_netfilter_builtin_chain($table, $chain));
2198 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2199 unless $option{noflush};
2202 # clear
2203 unless ($option{noflush}) {
2204 $status ||= execute_command("$table_cmd -F");
2205 $status ||= execute_command("$table_cmd -X");
2208 next if $option{flush};
2210 # create chains / set policy
2211 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2212 if (exists $chain_info->{policy}) {
2213 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2214 unless $chain_info->{policy} eq 'ACCEPT';
2215 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2216 $status ||= execute_command("$table_cmd -N $chain");
2220 # dump rules
2221 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2222 my $chain_cmd = "$table_cmd -A $chain";
2223 foreach my $rule (@{$chain_info->{rules}}) {
2224 $status ||= execute_command($chain_cmd . $rule->{rule});
2229 return $status;
2232 sub rules_to_save($$) {
2233 my ($domain, $domain_info) = @_;
2235 # convert this into an iptables-save text
2236 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2238 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2239 # select table
2240 $result .= '*' . $table . "\n";
2242 # create chains / set policy
2243 foreach my $chain (sort keys %{$table_info->{chains}}) {
2244 my $chain_info = $table_info->{chains}{$chain};
2245 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2246 unless (defined $policy) {
2247 if (is_netfilter_builtin_chain($table, $chain)) {
2248 $policy = 'ACCEPT';
2249 } else {
2250 $policy = '-';
2253 $result .= ":$chain $policy\ [0:0]\n";
2256 next if $option{flush};
2258 # dump rules
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 .= "-A $chain$rule->{rule}\n";
2266 # do it
2267 $result .= "COMMIT\n";
2270 return $result;
2273 sub restore_domain($$) {
2274 my ($domain, $save) = @_;
2276 my $path = $domains{$domain}{tools}{'tables-restore'};
2278 local *RESTORE;
2279 open RESTORE, "|$path"
2280 or die "Failed to run $path: $!\n";
2282 print RESTORE $save;
2284 close RESTORE
2285 or die "Failed to run $path\n";
2288 sub execute_fast($$) {
2289 my ($domain, $domain_info) = @_;
2291 my $save = rules_to_save($domain, $domain_info);
2293 if ($option{lines}) {
2294 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2295 if $option{shell};
2296 print LINES $save;
2297 print LINES "EOT\n"
2298 if $option{shell};
2301 return if $option{noexec};
2303 eval {
2304 restore_domain($domain, $save);
2306 if ($@) {
2307 print STDERR $@;
2308 return 1;
2311 return;
2314 sub rollback() {
2315 my $error;
2316 while (my ($domain, $domain_info) = each %domains) {
2317 next unless $domain_info->{enabled};
2318 unless (defined $domain_info->{tools}{'tables-restore'}) {
2319 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2320 next;
2323 my $reset = '';
2324 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2325 my $reset_chain = '';
2326 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2327 next unless is_netfilter_builtin_chain($table, $chain);
2328 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2330 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2331 if length $reset_chain;
2334 $reset .= $domain_info->{previous}
2335 if defined $domain_info->{previous};
2337 restore_domain($domain, $reset);
2340 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2341 exit 1;
2344 sub alrm_handler {
2345 # do nothing, just interrupt a system call
2348 sub confirm_rules() {
2349 $SIG{ALRM} = \&alrm_handler;
2351 alarm(5);
2353 print STDERR "\n"
2354 . "ferm has applied the new firewall rules.\n"
2355 . "Please type 'yes' to confirm:\n";
2356 STDERR->flush();
2358 alarm(30);
2360 my $line = '';
2361 STDIN->sysread($line, 3);
2363 eval {
2364 require POSIX;
2365 POSIX::tcflush(*STDIN, 2);
2367 print STDERR "$@" if $@;
2369 $SIG{ALRM} = 'DEFAULT';
2371 return $line eq 'yes';
2374 # end of ferm
2376 __END__
2378 =head1 NAME
2380 ferm - a firewall rule parser for linux
2382 =head1 SYNOPSIS
2384 B<ferm> I<options> I<inputfiles>
2386 =head1 OPTIONS
2388 -n, --noexec Do not execute the rules, just simulate
2389 -F, --flush Flush all netfilter tables managed by ferm
2390 -l, --lines Show all rules that were created
2391 -i, --interactive Interactive mode: revert if user does not confirm
2392 --remote Remote mode; ignore host specific configuration.
2393 This implies --noexec and --lines.
2394 -V, --version Show current version number
2395 -h, --help Look at this text
2396 --fast Generate an iptables-save file, used by iptables-restore
2397 --shell Generate a shell script which calls iptables-restore
2398 --domain {ip|ip6} Handle only the specified domain
2399 --def '$name=v' Override a variable
2401 =cut