removed the "was_created" flag
[ferm.git] / src / ferm
blob03319b60113d6d92cc2bd19c4585694b0ac73fa1
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2007 Auke Kok, Max Kellermann
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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 # - reset: has this domain already been reset?
74 # - tables{$name}: ferm state information about tables
75 # - chains{$chain}: ferm state information about the chains
76 # - builtin: whether this is a built-in chain
77 # - non_empty: are there rules for this chain?
78 use vars qw(%domains);
80 ## constants
81 use vars qw(%deprecated_keywords);
83 # keywords from ferm 1.1 which are deprecated, and the new one; these
84 # are automatically replaced, and a warning is printed
85 %deprecated_keywords = ( goto => 'jump',
88 # these hashes provide the Netfilter module definitions
89 use vars qw(%proto_defs %match_defs %target_defs);
92 # This subsubsystem allows you to support (most) new netfilter modules
93 # in ferm. Add a call to one of the "add_XY_def()" functions below.
95 # Ok, now about the cryptic syntax: the function "add_XY_def()"
96 # registers a new module. There are three kinds of modules: protocol
97 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
98 # target modules (e.g. DNAT, MARK).
100 # The first parameter is always the module name which is passed to
101 # iptables with "-p", "-m" or "-j" (depending on which kind of module
102 # this is).
104 # After that, you add an encoded string for each option the module
105 # supports. This is where it becomes tricky.
107 # foo defaults to an option with one argument (which may be a ferm
108 # array)
110 # foo*0 option without any arguments
112 # foo=s one argument which must not be a ferm array ('s' stands for
113 # 'scalar')
115 # u32=m an array which renders into multiple iptables options in one
116 # rule
118 # ctstate=c one argument, if it's an array, pass it to iptables as a
119 # single comma separated value; example:
120 # ctstate (ESTABLISHED RELATED) translates to:
121 # --ctstate ESTABLISHED,RELATED
123 # foo=sac three arguments: scalar, array, comma separated; you may
124 # concatenate more than one letter code after the '='
126 # foo&bar one argument; call the perl function '&bar()' which parses
127 # the argument
129 # !foo negation is allowed and the '!' is written before the keyword
131 # foo! same as above, but '!' is after the keyword and before the
132 # parameters
134 # to:=to-destination makes "to" an alias for "to-destination"; you have
135 # to add a declaration for option "to-destination"
138 # add a module definition
139 sub add_def_x {
140 my $defs = shift;
141 my $domain_family = shift;
142 my $params_default = shift;
143 my $name = shift;
144 die if exists $defs->{$domain_family}{$name};
145 my $def = $defs->{$domain_family}{$name} = {};
146 foreach (@_) {
147 my $keyword = $_;
148 my $k = {};
150 my $params = $params_default;
151 $params = $1 if $keyword =~ s,\*(\d+)$,,;
152 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
153 if ($keyword =~ s,&(\S+)$,,) {
154 $params = eval "\\&$1";
155 die $@ if $@;
157 $k->{params} = $params if $params;
159 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
160 $k->{negation} = 1 if $keyword =~ s,!$,,;
162 $k->{alias} = [$1, $def->{keywords}{$1} || die] if $keyword =~ s,:=(\S+)$,,;
164 $def->{keywords}{$keyword} = $k;
167 return $def;
170 # add a protocol module definition
171 sub add_proto_def_x(@) {
172 my $domain_family = shift;
173 add_def_x(\%proto_defs, $domain_family, 1, @_);
176 # add a match module definition
177 sub add_match_def_x(@) {
178 my $domain_family = shift;
179 add_def_x(\%match_defs, $domain_family, 1, @_);
182 # add a target module definition
183 sub add_target_def_x(@) {
184 my $domain_family = shift;
185 add_def_x(\%target_defs, $domain_family, 's', @_);
188 sub add_def {
189 my $defs = shift;
190 add_def_x($defs, 'ip', @_);
193 # add a protocol module definition
194 sub add_proto_def(@) {
195 add_def(\%proto_defs, 1, @_);
198 # add a match module definition
199 sub add_match_def(@) {
200 add_def(\%match_defs, 1, @_);
203 # add a target module definition
204 sub add_target_def(@) {
205 add_def(\%target_defs, 's', @_);
208 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
209 add_proto_def 'mh', qw(mh-type!);
210 add_proto_def 'icmp', qw(icmp-type!);
211 add_proto_def 'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
212 add_proto_def 'sctp', qw(chunk-types!=sc);
213 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
214 add_proto_def 'udp', qw();
216 add_match_def '',
217 # --protocol
218 qw(protocol! proto:=protocol),
219 # --source, --destination
220 qw(source! saddr:=source destination! daddr:=destination),
221 # --in-interface
222 qw(in-interface! interface:=in-interface if:=in-interface),
223 # --out-interface
224 qw(out-interface! outerface:=out-interface of:=out-interface),
225 # --fragment
226 qw(!fragment*0);
227 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
228 add_match_def 'addrtype', qw(src-type dst-type);
229 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
230 add_match_def 'comment', qw(comment=s);
231 add_match_def 'condition', qw(condition!);
232 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
233 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
234 add_match_def 'connmark', qw(mark);
235 add_match_def 'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
236 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
237 add_match_def 'dscp', qw(dscp dscp-class);
238 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
239 add_match_def 'esp', qw(espspi!);
240 add_match_def 'eui64';
241 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
242 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
243 add_match_def 'helper', qw(helper);
244 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
245 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
246 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
247 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
248 add_match_def 'iprange', qw(!src-range !dst-range);
249 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
250 add_match_def 'ipv6header', qw(header!=c soft*0);
251 add_match_def 'length', qw(length!);
252 add_match_def 'limit', qw(limit=s limit-burst=s);
253 add_match_def 'mac', qw(mac-source!);
254 add_match_def 'mark', qw(mark);
255 add_match_def 'multiport', qw(source-ports!&multiport_params),
256 qw(destination-ports!&multiport_params ports!&multiport_params);
257 add_match_def 'nth', qw(every counter start packet);
258 add_match_def 'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
259 add_match_def 'physdev', qw(physdev-in! physdev-out!),
260 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
261 add_match_def 'pkttype', qw(pkt-type),
262 add_match_def 'policy',
263 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
264 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
265 qw(psd-lo-ports-weight psd-hi-ports-weight);
266 add_match_def 'quota', qw(quota=s);
267 add_match_def 'random', qw(average);
268 add_match_def 'realm', qw(realm!);
269 add_match_def 'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
270 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
271 add_match_def 'set', qw(set=sc);
272 add_match_def 'state', qw(state=c);
273 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
274 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
275 add_match_def 'tcpmss', qw(!mss);
276 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
277 qw(!monthday=c !weekdays=c utc*0 localtz*0);
278 add_match_def 'tos', qw(!tos);
279 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
280 add_match_def 'u32', qw(!u32=m);
282 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
283 add_target_def 'CLASSIFY', qw(set-class);
284 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
285 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
286 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
287 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
288 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
289 add_target_def 'ECN', qw(ecn-tcp-remove*0);
290 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
291 add_target_def 'IPV4OPTSSTRIP';
292 add_target_def 'LOG', qw(log-level log-prefix),
293 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
294 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
295 add_target_def 'MASQUERADE', qw(to-ports random*0);
296 add_target_def 'MIRROR';
297 add_target_def 'NETMAP', qw(to);
298 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
299 add_target_def 'NFQUEUE', qw(queue-num);
300 add_target_def 'NOTRACK';
301 add_target_def 'REDIRECT', qw(to-ports random*0);
302 add_target_def 'REJECT', qw(reject-with);
303 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
304 add_target_def 'SAME', qw(to nodst*0 random*0);
305 add_target_def 'SECMARK', qw(selctx);
306 add_target_def 'SET', qw(add-set=sc del-set=sc);
307 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
308 add_target_def 'TARPIT';
309 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
310 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
311 add_target_def 'TRACE';
312 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
313 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
315 add_match_def_x 'arp', '',
316 # ip
317 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
318 # mac
319 qw(source-mac! destination-mac!),
320 # --in-interface
321 qw(in-interface! interface:=in-interface if:=in-interface),
322 # --out-interface
323 qw(out-interface! outerface:=out-interface of:=out-interface),
324 # misc
325 qw(h-length=s opcode=s h-type=s proto-type=s),
326 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
328 add_match_def_x 'eb', '',
329 # protocol
330 qw(protocol! proto:=protocol),
331 # --in-interface
332 qw(in-interface! interface:=in-interface if:=in-interface),
333 # --out-interface
334 qw(out-interface! outerface:=out-interface of:=out-interface),
335 # logical interface
336 qw(logical-in! logical-out!),
337 # --source, --destination
338 qw(source! saddr:=source destination! daddr:=destination),
339 # 802.3
340 qw(802_3-sap! 802_3-type!),
341 # arp
342 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
343 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
344 # ip
345 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
346 # mark_m
347 qw(mark!),
348 # pkttype
349 qw(pkttype-type!),
350 # stp
351 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
352 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
353 qw(stp-hello-time! stp-forward-delay!),
354 # vlan
355 qw(vlan-id! vlan-prio! vlan-encap!),
356 # log
357 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
359 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
360 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
361 add_target_def_x 'eb', 'mark', qw(set-mark mark-target);
362 add_target_def_x 'eb', 'redirect', qw(redirect-target);
363 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
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->{builtin}{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_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 'lines|l' => \$opt_lines,
444 'interactive|i' => \$opt_interactive,
445 'verbose|v' => \$opt_verbose,
446 'debug|d' => \$opt_debug,
447 'help|h' => \$opt_help,
448 'version|V' => \$opt_version,
449 test => \$opt_test,
450 remote => \$opt_test,
451 fast => \$opt_fast,
452 shell => \$opt_shell,
453 'domain=s' => \$opt_domain,
454 'def=s' => \&opt_def,
457 if (defined $opt_help) {
458 require Pod::Usage;
459 Pod::Usage::pod2usage(-exitstatus => 0);
462 if (defined $opt_version) {
463 printversion();
464 exit 0;
467 $option{'noexec'} = (defined $opt_noexec);
468 $option{flush} = defined $opt_flush;
469 $option{'lines'} = (defined $opt_lines);
470 $option{interactive} = (defined $opt_interactive);
471 $option{test} = (defined $opt_test);
473 if ($option{test}) {
474 $option{noexec} = 1;
475 $option{lines} = 1;
478 delete $option{interactive} if $option{noexec};
480 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
481 if $option{interactive} and not -t STDIN;
482 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
483 if $option{interactive} and not -t STDERR;
485 $option{fast} = 1 if defined $opt_fast;
487 if (defined $opt_shell) {
488 $option{$_} = 1 foreach qw(shell fast lines);
491 $option{domain} = $opt_domain if defined $opt_domain;
493 print STDERR "Warning: ignoring the obsolete --debug option\n"
494 if defined $opt_debug;
495 print STDERR "Warning: ignoring the obsolete --verbose option\n"
496 if defined $opt_verbose;
497 } else {
498 # tiny getopt emulation for microperl
499 my $filename;
500 foreach (@ARGV) {
501 if ($_ eq '--noexec' or $_ eq '-n') {
502 $option{noexec} = 1;
503 } elsif ($_ eq '--lines' or $_ eq '-l') {
504 $option{lines} = 1;
505 } elsif ($_ eq '--fast') {
506 $option{fast} = 1;
507 } elsif ($_ eq '--test') {
508 $option{test} = 1;
509 $option{noexec} = 1;
510 $option{lines} = 1;
511 } elsif ($_ eq '--shell') {
512 $option{$_} = 1 foreach qw(shell fast lines);
513 } elsif (/^-/) {
514 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
515 exit 1;
516 } else {
517 $filename = $_;
520 undef @ARGV;
521 push @ARGV, $filename;
524 unless (@ARGV == 1) {
525 require Pod::Usage;
526 Pod::Usage::pod2usage(-exitstatus => 1);
529 if ($has_strict) {
530 open LINES, ">&STDOUT" if $option{lines};
531 open STDOUT, ">&STDERR" if $option{shell};
532 } else {
533 # microperl can't redirect file handles
534 *LINES = *STDOUT;
536 if ($option{fast} and not $option{noexec}) {
537 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
538 exit 1
542 unshift @stack, {};
543 open_script($ARGV[0]);
545 # parse all input recursively
546 enter(0);
547 die unless @stack == 2;
549 # execute all generated rules
550 my $status;
552 foreach my $cmd (@pre_hooks) {
553 print LINES "$cmd\n" if $option{lines};
554 system($cmd) unless $option{noexec};
557 while (my ($domain, $domain_info) = each %domains) {
558 next unless $domain_info->{enabled};
559 my $s = $option{fast} &&
560 defined $domain_info->{tools}{'tables-restore'}
561 ? execute_fast($domain, $domain_info)
562 : execute_slow($domain, $domain_info);
563 $status = $s if defined $s;
566 foreach my $cmd (@post_hooks) {
567 print "$cmd\n" if $option{lines};
568 system($cmd) unless $option{noexec};
571 if (defined $status) {
572 rollback();
573 exit $status;
576 # ask user, and rollback if there is no confirmation
578 confirm_rules() or rollback() if $option{interactive};
580 exit 0;
582 # end of program execution!
585 # funcs
587 sub printversion {
588 print "ferm $VERSION\n";
589 print "Copyright (C) 2001-2007 Auke Kok, Max Kellermann\n";
590 print "This program is free software released under GPLv2.\n";
591 print "See the included COPYING file for license details.\n";
595 sub mydie {
596 print STDERR @_;
597 print STDERR "\n";
598 exit 1;
602 sub error {
603 # returns a nice formatted error message, showing the
604 # location of the error.
605 my $tabs = 0;
606 my @lines;
607 my $l = 0;
608 my @words = map { @$_ } @{$script->{past_tokens}};
610 for my $w ( 0 .. $#words ) {
611 if ($words[$w] eq "\x29")
612 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
613 if ($words[$w] eq "\x28")
614 { $l++ ; $lines[$l] = " " x $tabs++ ;};
615 if ($words[$w] eq "\x7d")
616 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
617 if ($words[$w] eq "\x7b")
618 { $l++ ; $lines[$l] = " " x $tabs++ ;};
619 if ( $l > $#lines ) { $lines[$l] = "" };
620 $lines[$l] .= $words[$w] . " ";
621 if ($words[$w] eq "\x28")
622 { $l++ ; $lines[$l] = " " x $tabs ;};
623 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
624 { $l++ ; $lines[$l] = " " x $tabs ;};
625 if ($words[$w] eq "\x7b")
626 { $l++ ; $lines[$l] = " " x $tabs ;};
627 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
628 { $l++ ; $lines[$l] = " " x $tabs ;};
629 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
630 { $l++ ; $lines[$l] = " " x $tabs ;}
631 if ($words[$w-1] eq "option")
632 { $l++ ; $lines[$l] = " " x $tabs ;}
634 my $start = $#lines - 4;
635 if ($start < 0) { $start = 0 } ;
636 print STDERR "Error in $script->{filename} line $script->{line}:\n";
637 for $l ( $start .. $#lines)
638 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
639 print STDERR "<--\n";
640 mydie(@_);
643 # print a warning message about code from an input file
644 sub warning {
645 print STDERR "Warning in $script->{filename} line $script->{line}: "
646 . (shift) . "\n";
649 sub find_tool($) {
650 my $name = shift;
651 return $name if $option{test};
652 for my $path ('/sbin', split ':', $ENV{PATH}) {
653 my $ret = "$path/$name";
654 return $ret if -x $ret;
656 die "$name not found in PATH\n";
659 sub initialize_domain {
660 my $domain = shift;
662 return if exists $domains{$domain}{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 foreach my $tool (@tools) {
672 $domains{$domain}{tools}{$tool} = find_tool("${domain}${tool}");
675 # make tables-save tell us about the state of this domain
676 # (which tables and chains do exist?), also remember the old
677 # save data which may be used later by the rollback function
678 local *SAVE;
679 if (!$option{test} &&
680 exists $domains{$domain}{tools}{'tables-save'} &&
681 open(SAVE, "$domains{$domain}{tools}{'tables-save'}|")) {
682 my $save = '';
684 my $table_info;
685 while (<SAVE>) {
686 $save .= $_;
688 if (/^\*(\w+)/) {
689 my $table = $1;
690 $table_info = $domains{$domain}{tables}{$table} ||= {};
691 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
692 and $2 ne '-') {
693 $table_info->{chains}{$1}{builtin} = 1;
694 $table_info->{has_builtin} = 1;
698 # for rollback
699 $domains{$domain}{previous} = $save;
702 $domains{$domain}{initialized} = 1;
705 # split the an input string into words and delete comments
706 sub tokenize_string($) {
707 my $string = shift;
709 my @ret;
711 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
712 last if $word eq '#';
713 push @ret, $word;
716 return \@ret;
719 # shift an array; helper function to be passed to &getvar / &getvalues
720 sub next_array_token {
721 my $array = shift;
722 shift @$array;
725 # read some more tokens from the input file into a buffer
726 sub prepare_tokens() {
727 my $tokens = $script->{tokens};
728 while (@$tokens == 0) {
729 my $handle = $script->{handle};
730 my $line = <$handle>;
731 return unless defined $line;
733 $script->{line} ++;
735 # the next parser stage eats this
736 push @$tokens, @{tokenize_string($line)};
739 return 1;
742 # open a ferm sub script
743 sub open_script($) {
744 my $filename = shift;
746 for (my $s = $script; defined $s; $s = $s->{parent}) {
747 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
748 if $s->{filename} eq $filename;
751 local *FILE;
752 open FILE, "<$filename"
753 or mydie("Failed to open $filename: $!");
754 my $handle = *FILE;
756 $script = { filename => $filename,
757 handle => $handle,
758 line => 0,
759 past_tokens => [],
760 tokens => [],
761 parent => $script,
764 return $script;
767 # collect script filenames which are being included
768 sub collect_filenames(@) {
769 my @ret;
771 # determine the current script's parent directory for relative
772 # file names
773 die unless defined $script;
774 my $parent_dir = $script->{filename} =~ m,^(.*/),
775 ? $1 : './';
777 foreach my $pathname (@_) {
778 # non-absolute file names are relative to the parent script's
779 # file name
780 $pathname = $parent_dir . $pathname
781 unless $pathname =~ m,^/,;
783 if ($pathname =~ m,/$,) {
784 # include all regular files in a directory
786 error("'$pathname' is not a directory")
787 unless -d $pathname;
789 local *DIR;
790 opendir DIR, $pathname
791 or error("Failed to open directory '$pathname': $!");
792 my @names = readdir DIR;
793 closedir DIR;
795 # sort those names for a well-defined order
796 foreach my $name (sort { $a cmp $b } @names) {
797 # don't include hidden and backup files
798 next if /^\.|~$/;
800 my $filename = $pathname . $name;
801 push @ret, $filename
802 if -f $filename;
804 } elsif ($pathname =~ m,\|$,) {
805 # run a program and use its output
806 push @ret, $pathname;
807 } elsif ($pathname =~ m,^\|,) {
808 error('This kind of pipe is not allowed');
809 } else {
810 # include a regular file
812 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
813 if -d $pathname;
814 error("'$pathname' is not a file")
815 unless -f $pathname;
817 push @ret, $pathname;
821 return @ret;
824 # peek a token from the queue, but don't remove it
825 sub peek_token() {
826 return unless prepare_tokens();
827 return $script->{tokens}[0];
830 # get a token from the queue
831 sub next_token() {
832 return unless prepare_tokens();
833 my $token = shift @{$script->{tokens}};
835 # update $script->{past_tokens}
836 my $past_tokens = $script->{past_tokens};
838 if (@$past_tokens > 0) {
839 my $prev_token = $past_tokens->[-1][-1];
840 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
841 if $prev_token eq ';';
842 pop @$past_tokens
843 if $prev_token eq '}';
846 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
847 push @{$past_tokens->[-1]}, $token;
849 # return
850 return $token;
853 sub expect_token($;$) {
854 my $expect = shift;
855 my $msg = shift;
856 my $token = next_token();
857 error($msg || "'$expect' expected")
858 unless defined $token and $token eq $expect;
861 # require that another token exists, and that it's not a "special"
862 # token, e.g. ";" and "{"
863 sub require_next_token {
864 my $code = shift || \&next_token;
866 my $token = &$code(@_);
868 error('unexpected end of file')
869 unless defined $token;
871 error("'$token' not allowed here")
872 if $token =~ /^[;{}]$/;
874 return $token;
877 # return the value of a variable
878 sub variable_value($) {
879 my $name = shift;
881 foreach (@stack) {
882 return $_->{vars}{$name}
883 if exists $_->{vars}{$name};
886 return $stack[0]{auto}{$name}
887 if exists $stack[0]{auto}{$name};
889 return;
892 # determine the value of a variable, die if the value is an array
893 sub string_variable_value($) {
894 my $name = shift;
895 my $value = variable_value($name);
897 error("variable '$name' must be a string, is an array")
898 if ref $value;
900 return $value;
903 # similar to the built-in "join" function, but also handle negated
904 # values in a special way
905 sub join_value($$) {
906 my ($expr, $value) = @_;
908 unless (ref $value) {
909 return $value;
910 } elsif (ref $value eq 'ARRAY') {
911 return join($expr, @$value);
912 } elsif (ref $value eq 'negated') {
913 # bless'negated' is a special marker for negated values
914 $value = join_value($expr, $value->[0]);
915 return bless [ $value ], 'negated';
916 } else {
917 die;
921 # returns the next parameter, which may either be a scalar or an array
922 sub getvalues {
923 my ($code, $param) = (shift, shift);
924 my %options = @_;
926 my $token = require_next_token($code, $param);
928 if ($token eq '(') {
929 # read an array until ")"
930 my @wordlist;
932 for (;;) {
933 $token = getvalues($code, $param,
934 parenthesis_allowed => 1,
935 comma_allowed => 1);
937 unless (ref $token) {
938 last if $token eq ')';
940 if ($token eq ',') {
941 error('Comma is not allowed within arrays, please use only a space');
942 next;
945 push @wordlist, $token;
946 } elsif (ref $token eq 'ARRAY') {
947 push @wordlist, @$token;
948 } else {
949 error('unknown toke type');
953 error('empty array not allowed here')
954 unless @wordlist or not $options{non_empty};
956 return @wordlist == 1
957 ? $wordlist[0]
958 : \@wordlist;
959 } elsif ($token =~ /^\`(.*)\`$/s) {
960 # execute a shell command, insert output
961 my $command = $1;
962 my $output = `$command`;
963 unless ($? == 0) {
964 if ($? == -1) {
965 error("failed to execute: $!");
966 } elsif ($? & 0x7f) {
967 error("child died with signal " . ($? & 0x7f));
968 } elsif ($? >> 8) {
969 error("child exited with status " . ($? >> 8));
973 # remove comments
974 $output =~ s/#.*//mg;
976 # tokenize
977 my @tokens = grep { length } split /\s+/s, $output;
979 my @values;
980 while (@tokens) {
981 my $value = getvalues(\&next_array_token, \@tokens);
982 push @values, to_array($value);
985 # and recurse
986 return @values == 1
987 ? $values[0]
988 : \@values;
989 } elsif ($token =~ /^\'(.*)\'$/s) {
990 # single quotes: a string
991 return $1;
992 } elsif ($token =~ /^\"(.*)\"$/s) {
993 # double quotes: a string with escapes
994 $token = $1;
995 $token =~ s,\$(\w+),string_variable_value($1),eg;
996 return $token;
997 } elsif ($token eq '!') {
998 error('negation is not allowed here')
999 unless $options{allow_negation};
1001 $token = getvalues($code, $param);
1003 error('it is not possible to negate an array')
1004 if ref $token and not $options{allow_array_negation};
1006 return bless [ $token ], 'negated';
1007 } elsif ($token eq ',') {
1008 return $token
1009 if $options{comma_allowed};
1011 error('comma is not allowed here');
1012 } elsif ($token eq '=') {
1013 error('equals operator ("=") is not allowed here');
1014 } elsif ($token eq '$') {
1015 my $name = require_next_token($code, $param);
1016 error('variable name expected - if you want to concatenate strings, try using double quotes')
1017 unless $name =~ /^\w+$/;
1019 my $value = variable_value($name);
1021 error("no such variable: \$$name")
1022 unless defined $value;
1024 return $value;
1025 } elsif ($token eq '&') {
1026 error("function calls are not allowed as keyword parameter");
1027 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1028 error('Syntax error');
1029 } elsif ($token =~ /^@/) {
1030 if ($token eq '@resolve') {
1031 my @params = get_function_params();
1032 error('Usage: @resolve((hostname ...))')
1033 unless @params == 1;
1034 eval { require Net::DNS; };
1035 error('For the @resolve() function, you need the Perl library Net::DNS')
1036 if $@;
1037 my $type = 'A';
1038 my $resolver = new Net::DNS::Resolver;
1039 my @result;
1040 foreach my $hostname (to_array($params[0])) {
1041 my $query = $resolver->search($hostname, $type);
1042 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1043 unless $query;
1044 foreach my $rr ($query->answer) {
1045 next unless $rr->type eq $type;
1046 push @result, $rr->address;
1049 return \@result;
1050 } else {
1051 error("unknown ferm built-in function");
1053 } else {
1054 return $token;
1058 # returns the next parameter, but only allow a scalar
1059 sub getvar {
1060 my $token = getvalues(@_);
1062 error('array not allowed here')
1063 if ref $token and ref $token eq 'ARRAY';
1065 return $token;
1068 sub get_function_params(%) {
1069 expect_token('(', 'function name must be followed by "()"');
1071 my $token = peek_token();
1072 if ($token eq ')') {
1073 require_next_token;
1074 return;
1077 my @params;
1079 while (1) {
1080 if (@params > 0) {
1081 $token = require_next_token();
1082 last
1083 if $token eq ')';
1085 error('"," expected')
1086 unless $token eq ',';
1089 push @params, getvalues(undef, undef, @_);
1092 return @params;
1095 # collect all tokens in a flat array reference until the end of the
1096 # command is reached
1097 sub collect_tokens() {
1098 my @level;
1099 my @tokens;
1101 while (1) {
1102 my $keyword = next_token();
1103 error('unexpected end of file within function/variable declaration')
1104 unless defined $keyword;
1106 if ($keyword =~ /^[\{\(]$/) {
1107 push @level, $keyword;
1108 } elsif ($keyword =~ /^[\}\)]$/) {
1109 my $expected = $keyword;
1110 $expected =~ tr/\}\)/\{\(/;
1111 my $opener = pop @level;
1112 error("unmatched '$keyword'")
1113 unless defined $opener and $opener eq $expected;
1114 } elsif ($keyword eq ';' and @level == 0) {
1115 last;
1118 push @tokens, $keyword;
1120 last
1121 if $keyword eq '}' and @level == 0;
1124 return \@tokens;
1128 # returns the specified value as an array. dereference arrayrefs
1129 sub to_array($) {
1130 my $value = shift;
1131 die unless wantarray;
1132 die if @_;
1133 unless (ref $value) {
1134 return $value;
1135 } elsif (ref $value eq 'ARRAY') {
1136 return @$value;
1137 } else {
1138 die;
1142 # evaluate the specified value as bool
1143 sub eval_bool($) {
1144 my $value = shift;
1145 die if wantarray;
1146 die if @_;
1147 unless (ref $value) {
1148 return $value;
1149 } elsif (ref $value eq 'ARRAY') {
1150 return @$value > 0;
1151 } else {
1152 die;
1156 sub is_netfilter_core_target($) {
1157 my $target = shift;
1158 die unless defined $target and length $target;
1160 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1163 sub is_netfilter_module_target($$) {
1164 my ($domain_family, $target) = @_;
1165 die unless defined $target and length $target;
1167 return defined $domain_family &&
1168 exists $target_defs{$domain_family} &&
1169 exists $target_defs{$domain_family}{$target};
1172 sub is_netfilter_builtin_chain($$) {
1173 my ($table, $chain) = @_;
1175 return grep { $_ eq $chain }
1176 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1179 sub netfilter_canonical_protocol($) {
1180 my $proto = shift;
1181 return 'icmpv6'
1182 if $proto eq 'ipv6-icmp';
1183 return 'mh'
1184 if $proto eq 'ipv6-mh';
1185 return $proto;
1188 sub netfilter_protocol_module($) {
1189 my $proto = shift;
1190 return unless defined $proto;
1191 return 'icmp6'
1192 if $proto eq 'icmpv6';
1193 return $proto;
1196 # escape the string in a way safe for the shell
1197 sub shell_escape($) {
1198 my $token = shift;
1200 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1202 if ($option{fast}) {
1203 # iptables-save/iptables-restore are quite buggy concerning
1204 # escaping and special characters... we're trying our best
1205 # here
1207 $token =~ s,",',g;
1208 $token = '"' . $token . '"'
1209 if $token =~ /[\s\'\\;&]/s;
1210 } else {
1211 return $token
1212 if $token =~ /^\`.*\`$/;
1213 $token =~ s/'/\\'/g;
1214 $token = '\'' . $token . '\''
1215 if $token =~ /[\s\"\\;<>&|]/s;
1218 return $token;
1221 # append an option to the shell command line, using information from
1222 # the module definition (see %match_defs etc.)
1223 sub shell_append_option($$$) {
1224 my ($ref, $keyword, $value) = @_;
1226 if (ref $value) {
1227 if (ref $value eq 'negated') {
1228 $value = $value->[0];
1229 $keyword .= ' !';
1230 } elsif (ref $value eq 'pre_negated') {
1231 $value = $value->[0];
1232 $$ref .= ' !';
1236 unless (defined $value) {
1237 $$ref .= " --$keyword";
1238 } elsif (ref $value) {
1239 if (ref $value eq 'params') {
1240 $$ref .= " --$keyword ";
1241 $$ref .= join(' ', map { shell_escape($_) } @$value);
1242 } elsif (ref $value eq 'multi') {
1243 foreach (@$value) {
1244 $$ref .= " --$keyword " . shell_escape($_);
1246 } else {
1247 die;
1249 } else {
1250 $$ref .= " --$keyword " . shell_escape($value);
1254 # convert an internal rule structure into an iptables call
1255 sub tables($) {
1256 my $rule = shift;
1258 my $domain = $rule->{domain};
1259 my $domain_info = $domains{$domain};
1260 $domain_info->{enabled} = 1;
1261 my $domain_family = $rule->{domain_family};
1263 my $table = $rule->{table};
1264 my $table_info = $domain_info->{tables}{$table} ||= {};
1266 my $chain = $rule->{chain};
1267 my $chain_info = $table_info->{chains}{$chain} ||= {};
1268 my $chain_rules = $chain_info->{rules} ||= [];
1270 return if $option{flush};
1272 my $action = $rule->{action};
1274 # mark this chain as "non-empty" because we will add stuff to
1275 # it now; this flag is later used to check if a custom chain
1276 # referenced by "jump" was actually defined
1277 $chain_info->{non_empty} = 1;
1279 # return if this is a declaration-only rule
1280 return
1281 unless $rule->{has_rule};
1283 my $rr = '';
1285 # general iptables options
1287 while (my ($keyword, $value) = each %{$rule->{builtin}}) {
1288 shell_append_option(\$rr, $keyword, $value);
1292 # match module options
1295 my %modules;
1297 if (defined $rule->{builtin}{protocol}) {
1298 my $proto = $rule->{builtin}{protocol};
1300 # special case: --dport and --sport for TCP/UDP
1301 if ($domain_family eq 'ip' and
1302 (exists $rule->{dport} or exists $rule->{sport}) and
1303 $proto =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
1304 unless (exists $modules{$proto}) {
1305 $rr .= " -m $proto";
1306 $modules{$proto} = 1;
1309 shell_append_option(\$rr, 'dport', $rule->{dport})
1310 if exists $rule->{dport};
1311 shell_append_option(\$rr, 'sport', $rule->{sport})
1312 if exists $rule->{sport};
1316 # modules stored in %match_defs
1318 foreach my $match (@{$rule->{match}}) {
1319 my $module_name = $match->{name};
1320 unless (exists $modules{$module_name}) {
1321 $rr .= " -m $module_name";
1322 $modules{$module_name} = 1;
1325 while (my ($keyword, $value) = each %{$match->{options}}) {
1326 shell_append_option(\$rr, $keyword, $value);
1331 # target options
1334 if ($action->{type} eq 'jump') {
1335 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1336 $rr .= " -j " . $action->{chain};
1337 } elsif ($action->{type} eq 'goto') {
1338 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1339 $rr .= " -g " . $action->{chain};
1340 } elsif ($action->{type} eq 'target') {
1341 $rr .= " -j " . $action->{target};
1343 # targets stored in %target_defs
1345 while (my ($keyword, $value) = each %{$rule->{target_options}}) {
1346 shell_append_option(\$rr, $keyword, $value);
1348 } elsif ($action->{type} ne 'nop') {
1349 die;
1352 # this line is done
1353 push @$chain_rules, { rule => $rr,
1354 script => $rule->{script},
1358 sub transform_rule($) {
1359 my $rule = shift;
1361 $rule->{builtin}{protocol} = 'icmpv6'
1362 if $rule->{domain} eq 'ip6' and $rule->{builtin}{protocol} eq 'icmp';
1365 sub printrule($) {
1366 my $rule = shift;
1368 transform_rule($rule);
1370 # prints all rules in a hash
1371 tables($rule);
1375 sub check_unfold(\@$$) {
1376 my ($unfold, $parent, $key) = @_;
1378 return unless ref $parent->{$key} and
1379 ref $parent->{$key} eq 'ARRAY';
1381 push @$unfold, $parent, $key, $parent->{$key};
1384 # convert a bunch of internal rule structures in iptables calls,
1385 # unfold arrays during that
1386 sub mkrules($) {
1387 # compile the list hashes into rules
1388 my $fw = shift;
1390 my @unfold;
1392 foreach my $key (qw(domain table chain)) {
1393 check_unfold(@unfold, $fw, $key);
1396 foreach my $key (keys %{$fw->{builtin}}) {
1397 check_unfold(@unfold, $fw->{builtin}, $key);
1400 foreach my $match (@{$fw->{match}}) {
1401 while (my ($key, $value) = each %{$match->{options}}) {
1402 check_unfold(@unfold, $match->{options}, $key);
1406 check_unfold(@unfold, $fw, 'sport');
1407 check_unfold(@unfold, $fw, 'dport');
1409 if (@unfold == 0) {
1410 printrule($fw);
1411 return;
1414 sub dofr {
1415 my $fw = shift;
1416 my ($parent, $key, $values) = (shift, shift, shift);
1418 foreach my $value (@$values) {
1419 $parent->{$key} = $value;
1421 if (@_) {
1422 dofr($fw, @_);
1423 } else {
1424 printrule($fw);
1429 dofr($fw, @unfold);
1432 sub filter_domains($) {
1433 my $domains = shift;
1434 my $result = [];
1436 foreach my $domain (to_array $domains) {
1437 next if exists $option{domain}
1438 and $domain ne $option{domain};
1440 eval {
1441 initialize_domain($domain);
1443 error($@) if $@;
1445 push @$result, $domain;
1448 return @$result == 1 ? $result->[0] : $result;
1451 # parse a keyword from a module definition
1452 sub parse_keyword($$$$) {
1453 my ($current, $def, $keyword, $negated_ref) = @_;
1455 my $params = $def->{params};
1457 my $value;
1459 my $negated;
1460 if ($$negated_ref && exists $def->{pre_negation}) {
1461 $negated = 1;
1462 undef $$negated_ref;
1465 unless (defined $params) {
1466 undef $value;
1467 } elsif (ref $params && ref $params eq 'CODE') {
1468 $value = &$params($current);
1469 } elsif ($params eq 'm') {
1470 $value = bless [ to_array getvalues() ], 'multi';
1471 } elsif ($params =~ /^[a-z]/) {
1472 if (exists $def->{negation} and not $negated) {
1473 my $token = peek_token();
1474 if ($token eq '!') {
1475 require_next_token;
1476 $negated = 1;
1480 my @params;
1481 foreach my $p (split(//, $params)) {
1482 if ($p eq 's') {
1483 push @params, getvar();
1484 } elsif ($p eq 'c') {
1485 my @v = to_array getvalues(undef, undef,
1486 non_empty => 1);
1487 push @params, join(',', @v);
1488 } else {
1489 die;
1493 $value = @params == 1
1494 ? $params[0]
1495 : bless \@params, 'params';
1496 } elsif ($params == 1) {
1497 if (exists $def->{negation} and not $negated) {
1498 my $token = peek_token();
1499 if ($token eq '!') {
1500 require_next_token;
1501 $negated = 1;
1505 $value = getvalues();
1507 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1508 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1509 } else {
1510 if (exists $def->{negation} and not $negated) {
1511 my $token = peek_token();
1512 if ($token eq '!') {
1513 require_next_token;
1514 $negated = 1;
1518 $value = bless [ map {
1519 getvar()
1520 } (1..$params) ], 'params';
1523 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1524 if $negated;
1526 return $value;
1529 # parse options of a module
1530 sub parse_option($$$$$) {
1531 my ($def, $current, $store, $keyword, $negated_ref) = @_;
1533 while (exists $def->{alias}) {
1534 ($keyword, $def) = @{$def->{alias}};
1535 die unless defined $def;
1538 $store->{$keyword}
1539 = parse_keyword($current, $def,
1540 $keyword, $negated_ref);
1541 $current->{has_rule} = 1;
1542 return 1;
1545 # parse options for a protocol module definition
1546 sub parse_protocol_options($$$$) {
1547 my ($current, $proto, $keyword, $negated_ref) = @_;
1549 my $domain_family = $current->{'domain_family'};
1550 my $proto_defs = $proto_defs{$domain_family};
1551 return unless defined $proto_defs;
1553 my $proto_def = $proto_defs->{$proto};
1554 return unless defined $proto_def and
1555 exists $proto_def->{keywords}{$keyword};
1557 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1558 my $module = { name => $module_name,
1559 options => {},
1560 defs => $proto_def,
1562 push @{$current->{match}}, $module;
1564 return parse_option($proto_def->{keywords}{$keyword},
1565 $current, $module->{options},
1566 $keyword, $negated_ref);
1569 sub copy_on_write($$) {
1570 my ($rule, $key) = @_;
1571 return unless exists $rule->{cow}{$key};
1572 $rule->{$key} = {%{$rule->{$key}}};
1573 delete $rule->{cow}{$key};
1576 sub clone_match($) {
1577 my $match = shift;
1578 return { name => $match->{name},
1579 options => { %{$match->{options}} },
1580 defs => $match->{defs},
1584 sub new_level(\%$) {
1585 my ($current, $prev) = @_;
1587 %$current = ();
1588 if (defined $prev) {
1589 # copy data from previous level
1590 $current->{cow} = { keywords => 1, };
1591 $current->{keywords} = $prev->{keywords};
1592 $current->{builtin} = { %{$prev->{builtin}} };
1593 $current->{match} = [ map { clone_match($_) } @{$prev->{match}} ];
1594 $current->{action} = { %{$prev->{action}} };
1595 foreach my $key (qw(domain domain_family table chain sport dport)) {
1596 $current->{$key} = $prev->{$key}
1597 if exists $prev->{$key};
1599 } else {
1600 $current->{cow} = {};
1601 $current->{keywords} = {};
1602 $current->{builtin} = {};
1603 $current->{match} = [];
1604 $current->{action} = {};
1608 sub rule_defined(\%) {
1609 my $rule = shift;
1610 return defined($rule->{domain}) or
1611 keys(%{$rule->{builtin}}) > 0 or
1612 keys(%{$rule->{match}}) > 0 or
1613 keys(%{$rule->{action}}) > 0;
1616 # the main parser loop: read tokens, convert them into internal rule
1617 # structures
1618 sub enter($$) {
1619 my $lev = shift; # current recursion depth
1620 my $prev = shift; # previous rule hash
1622 # enter is the core of the firewall setup, it is a
1623 # simple parser program that recognizes keywords and
1624 # retreives parameters to set up the kernel routing
1625 # chains
1627 my $base_level = $script->{base_level} || 0;
1628 die if $base_level > $lev;
1630 my %current;
1631 new_level(%current, $prev);
1633 # read keywords 1 by 1 and dump into parser
1634 while (defined (my $keyword = next_token())) {
1635 # check if the current rule should be negated
1636 my $negated = $keyword eq '!';
1637 if ($negated) {
1638 # negation. get the next word which contains the 'real'
1639 # rule
1640 $keyword = getvar();
1642 error('unexpected end of file after negation')
1643 unless defined $keyword;
1646 # the core: parse all data
1647 for ($keyword)
1649 # deprecated keyword?
1650 if (exists $deprecated_keywords{$keyword}) {
1651 my $new_keyword = $deprecated_keywords{$keyword};
1652 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1653 $keyword = $new_keyword;
1656 # effectuation operator
1657 if ($keyword eq ';') {
1658 if ($current{has_rule} and not $current{action}{type}) {
1659 # something is wrong when a rule was specifiedd,
1660 # but no action
1661 error('No action defined; did you mean "NOP"?');
1664 error('No chain defined') unless defined $current{chain};
1666 $current{script} = { filename => $script->{filename},
1667 line => $script->{line},
1670 mkrules(\%current);
1672 # and clean up variables set in this level
1673 new_level(%current, $prev);
1675 next;
1678 # conditional expression
1679 if ($keyword eq '@if') {
1680 unless (eval_bool(getvalues)) {
1681 collect_tokens;
1682 my $token = peek_token();
1683 require_next_token() if $token and $token eq '@else';
1686 next;
1689 if ($keyword eq '@else') {
1690 # hack: if this "else" has not been eaten by the "if"
1691 # handler above, we believe it came from an if clause
1692 # which evaluated "true" - remove the "else" part now.
1693 collect_tokens;
1694 next;
1697 # hooks for custom shell commands
1698 if ($keyword eq 'hook') {
1699 error('"hook" must be the first token in a command')
1700 if rule_defined(%current);
1702 my $position = getvar();
1703 my $hooks;
1704 if ($position eq 'pre') {
1705 $hooks = \@pre_hooks;
1706 } elsif ($position eq 'post') {
1707 $hooks = \@post_hooks;
1708 } else {
1709 error("Invalid hook position: '$position'");
1712 push @$hooks, getvar();
1714 expect_token(';');
1715 next;
1718 # recursing operators
1719 if ($keyword eq '{') {
1720 # push stack
1721 my $old_stack_depth = @stack;
1723 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1725 # recurse
1726 enter($lev + 1, \%current);
1728 # pop stack
1729 shift @stack;
1730 die unless @stack == $old_stack_depth;
1732 # after a block, the command is finished, clear this
1733 # level
1734 new_level(%current, $prev);
1736 next;
1739 if ($keyword eq '}') {
1740 error('Unmatched "}"')
1741 if $lev <= $base_level;
1743 # consistency check: check if they havn't forgotten
1744 # the ';' before the last statement
1745 error('Missing semicolon before "}"')
1746 if $current{has_rule};
1748 # and exit
1749 return;
1752 # include another file
1753 if ($keyword eq '@include' or $keyword eq 'include') {
1754 my @files = collect_filenames to_array getvalues;
1755 $keyword = next_token;
1756 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1757 unless defined $keyword and $keyword eq ';';
1759 foreach my $filename (@files) {
1760 # save old script, open new script
1761 my $old_script = $script;
1762 open_script($filename);
1763 $script->{base_level} = $lev + 1;
1765 # push stack
1766 my $old_stack_depth = @stack;
1768 my $stack = {};
1770 if (@stack > 0) {
1771 # include files may set variables for their parent
1772 $stack->{vars} = ($stack[0]{vars} ||= {});
1773 $stack->{functions} = ($stack[0]{functions} ||= {});
1774 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1777 unshift @stack, $stack;
1779 # parse the script
1780 enter($lev + 1, \%current);
1782 # pop stack
1783 shift @stack;
1784 die unless @stack == $old_stack_depth;
1786 # restore old script
1787 $script = $old_script;
1790 next;
1793 # definition of a variable or function
1794 if ($keyword eq '@def' or $keyword eq 'def') {
1795 error('"def" must be the first token in a command')
1796 if $current{has_rule};
1798 my $type = require_next_token();
1799 if ($type eq '$') {
1800 my $name = require_next_token();
1801 error('invalid variable name')
1802 unless $name =~ /^\w+$/;
1804 expect_token('=');
1806 my $value = getvalues(undef, undef, allow_negation => 1);
1808 expect_token(';');
1810 $stack[0]{vars}{$name} = $value
1811 unless exists $stack[-1]{vars}{$name};
1812 } elsif ($type eq '&') {
1813 my $name = require_next_token();
1814 error('invalid function name')
1815 unless $name =~ /^\w+$/;
1817 expect_token('(', 'function parameter list or "()" expected');
1819 my @params;
1820 while (1) {
1821 my $token = require_next_token();
1822 last if $token eq ')';
1824 if (@params > 0) {
1825 error('"," expected')
1826 unless $token eq ',';
1828 $token = require_next_token();
1831 error('"$" and parameter name expected')
1832 unless $token eq '$';
1834 $token = require_next_token();
1835 error('invalid function parameter name')
1836 unless $token =~ /^\w+$/;
1838 push @params, $token;
1841 my %function;
1843 $function{params} = \@params;
1845 expect_token('=');
1847 my $tokens = collect_tokens();
1848 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1849 $function{tokens} = $tokens;
1851 $stack[0]{functions}{$name} = \%function
1852 unless exists $stack[-1]{functions}{$name};
1853 } else {
1854 error('"$" (variable) or "&" (function) expected');
1857 next;
1860 # def references
1861 if ($keyword eq '$') {
1862 error('variable references are only allowed as keyword parameter');
1865 if ($keyword eq '&') {
1866 my $name = require_next_token;
1867 error('function name expected')
1868 unless $name =~ /^\w+$/;
1870 my $function;
1871 foreach (@stack) {
1872 $function = $_->{functions}{$name};
1873 last if defined $function;
1875 error("no such function: \&$name")
1876 unless defined $function;
1878 my $paramdef = $function->{params};
1879 die unless defined $paramdef;
1881 my @params = get_function_params(allow_negation => 1);
1883 error("Wrong number of parameters for function '\&$name': "
1884 . @$paramdef . " expected, " . @params . " given")
1885 unless @params == @$paramdef;
1887 my %vars;
1888 for (my $i = 0; $i < @params; $i++) {
1889 $vars{$paramdef->[$i]} = $params[$i];
1892 if ($function->{block}) {
1893 # block {} always ends the current rule, so if the
1894 # function contains a block, we have to require
1895 # the calling rule also ends here
1896 expect_token(';');
1899 my @tokens = @{$function->{tokens}};
1900 for (my $i = 0; $i < @tokens; $i++) {
1901 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1902 exists $vars{$tokens[$i + 1]}) {
1903 my @value = to_array($vars{$tokens[$i + 1]});
1904 @value = ('(', @value, ')')
1905 unless @tokens == 1;
1906 splice(@tokens, $i, 2, @value);
1907 $i += @value - 2;
1908 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1909 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1913 unshift @{$script->{tokens}}, @tokens;
1915 next;
1918 # where to put the rule?
1919 if ($keyword eq 'domain') {
1920 error('Domain is already specified')
1921 if exists $current{domain};
1923 my $domain = getvalues();
1924 my $filtered_domain = filter_domains($domain);
1925 my $domain_family;
1926 unless (ref $domain) {
1927 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1928 } elsif (@$domain == 0) {
1929 $domain_family = 'none';
1930 } elsif (grep { not /^ip6?$/s } @$domain) {
1931 error('Cannot combine non-IP domains');
1932 } else {
1933 $domain_family = 'ip';
1935 $current{domain_family} = $domain_family;
1936 $current{keywords} = get_builtin_keywords($domain_family);
1937 delete $current{cow}{keywords};
1939 $current{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1941 next;
1944 if ($keyword eq 'table') {
1945 error('Table is already specified')
1946 if exists $current{table};
1947 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1949 unless (exists $current{domain}) {
1950 $current{domain} = filter_domains('ip');
1951 $current{domain_family} = 'ip';
1952 $current{keywords} = get_builtin_keywords('ip');
1953 delete $current{cow}{keywords};
1956 next;
1959 if ($keyword eq 'chain') {
1960 error('Chain is already specified')
1961 if exists $current{chain};
1962 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1964 # ferm 1.1 allowed lower case built-in chain names
1965 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1966 error('Please write built-in chain names in upper case')
1967 if /^(?:input|forward|output|prerouting|postrouting)$/;
1970 unless (exists $current{domain}) {
1971 $current{domain} = filter_domains('ip');
1972 $current{domain_family} = 'ip';
1973 $current{keywords} = get_builtin_keywords('ip');
1974 delete $current{cow}{keywords};
1977 $current{table} = 'filter'
1978 unless exists $current{table};
1980 # mark this chain as non-empty so ferm does not print a warning
1981 foreach my $domain (to_array $current{domain}) {
1982 foreach my $table (to_array $current{table}) {
1983 $domains{$domain}{tables}{$table}{chains}{$current{chain}}{non_empty} = 1
1987 next;
1990 error('Chain must be specified')
1991 unless exists $current{chain};
1993 # policy for built-in chain
1994 if ($keyword eq 'policy') {
1995 error('Cannot specify matches for policy')
1996 if $current{has_rule};
1998 my $policy = getvar();
1999 error("Invalid policy target: $policy")
2000 unless $policy =~ /^(?:ACCEPT|DROP)$/;
2002 expect_token(';');
2004 foreach my $domain (to_array $current{domain}) {
2005 foreach my $table (to_array $current{table}) {
2006 foreach my $chain (to_array $current{chain}) {
2007 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
2012 new_level(%current, $prev);
2013 next;
2016 # create a subchain
2017 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2018 error('Chain must be specified')
2019 unless exists $current{chain};
2021 error('No rule specified before "@subchain"')
2022 unless $current{has_rule};
2024 my $subchain;
2025 $keyword = next_token();
2027 if ($keyword =~ /^(["'])(.*)\1$/s) {
2028 $subchain = $2;
2029 $keyword = next_token();
2030 } else {
2031 $subchain = 'ferm_auto_' . ++$auto_chain;
2034 error('"{" or chain name expected after "@subchain"')
2035 unless $keyword eq '{';
2037 # create a deep copy of %current, only containing values
2038 # which must be in the subchain
2039 my %inner = ( cow => { keywords => 1, },
2040 keywords => $current{keywords},
2041 builtin => {},
2042 action => {},
2044 $inner{domain} = $current{domain};
2045 $inner{domain_family} = $current{domain_family};
2046 $inner{table} = $current{table};
2047 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2048 $inner{builtin}{protocol} = $current{builtin}{protocol}
2049 if exists $current{builtin}{protocol};
2051 # enter the block
2052 enter(1, \%inner);
2054 # mark this chain as non-empty so ferm does not print a warning
2055 foreach my $domain (to_array $current{domain}) {
2056 foreach my $table (to_array $current{table}) {
2057 $domains{$domain}{tables}{$table}{chains}{$subchain}{non_empty} = 1
2061 # now handle the parent - it's a jump to the sub chain
2062 $current{action} = { type => 'jump',
2063 chain => $subchain,
2066 $current{script} = { filename => $script->{filename},
2067 line => $script->{line},
2070 mkrules(\%current);
2072 # and clean up variables set in this level
2073 new_level(%current, $prev);
2075 next;
2078 # everything else must be part of a "real" rule, not just
2079 # "policy only"
2080 $current{has_rule}++;
2082 # extended parameters:
2083 if ($keyword =~ /^mod(?:ule)?$/) {
2084 foreach my $module (to_array getvalues) {
2085 next if grep { $_->{name} eq $module } @{$current{match}};
2087 my $domain_family = $current{domain_family};
2088 my $defs = $match_defs{$domain_family}{$module};
2089 if (not defined $defs and exists $current{builtin}{protocol}) {
2090 my $proto = $current{builtin}{protocol};
2091 unless (ref $proto) {
2092 $proto = netfilter_canonical_protocol($current{builtin}{protocol});
2093 $defs = $proto_defs{$domain_family}{$proto}
2094 if netfilter_protocol_module($proto) eq $module;
2098 push @{$current{match}}, { name => $module,
2099 options => {},
2100 defs => $defs,
2103 if (defined $defs) {
2104 copy_on_write(\%current, 'keywords');
2105 while (my ($k, $def) = each %{$defs->{keywords}}) {
2106 $current{keywords}{$k} = [ 'match', $module, $def ];
2111 next;
2114 # keywords from $current{keywords}
2116 if (exists $current{keywords}{$keyword}) {
2117 my ($type, $module, $def) = @{$current{keywords}{$keyword}};
2118 my $store;
2119 if ($type eq 'builtin') {
2120 $store = $current{builtin};
2121 } elsif ($type eq 'match') {
2122 $store = (grep { $_->{name} eq $module } @{$current{match}})[-1]->{options};
2123 } elsif ($type eq 'target') {
2124 $store = $current{target_options} ||= {};
2125 } else {
2126 die;
2129 parse_option($def, \%current, $store, $keyword, \$negated);
2130 next;
2134 # actions
2137 # jump action
2138 if ($keyword eq 'jump') {
2139 error('There can only one action per rule')
2140 if defined $current{action}{type};
2141 my $chain = getvar();
2142 if (is_netfilter_core_target($chain) or
2143 is_netfilter_module_target($current{domain_family}, $chain)) {
2144 my $defs = $target_defs{$current{domain_family}} &&
2145 $target_defs{$current{domain_family}}{$chain};
2146 $current{action} = { type => 'target',
2147 target => $chain,
2148 defs => $defs,
2151 if (defined $defs) {
2152 copy_on_write(\%current, 'keywords');
2153 while (my ($k, $def) = each %{$defs->{keywords}}) {
2154 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2157 } else {
2158 $current{action} = { type => 'jump',
2159 chain => $chain,
2162 next;
2165 # goto action
2166 if ($keyword eq 'realgoto') {
2167 error('There can only one action per rule')
2168 if defined $current{action}{type};
2169 $current{action} = { type => 'goto',
2170 chain => getvar(),
2172 next;
2175 # action keywords
2176 if (is_netfilter_core_target($keyword)) {
2177 error('There can only one action per rule')
2178 if defined $current{action}{type};
2179 $current{action} = { type => 'target',
2180 target => $keyword,
2182 next;
2185 if ($keyword eq 'NOP') {
2186 error('There can only one action per rule')
2187 if defined $current{action}{type};
2188 $current{action} = { type => 'nop',
2190 next;
2193 if (is_netfilter_module_target($current{domain_family}, $keyword)) {
2194 error('There can only one action per rule')
2195 if defined $current{action}{type};
2197 if ($keyword eq 'TCPMSS') {
2198 my $protos = $current{builtin}{protocol};
2199 error('No protocol specified before TCPMSS')
2200 unless defined $protos;
2201 foreach my $proto (to_array $protos) {
2202 error('TCPMSS not available for protocol "$proto"')
2203 unless $proto eq 'tcp';
2207 my $defs = $target_defs{$current{domain_family}}{$keyword};
2209 $current{action} = { type => 'target',
2210 target => $keyword,
2211 defs => $defs,
2214 if (defined $defs) {
2215 copy_on_write(\%current, 'keywords');
2216 while (my ($k, $def) = each %{$defs->{keywords}}) {
2217 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2221 next;
2224 my $proto = $current{builtin}{protocol};
2227 # protocol specific options
2230 if (defined $proto and not ref $proto) {
2231 $proto = netfilter_canonical_protocol($proto);
2233 if ($proto eq 'icmp') {
2234 my $domains = $current{domain};
2235 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2238 parse_protocol_options(\%current, $proto, $keyword, \$negated)
2239 and next;
2242 # port switches
2243 if ($keyword =~ /^[sd]port$/) {
2244 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2245 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2247 $current{$keyword} = getvalues(undef, undef,
2248 allow_negation => 1);
2249 next;
2252 # default
2253 error("Unrecognized keyword: $keyword");
2256 # if the rule didn't reset the negated flag, it's not
2257 # supported
2258 error("Doesn't support negation: $keyword")
2259 if $negated;
2262 error('Missing "}" at end of file')
2263 if $lev > $base_level;
2265 # consistency check: check if they havn't forgotten
2266 # the ';' before the last statement
2267 error("Missing semicolon before end of file")
2268 if $current{has_rule}; # XXX
2271 sub execute_command {
2272 my ($command, $script) = @_;
2274 print LINES "$command\n"
2275 if $option{lines};
2276 return if $option{noexec};
2278 my $ret = system($_);
2279 unless ($ret == 0) {
2280 if ($? == -1) {
2281 print STDERR "failed to execute: $!\n";
2282 exit 1;
2283 } elsif ($? & 0x7f) {
2284 printf STDERR "child died with signal %d\n", $? & 0x7f;
2285 return 1;
2286 } else {
2287 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2288 if defined $script;
2289 return $? >> 8;
2293 return;
2296 sub execute_slow($$) {
2297 my ($domain, $domain_info) = @_;
2299 my $domain_cmd = $domain_info->{tools}{tables};
2301 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2302 my $table_cmd = "$domain_cmd -t $table";
2304 # reset chain policies
2305 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2306 next unless $chain_info->{builtin} or
2307 (not $table_info->{has_builtin} and
2308 is_netfilter_builtin_chain($table, $chain));
2309 $status ||= execute_command("$table_cmd -P $chain ACCEPT");
2312 # clear
2313 $status ||= execute_command("$table_cmd -F");
2314 $status ||= execute_command("$table_cmd -X");
2316 next if $option{flush};
2318 # create chains / set policy
2319 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2320 if (exists $chain_info->{policy}) {
2321 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2322 unless $chain_info->{policy} eq 'ACCEPT';
2323 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2324 $status ||= execute_command("$table_cmd -N $chain");
2328 # dump rules
2329 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2330 my $chain_cmd = "$table_cmd -A $chain";
2331 foreach my $rule (@{$chain_info->{rules}}) {
2332 $status ||= execute_command($chain_cmd . $rule->{rule});
2337 return $status;
2340 sub rules_to_save($$) {
2341 my ($domain, $domain_info) = @_;
2343 # convert this into an iptables-save text
2344 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2346 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2347 # select table
2348 $result .= '*' . $table . "\n";
2350 # create chains / set policy
2351 foreach my $chain (sort keys %{$table_info->{chains}}) {
2352 my $chain_info = $table_info->{chains}{$chain};
2353 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2354 unless (defined $policy) {
2355 if (is_netfilter_builtin_chain($table, $chain)) {
2356 $policy = 'ACCEPT';
2357 } else {
2358 $policy = '-';
2361 $result .= ":$chain $policy\ [0:0]\n";
2364 next if $option{flush};
2366 # dump rules
2367 foreach my $chain (sort keys %{$table_info->{chains}}) {
2368 my $chain_info = $table_info->{chains}{$chain};
2369 foreach my $rule (@{$chain_info->{rules}}) {
2370 $result .= "-A $chain$rule->{rule}\n";
2374 # do it
2375 $result .= "COMMIT\n";
2378 return $result;
2381 sub restore_domain($$) {
2382 my ($domain, $save) = @_;
2384 my $path = $domains{$domain}{tools}{'tables-restore'};
2386 local *RESTORE;
2387 open RESTORE, "|$path"
2388 or die "Failed to run $path: $!\n";
2390 print RESTORE $save;
2392 close RESTORE
2393 or die "Failed to run $path\n";
2396 sub execute_fast($$) {
2397 my ($domain, $domain_info) = @_;
2399 my $save = rules_to_save($domain, $domain_info);
2401 if ($option{lines}) {
2402 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2403 if $option{shell};
2404 print LINES $save;
2405 print LINES "EOT\n"
2406 if $option{shell};
2409 return if $option{noexec};
2411 eval {
2412 restore_domain($domain, $save);
2414 if ($@) {
2415 print STDERR $@;
2416 return 1;
2419 return;
2422 sub rollback() {
2423 my $error;
2424 while (my ($domain, $domain_info) = each %domains) {
2425 next unless $domain_info->{enabled};
2426 unless (defined $domain_info->{tools}{'tables-restore'}) {
2427 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2428 next;
2431 my $reset = '';
2432 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2433 my $reset_chain = '';
2434 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2435 next unless is_netfilter_builtin_chain($table, $chain);
2436 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2438 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2439 if length $reset_chain;
2442 $reset .= $domain_info->{previous}
2443 if defined $domain_info->{previous};
2445 restore_domain($domain, $reset);
2448 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2449 exit 1;
2452 sub alrm_handler {
2453 # do nothing, just interrupt a system call
2456 sub confirm_rules() {
2457 $SIG{ALRM} = \&alrm_handler;
2459 alarm(5);
2461 print STDERR "\n"
2462 . "ferm has applied the new firewall rules.\n"
2463 . "Please type 'yes' to confirm:\n";
2464 STDERR->flush();
2466 alarm(30);
2468 my $line = '';
2469 STDIN->sysread($line, 3);
2471 eval {
2472 require POSIX;
2473 POSIX::tcflush(*STDIN, 2);
2475 print STDERR "$@" if $@;
2477 $SIG{ALRM} = 'DEFAULT';
2479 return $line eq 'yes';
2482 # end of ferm
2484 __END__
2486 =head1 NAME
2488 ferm - a firewall rule parser for linux
2490 =head1 SYNOPSIS
2492 B<ferm> I<options> I<inputfiles>
2494 =head1 OPTIONS
2496 -n, --noexec Do not execute the rules, just simulate
2497 -F, --flush Flush all netfilter tables managed by ferm
2498 -l, --lines Show all rules that were created
2499 -i, --interactive Interactive mode: revert if user does not confirm
2500 --remote Remote mode; ignore host specific configuration.
2501 This implies --noexec and --lines.
2502 -V, --version Show current version number
2503 -h, --help Look at this text
2504 --fast Generate an iptables-save file, used by iptables-restore
2505 --shell Generate a shell script which calls iptables-restore
2506 --domain {ip|ip6} Handle only the specified domain
2507 --def '$name=v' Override a variable
2509 =cut