removed the "non_empty" flag
[ferm.git] / src / ferm
blob8849294bb0d64f992526f2ef3a1469aa3b2b5de4
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 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 # --protocol
217 qw(protocol! proto:=protocol),
218 # --source, --destination
219 qw(source! saddr:=source destination! daddr:=destination),
220 # --in-interface
221 qw(in-interface! interface:=in-interface if:=in-interface),
222 # --out-interface
223 qw(out-interface! outerface:=out-interface of:=out-interface),
224 # --fragment
225 qw(!fragment*0);
226 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
227 add_match_def 'addrtype', qw(src-type dst-type);
228 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
229 add_match_def 'comment', qw(comment=s);
230 add_match_def 'condition', qw(condition!);
231 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
232 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
233 add_match_def 'connmark', qw(mark);
234 add_match_def 'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
235 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
236 add_match_def 'dscp', qw(dscp dscp-class);
237 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
238 add_match_def 'esp', qw(espspi!);
239 add_match_def 'eui64';
240 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
241 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
242 add_match_def 'helper', qw(helper);
243 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
244 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
245 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
246 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
247 add_match_def 'iprange', qw(!src-range !dst-range);
248 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
249 add_match_def 'ipv6header', qw(header!=c soft*0);
250 add_match_def 'length', qw(length!);
251 add_match_def 'limit', qw(limit=s limit-burst=s);
252 add_match_def 'mac', qw(mac-source!);
253 add_match_def 'mark', qw(mark);
254 add_match_def 'multiport', qw(source-ports!&multiport_params),
255 qw(destination-ports!&multiport_params ports!&multiport_params);
256 add_match_def 'nth', qw(every counter start packet);
257 add_match_def 'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
258 add_match_def 'physdev', qw(physdev-in! physdev-out!),
259 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
260 add_match_def 'pkttype', qw(pkt-type),
261 add_match_def 'policy',
262 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
263 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
264 qw(psd-lo-ports-weight psd-hi-ports-weight);
265 add_match_def 'quota', qw(quota=s);
266 add_match_def 'random', qw(average);
267 add_match_def 'realm', qw(realm!);
268 add_match_def 'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
269 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
270 add_match_def 'set', qw(set=sc);
271 add_match_def 'state', qw(state=c);
272 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
273 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
274 add_match_def 'tcpmss', qw(!mss);
275 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
276 qw(!monthday=c !weekdays=c utc*0 localtz*0);
277 add_match_def 'tos', qw(!tos);
278 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
279 add_match_def 'u32', qw(!u32=m);
281 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
282 add_target_def 'CLASSIFY', qw(set-class);
283 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
284 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
285 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
286 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
287 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
288 add_target_def 'ECN', qw(ecn-tcp-remove*0);
289 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
290 add_target_def 'IPV4OPTSSTRIP';
291 add_target_def 'LOG', qw(log-level log-prefix),
292 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
293 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
294 add_target_def 'MASQUERADE', qw(to-ports random*0);
295 add_target_def 'MIRROR';
296 add_target_def 'NETMAP', qw(to);
297 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
298 add_target_def 'NFQUEUE', qw(queue-num);
299 add_target_def 'NOTRACK';
300 add_target_def 'REDIRECT', qw(to-ports random*0);
301 add_target_def 'REJECT', qw(reject-with);
302 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
303 add_target_def 'SAME', qw(to nodst*0 random*0);
304 add_target_def 'SECMARK', qw(selctx);
305 add_target_def 'SET', qw(add-set=sc del-set=sc);
306 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
307 add_target_def 'TARPIT';
308 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
309 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
310 add_target_def 'TRACE';
311 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
312 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
314 add_match_def_x 'arp', '',
315 # ip
316 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
317 # mac
318 qw(source-mac! destination-mac!),
319 # --in-interface
320 qw(in-interface! interface:=in-interface if:=in-interface),
321 # --out-interface
322 qw(out-interface! outerface:=out-interface of:=out-interface),
323 # misc
324 qw(h-length=s opcode=s h-type=s proto-type=s),
325 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
327 add_match_def_x 'eb', '',
328 # protocol
329 qw(protocol! proto:=protocol),
330 # --in-interface
331 qw(in-interface! interface:=in-interface if:=in-interface),
332 # --out-interface
333 qw(out-interface! outerface:=out-interface of:=out-interface),
334 # logical interface
335 qw(logical-in! logical-out!),
336 # --source, --destination
337 qw(source! saddr:=source destination! daddr:=destination),
338 # 802.3
339 qw(802_3-sap! 802_3-type!),
340 # arp
341 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
342 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
343 # ip
344 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
345 # mark_m
346 qw(mark!),
347 # pkttype
348 qw(pkttype-type!),
349 # stp
350 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
351 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
352 qw(stp-hello-time! stp-forward-delay!),
353 # vlan
354 qw(vlan-id! vlan-prio! vlan-encap!),
355 # log
356 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
358 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
359 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
360 add_target_def_x 'eb', 'mark', qw(set-mark mark-target);
361 add_target_def_x 'eb', 'redirect', qw(redirect-target);
362 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
364 use vars qw(%builtin_keywords);
366 sub get_builtin_keywords($) {
367 my $domain_family = shift;
368 return {} unless defined $domain_family;
370 return {%{$builtin_keywords{$domain_family}}}
371 if exists $builtin_keywords{$domain_family};
373 return {} unless exists $match_defs{$domain_family};
374 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
375 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
377 $builtin_keywords{$domain_family} = \%keywords;
378 return {%keywords};
381 # parameter parser for ipt_multiport
382 sub multiport_params {
383 my $fw = shift;
385 # multiport only allows 15 ports at a time. For this
386 # reason, we do a little magic here: split the ports
387 # into portions of 15, and handle these portions as
388 # array elements
390 my $proto = $fw->{builtin}{protocol};
391 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
392 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
394 my $value = getvalues(undef, undef,
395 allow_negation => 1,
396 allow_array_negation => 1);
397 if (ref $value and ref $value eq 'ARRAY') {
398 my @value = @$value;
399 my @params;
401 while (@value) {
402 push @params, join(',', splice(@value, 0, 15));
405 return @params == 1
406 ? $params[0]
407 : \@params;
408 } else {
409 return join_value(',', $value);
413 # initialize stack: command line definitions
414 unshift @stack, {};
416 # Get command line stuff
417 if ($has_getopt) {
418 my ($opt_noexec, $opt_flush, $opt_lines, $opt_interactive,
419 $opt_verbose, $opt_debug,
420 $opt_help,
421 $opt_version, $opt_test, $opt_fast, $opt_shell,
422 $opt_domain);
424 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
425 'no_auto_abbrev');
427 sub opt_def {
428 my ($opt, $value) = @_;
429 die 'Invalid --def specification'
430 unless $value =~ /^\$?(\w+)=(.*)$/s;
431 my ($name, $unparsed_value) = ($1, $2);
432 my $tokens = tokenize_string($unparsed_value);
433 my $value = getvalues(\&next_array_token, $tokens);
434 die 'Extra tokens after --def'
435 if @$tokens > 0;
436 $stack[0]{vars}{$name} = $value;
439 local $SIG{__WARN__} = sub { die $_[0]; };
440 GetOptions('noexec|n' => \$opt_noexec,
441 'flush|F' => \$opt_flush,
442 'lines|l' => \$opt_lines,
443 'interactive|i' => \$opt_interactive,
444 'verbose|v' => \$opt_verbose,
445 'debug|d' => \$opt_debug,
446 'help|h' => \$opt_help,
447 'version|V' => \$opt_version,
448 test => \$opt_test,
449 remote => \$opt_test,
450 fast => \$opt_fast,
451 shell => \$opt_shell,
452 'domain=s' => \$opt_domain,
453 'def=s' => \&opt_def,
456 if (defined $opt_help) {
457 require Pod::Usage;
458 Pod::Usage::pod2usage(-exitstatus => 0);
461 if (defined $opt_version) {
462 printversion();
463 exit 0;
466 $option{'noexec'} = (defined $opt_noexec);
467 $option{flush} = defined $opt_flush;
468 $option{'lines'} = (defined $opt_lines);
469 $option{interactive} = (defined $opt_interactive);
470 $option{test} = (defined $opt_test);
472 if ($option{test}) {
473 $option{noexec} = 1;
474 $option{lines} = 1;
477 delete $option{interactive} if $option{noexec};
479 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
480 if $option{interactive} and not -t STDIN;
481 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
482 if $option{interactive} and not -t STDERR;
484 $option{fast} = 1 if defined $opt_fast;
486 if (defined $opt_shell) {
487 $option{$_} = 1 foreach qw(shell fast lines);
490 $option{domain} = $opt_domain if defined $opt_domain;
492 print STDERR "Warning: ignoring the obsolete --debug option\n"
493 if defined $opt_debug;
494 print STDERR "Warning: ignoring the obsolete --verbose option\n"
495 if defined $opt_verbose;
496 } else {
497 # tiny getopt emulation for microperl
498 my $filename;
499 foreach (@ARGV) {
500 if ($_ eq '--noexec' or $_ eq '-n') {
501 $option{noexec} = 1;
502 } elsif ($_ eq '--lines' or $_ eq '-l') {
503 $option{lines} = 1;
504 } elsif ($_ eq '--fast') {
505 $option{fast} = 1;
506 } elsif ($_ eq '--test') {
507 $option{test} = 1;
508 $option{noexec} = 1;
509 $option{lines} = 1;
510 } elsif ($_ eq '--shell') {
511 $option{$_} = 1 foreach qw(shell fast lines);
512 } elsif (/^-/) {
513 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
514 exit 1;
515 } else {
516 $filename = $_;
519 undef @ARGV;
520 push @ARGV, $filename;
523 unless (@ARGV == 1) {
524 require Pod::Usage;
525 Pod::Usage::pod2usage(-exitstatus => 1);
528 if ($has_strict) {
529 open LINES, ">&STDOUT" if $option{lines};
530 open STDOUT, ">&STDERR" if $option{shell};
531 } else {
532 # microperl can't redirect file handles
533 *LINES = *STDOUT;
535 if ($option{fast} and not $option{noexec}) {
536 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
537 exit 1
541 unshift @stack, {};
542 open_script($ARGV[0]);
544 # parse all input recursively
545 enter(0);
546 die unless @stack == 2;
548 # execute all generated rules
549 my $status;
551 foreach my $cmd (@pre_hooks) {
552 print LINES "$cmd\n" if $option{lines};
553 system($cmd) unless $option{noexec};
556 while (my ($domain, $domain_info) = each %domains) {
557 next unless $domain_info->{enabled};
558 my $s = $option{fast} &&
559 defined $domain_info->{tools}{'tables-restore'}
560 ? execute_fast($domain, $domain_info)
561 : execute_slow($domain, $domain_info);
562 $status = $s if defined $s;
565 foreach my $cmd (@post_hooks) {
566 print "$cmd\n" if $option{lines};
567 system($cmd) unless $option{noexec};
570 if (defined $status) {
571 rollback();
572 exit $status;
575 # ask user, and rollback if there is no confirmation
577 confirm_rules() or rollback() if $option{interactive};
579 exit 0;
581 # end of program execution!
584 # funcs
586 sub printversion {
587 print "ferm $VERSION\n";
588 print "Copyright (C) 2001-2007 Auke Kok, Max Kellermann\n";
589 print "This program is free software released under GPLv2.\n";
590 print "See the included COPYING file for license details.\n";
594 sub mydie {
595 print STDERR @_;
596 print STDERR "\n";
597 exit 1;
601 sub error {
602 # returns a nice formatted error message, showing the
603 # location of the error.
604 my $tabs = 0;
605 my @lines;
606 my $l = 0;
607 my @words = map { @$_ } @{$script->{past_tokens}};
609 for my $w ( 0 .. $#words ) {
610 if ($words[$w] eq "\x29")
611 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
612 if ($words[$w] eq "\x28")
613 { $l++ ; $lines[$l] = " " x $tabs++ ;};
614 if ($words[$w] eq "\x7d")
615 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
616 if ($words[$w] eq "\x7b")
617 { $l++ ; $lines[$l] = " " x $tabs++ ;};
618 if ( $l > $#lines ) { $lines[$l] = "" };
619 $lines[$l] .= $words[$w] . " ";
620 if ($words[$w] eq "\x28")
621 { $l++ ; $lines[$l] = " " x $tabs ;};
622 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
623 { $l++ ; $lines[$l] = " " x $tabs ;};
624 if ($words[$w] eq "\x7b")
625 { $l++ ; $lines[$l] = " " x $tabs ;};
626 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
627 { $l++ ; $lines[$l] = " " x $tabs ;};
628 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
629 { $l++ ; $lines[$l] = " " x $tabs ;}
630 if ($words[$w-1] eq "option")
631 { $l++ ; $lines[$l] = " " x $tabs ;}
633 my $start = $#lines - 4;
634 if ($start < 0) { $start = 0 } ;
635 print STDERR "Error in $script->{filename} line $script->{line}:\n";
636 for $l ( $start .. $#lines)
637 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
638 print STDERR "<--\n";
639 mydie(@_);
642 # print a warning message about code from an input file
643 sub warning {
644 print STDERR "Warning in $script->{filename} line $script->{line}: "
645 . (shift) . "\n";
648 sub find_tool($) {
649 my $name = shift;
650 return $name if $option{test};
651 for my $path ('/sbin', split ':', $ENV{PATH}) {
652 my $ret = "$path/$name";
653 return $ret if -x $ret;
655 die "$name not found in PATH\n";
658 sub initialize_domain {
659 my $domain = shift;
661 return if exists $domains{$domain}{initialized};
663 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
665 my @tools = qw(tables);
666 push @tools, qw(tables-save tables-restore)
667 if $domain =~ /^ip6?$/;
669 # determine the location of this domain's tools
670 foreach my $tool (@tools) {
671 $domains{$domain}{tools}{$tool} = find_tool("${domain}${tool}");
674 # make tables-save tell us about the state of this domain
675 # (which tables and chains do exist?), also remember the old
676 # save data which may be used later by the rollback function
677 local *SAVE;
678 if (!$option{test} &&
679 exists $domains{$domain}{tools}{'tables-save'} &&
680 open(SAVE, "$domains{$domain}{tools}{'tables-save'}|")) {
681 my $save = '';
683 my $table_info;
684 while (<SAVE>) {
685 $save .= $_;
687 if (/^\*(\w+)/) {
688 my $table = $1;
689 $table_info = $domains{$domain}{tables}{$table} ||= {};
690 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
691 and $2 ne '-') {
692 $table_info->{chains}{$1}{builtin} = 1;
693 $table_info->{has_builtin} = 1;
697 # for rollback
698 $domains{$domain}{previous} = $save;
701 $domains{$domain}{initialized} = 1;
704 # split the an input string into words and delete comments
705 sub tokenize_string($) {
706 my $string = shift;
708 my @ret;
710 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
711 last if $word eq '#';
712 push @ret, $word;
715 return \@ret;
718 # shift an array; helper function to be passed to &getvar / &getvalues
719 sub next_array_token {
720 my $array = shift;
721 shift @$array;
724 # read some more tokens from the input file into a buffer
725 sub prepare_tokens() {
726 my $tokens = $script->{tokens};
727 while (@$tokens == 0) {
728 my $handle = $script->{handle};
729 my $line = <$handle>;
730 return unless defined $line;
732 $script->{line} ++;
734 # the next parser stage eats this
735 push @$tokens, @{tokenize_string($line)};
738 return 1;
741 # open a ferm sub script
742 sub open_script($) {
743 my $filename = shift;
745 for (my $s = $script; defined $s; $s = $s->{parent}) {
746 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
747 if $s->{filename} eq $filename;
750 local *FILE;
751 open FILE, "<$filename"
752 or mydie("Failed to open $filename: $!");
753 my $handle = *FILE;
755 $script = { filename => $filename,
756 handle => $handle,
757 line => 0,
758 past_tokens => [],
759 tokens => [],
760 parent => $script,
763 return $script;
766 # collect script filenames which are being included
767 sub collect_filenames(@) {
768 my @ret;
770 # determine the current script's parent directory for relative
771 # file names
772 die unless defined $script;
773 my $parent_dir = $script->{filename} =~ m,^(.*/),
774 ? $1 : './';
776 foreach my $pathname (@_) {
777 # non-absolute file names are relative to the parent script's
778 # file name
779 $pathname = $parent_dir . $pathname
780 unless $pathname =~ m,^/,;
782 if ($pathname =~ m,/$,) {
783 # include all regular files in a directory
785 error("'$pathname' is not a directory")
786 unless -d $pathname;
788 local *DIR;
789 opendir DIR, $pathname
790 or error("Failed to open directory '$pathname': $!");
791 my @names = readdir DIR;
792 closedir DIR;
794 # sort those names for a well-defined order
795 foreach my $name (sort { $a cmp $b } @names) {
796 # don't include hidden and backup files
797 next if /^\.|~$/;
799 my $filename = $pathname . $name;
800 push @ret, $filename
801 if -f $filename;
803 } elsif ($pathname =~ m,\|$,) {
804 # run a program and use its output
805 push @ret, $pathname;
806 } elsif ($pathname =~ m,^\|,) {
807 error('This kind of pipe is not allowed');
808 } else {
809 # include a regular file
811 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
812 if -d $pathname;
813 error("'$pathname' is not a file")
814 unless -f $pathname;
816 push @ret, $pathname;
820 return @ret;
823 # peek a token from the queue, but don't remove it
824 sub peek_token() {
825 return unless prepare_tokens();
826 return $script->{tokens}[0];
829 # get a token from the queue
830 sub next_token() {
831 return unless prepare_tokens();
832 my $token = shift @{$script->{tokens}};
834 # update $script->{past_tokens}
835 my $past_tokens = $script->{past_tokens};
837 if (@$past_tokens > 0) {
838 my $prev_token = $past_tokens->[-1][-1];
839 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
840 if $prev_token eq ';';
841 pop @$past_tokens
842 if $prev_token eq '}';
845 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
846 push @{$past_tokens->[-1]}, $token;
848 # return
849 return $token;
852 sub expect_token($;$) {
853 my $expect = shift;
854 my $msg = shift;
855 my $token = next_token();
856 error($msg || "'$expect' expected")
857 unless defined $token and $token eq $expect;
860 # require that another token exists, and that it's not a "special"
861 # token, e.g. ";" and "{"
862 sub require_next_token {
863 my $code = shift || \&next_token;
865 my $token = &$code(@_);
867 error('unexpected end of file')
868 unless defined $token;
870 error("'$token' not allowed here")
871 if $token =~ /^[;{}]$/;
873 return $token;
876 # return the value of a variable
877 sub variable_value($) {
878 my $name = shift;
880 foreach (@stack) {
881 return $_->{vars}{$name}
882 if exists $_->{vars}{$name};
885 return $stack[0]{auto}{$name}
886 if exists $stack[0]{auto}{$name};
888 return;
891 # determine the value of a variable, die if the value is an array
892 sub string_variable_value($) {
893 my $name = shift;
894 my $value = variable_value($name);
896 error("variable '$name' must be a string, is an array")
897 if ref $value;
899 return $value;
902 # similar to the built-in "join" function, but also handle negated
903 # values in a special way
904 sub join_value($$) {
905 my ($expr, $value) = @_;
907 unless (ref $value) {
908 return $value;
909 } elsif (ref $value eq 'ARRAY') {
910 return join($expr, @$value);
911 } elsif (ref $value eq 'negated') {
912 # bless'negated' is a special marker for negated values
913 $value = join_value($expr, $value->[0]);
914 return bless [ $value ], 'negated';
915 } else {
916 die;
920 # returns the next parameter, which may either be a scalar or an array
921 sub getvalues {
922 my ($code, $param) = (shift, shift);
923 my %options = @_;
925 my $token = require_next_token($code, $param);
927 if ($token eq '(') {
928 # read an array until ")"
929 my @wordlist;
931 for (;;) {
932 $token = getvalues($code, $param,
933 parenthesis_allowed => 1,
934 comma_allowed => 1);
936 unless (ref $token) {
937 last if $token eq ')';
939 if ($token eq ',') {
940 error('Comma is not allowed within arrays, please use only a space');
941 next;
944 push @wordlist, $token;
945 } elsif (ref $token eq 'ARRAY') {
946 push @wordlist, @$token;
947 } else {
948 error('unknown toke type');
952 error('empty array not allowed here')
953 unless @wordlist or not $options{non_empty};
955 return @wordlist == 1
956 ? $wordlist[0]
957 : \@wordlist;
958 } elsif ($token =~ /^\`(.*)\`$/s) {
959 # execute a shell command, insert output
960 my $command = $1;
961 my $output = `$command`;
962 unless ($? == 0) {
963 if ($? == -1) {
964 error("failed to execute: $!");
965 } elsif ($? & 0x7f) {
966 error("child died with signal " . ($? & 0x7f));
967 } elsif ($? >> 8) {
968 error("child exited with status " . ($? >> 8));
972 # remove comments
973 $output =~ s/#.*//mg;
975 # tokenize
976 my @tokens = grep { length } split /\s+/s, $output;
978 my @values;
979 while (@tokens) {
980 my $value = getvalues(\&next_array_token, \@tokens);
981 push @values, to_array($value);
984 # and recurse
985 return @values == 1
986 ? $values[0]
987 : \@values;
988 } elsif ($token =~ /^\'(.*)\'$/s) {
989 # single quotes: a string
990 return $1;
991 } elsif ($token =~ /^\"(.*)\"$/s) {
992 # double quotes: a string with escapes
993 $token = $1;
994 $token =~ s,\$(\w+),string_variable_value($1),eg;
995 return $token;
996 } elsif ($token eq '!') {
997 error('negation is not allowed here')
998 unless $options{allow_negation};
1000 $token = getvalues($code, $param);
1002 error('it is not possible to negate an array')
1003 if ref $token and not $options{allow_array_negation};
1005 return bless [ $token ], 'negated';
1006 } elsif ($token eq ',') {
1007 return $token
1008 if $options{comma_allowed};
1010 error('comma is not allowed here');
1011 } elsif ($token eq '=') {
1012 error('equals operator ("=") is not allowed here');
1013 } elsif ($token eq '$') {
1014 my $name = require_next_token($code, $param);
1015 error('variable name expected - if you want to concatenate strings, try using double quotes')
1016 unless $name =~ /^\w+$/;
1018 my $value = variable_value($name);
1020 error("no such variable: \$$name")
1021 unless defined $value;
1023 return $value;
1024 } elsif ($token eq '&') {
1025 error("function calls are not allowed as keyword parameter");
1026 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1027 error('Syntax error');
1028 } elsif ($token =~ /^@/) {
1029 if ($token eq '@resolve') {
1030 my @params = get_function_params();
1031 error('Usage: @resolve((hostname ...))')
1032 unless @params == 1;
1033 eval { require Net::DNS; };
1034 error('For the @resolve() function, you need the Perl library Net::DNS')
1035 if $@;
1036 my $type = 'A';
1037 my $resolver = new Net::DNS::Resolver;
1038 my @result;
1039 foreach my $hostname (to_array($params[0])) {
1040 my $query = $resolver->search($hostname, $type);
1041 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1042 unless $query;
1043 foreach my $rr ($query->answer) {
1044 next unless $rr->type eq $type;
1045 push @result, $rr->address;
1048 return \@result;
1049 } else {
1050 error("unknown ferm built-in function");
1052 } else {
1053 return $token;
1057 # returns the next parameter, but only allow a scalar
1058 sub getvar {
1059 my $token = getvalues(@_);
1061 error('array not allowed here')
1062 if ref $token and ref $token eq 'ARRAY';
1064 return $token;
1067 sub get_function_params(%) {
1068 expect_token('(', 'function name must be followed by "()"');
1070 my $token = peek_token();
1071 if ($token eq ')') {
1072 require_next_token;
1073 return;
1076 my @params;
1078 while (1) {
1079 if (@params > 0) {
1080 $token = require_next_token();
1081 last
1082 if $token eq ')';
1084 error('"," expected')
1085 unless $token eq ',';
1088 push @params, getvalues(undef, undef, @_);
1091 return @params;
1094 # collect all tokens in a flat array reference until the end of the
1095 # command is reached
1096 sub collect_tokens() {
1097 my @level;
1098 my @tokens;
1100 while (1) {
1101 my $keyword = next_token();
1102 error('unexpected end of file within function/variable declaration')
1103 unless defined $keyword;
1105 if ($keyword =~ /^[\{\(]$/) {
1106 push @level, $keyword;
1107 } elsif ($keyword =~ /^[\}\)]$/) {
1108 my $expected = $keyword;
1109 $expected =~ tr/\}\)/\{\(/;
1110 my $opener = pop @level;
1111 error("unmatched '$keyword'")
1112 unless defined $opener and $opener eq $expected;
1113 } elsif ($keyword eq ';' and @level == 0) {
1114 last;
1117 push @tokens, $keyword;
1119 last
1120 if $keyword eq '}' and @level == 0;
1123 return \@tokens;
1127 # returns the specified value as an array. dereference arrayrefs
1128 sub to_array($) {
1129 my $value = shift;
1130 die unless wantarray;
1131 die if @_;
1132 unless (ref $value) {
1133 return $value;
1134 } elsif (ref $value eq 'ARRAY') {
1135 return @$value;
1136 } else {
1137 die;
1141 # evaluate the specified value as bool
1142 sub eval_bool($) {
1143 my $value = shift;
1144 die if wantarray;
1145 die if @_;
1146 unless (ref $value) {
1147 return $value;
1148 } elsif (ref $value eq 'ARRAY') {
1149 return @$value > 0;
1150 } else {
1151 die;
1155 sub is_netfilter_core_target($) {
1156 my $target = shift;
1157 die unless defined $target and length $target;
1159 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1162 sub is_netfilter_module_target($$) {
1163 my ($domain_family, $target) = @_;
1164 die unless defined $target and length $target;
1166 return defined $domain_family &&
1167 exists $target_defs{$domain_family} &&
1168 exists $target_defs{$domain_family}{$target};
1171 sub is_netfilter_builtin_chain($$) {
1172 my ($table, $chain) = @_;
1174 return grep { $_ eq $chain }
1175 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1178 sub netfilter_canonical_protocol($) {
1179 my $proto = shift;
1180 return 'icmpv6'
1181 if $proto eq 'ipv6-icmp';
1182 return 'mh'
1183 if $proto eq 'ipv6-mh';
1184 return $proto;
1187 sub netfilter_protocol_module($) {
1188 my $proto = shift;
1189 return unless defined $proto;
1190 return 'icmp6'
1191 if $proto eq 'icmpv6';
1192 return $proto;
1195 # escape the string in a way safe for the shell
1196 sub shell_escape($) {
1197 my $token = shift;
1199 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1201 if ($option{fast}) {
1202 # iptables-save/iptables-restore are quite buggy concerning
1203 # escaping and special characters... we're trying our best
1204 # here
1206 $token =~ s,",',g;
1207 $token = '"' . $token . '"'
1208 if $token =~ /[\s\'\\;&]/s;
1209 } else {
1210 return $token
1211 if $token =~ /^\`.*\`$/;
1212 $token =~ s/'/\\'/g;
1213 $token = '\'' . $token . '\''
1214 if $token =~ /[\s\"\\;<>&|]/s;
1217 return $token;
1220 # append an option to the shell command line, using information from
1221 # the module definition (see %match_defs etc.)
1222 sub shell_append_option($$$) {
1223 my ($ref, $keyword, $value) = @_;
1225 if (ref $value) {
1226 if (ref $value eq 'negated') {
1227 $value = $value->[0];
1228 $keyword .= ' !';
1229 } elsif (ref $value eq 'pre_negated') {
1230 $value = $value->[0];
1231 $$ref .= ' !';
1235 unless (defined $value) {
1236 $$ref .= " --$keyword";
1237 } elsif (ref $value) {
1238 if (ref $value eq 'params') {
1239 $$ref .= " --$keyword ";
1240 $$ref .= join(' ', map { shell_escape($_) } @$value);
1241 } elsif (ref $value eq 'multi') {
1242 foreach (@$value) {
1243 $$ref .= " --$keyword " . shell_escape($_);
1245 } else {
1246 die;
1248 } else {
1249 $$ref .= " --$keyword " . shell_escape($value);
1253 # convert an internal rule structure into an iptables call
1254 sub tables($) {
1255 my $rule = shift;
1257 my $domain = $rule->{domain};
1258 my $domain_info = $domains{$domain};
1259 $domain_info->{enabled} = 1;
1260 my $domain_family = $rule->{domain_family};
1262 my $table = $rule->{table};
1263 my $table_info = $domain_info->{tables}{$table} ||= {};
1265 my $chain = $rule->{chain};
1266 my $chain_info = $table_info->{chains}{$chain} ||= {};
1267 my $chain_rules = $chain_info->{rules} ||= [];
1269 return if $option{flush};
1271 my $action = $rule->{action};
1273 # return if this is a declaration-only rule
1274 return
1275 unless $rule->{has_rule};
1277 my $rr = '';
1279 # general iptables options
1281 while (my ($keyword, $value) = each %{$rule->{builtin}}) {
1282 shell_append_option(\$rr, $keyword, $value);
1286 # match module options
1289 my %modules;
1291 if (defined $rule->{builtin}{protocol}) {
1292 my $proto = $rule->{builtin}{protocol};
1294 # special case: --dport and --sport for TCP/UDP
1295 if ($domain_family eq 'ip' and
1296 (exists $rule->{dport} or exists $rule->{sport}) and
1297 $proto =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
1298 unless (exists $modules{$proto}) {
1299 $rr .= " -m $proto";
1300 $modules{$proto} = 1;
1303 shell_append_option(\$rr, 'dport', $rule->{dport})
1304 if exists $rule->{dport};
1305 shell_append_option(\$rr, 'sport', $rule->{sport})
1306 if exists $rule->{sport};
1310 # modules stored in %match_defs
1312 foreach my $match (@{$rule->{match}}) {
1313 my $module_name = $match->{name};
1314 unless (exists $modules{$module_name}) {
1315 $rr .= " -m $module_name";
1316 $modules{$module_name} = 1;
1319 while (my ($keyword, $value) = each %{$match->{options}}) {
1320 shell_append_option(\$rr, $keyword, $value);
1325 # target options
1328 if ($action->{type} eq 'jump') {
1329 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1330 $rr .= " -j " . $action->{chain};
1331 } elsif ($action->{type} eq 'goto') {
1332 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1333 $rr .= " -g " . $action->{chain};
1334 } elsif ($action->{type} eq 'target') {
1335 $rr .= " -j " . $action->{target};
1337 # targets stored in %target_defs
1339 while (my ($keyword, $value) = each %{$rule->{target_options}}) {
1340 shell_append_option(\$rr, $keyword, $value);
1342 } elsif ($action->{type} ne 'nop') {
1343 die;
1346 # this line is done
1347 push @$chain_rules, { rule => $rr,
1348 script => $rule->{script},
1352 sub transform_rule($) {
1353 my $rule = shift;
1355 $rule->{builtin}{protocol} = 'icmpv6'
1356 if $rule->{domain} eq 'ip6' and $rule->{builtin}{protocol} eq 'icmp';
1359 sub printrule($) {
1360 my $rule = shift;
1362 transform_rule($rule);
1364 # prints all rules in a hash
1365 tables($rule);
1369 sub check_unfold(\@$$) {
1370 my ($unfold, $parent, $key) = @_;
1372 return unless ref $parent->{$key} and
1373 ref $parent->{$key} eq 'ARRAY';
1375 push @$unfold, $parent, $key, $parent->{$key};
1378 # convert a bunch of internal rule structures in iptables calls,
1379 # unfold arrays during that
1380 sub mkrules($) {
1381 # compile the list hashes into rules
1382 my $fw = shift;
1384 my @unfold;
1386 foreach my $key (qw(domain table chain)) {
1387 check_unfold(@unfold, $fw, $key);
1390 foreach my $key (keys %{$fw->{builtin}}) {
1391 check_unfold(@unfold, $fw->{builtin}, $key);
1394 foreach my $match (@{$fw->{match}}) {
1395 while (my ($key, $value) = each %{$match->{options}}) {
1396 check_unfold(@unfold, $match->{options}, $key);
1400 check_unfold(@unfold, $fw, 'sport');
1401 check_unfold(@unfold, $fw, 'dport');
1403 if (@unfold == 0) {
1404 printrule($fw);
1405 return;
1408 sub dofr {
1409 my $fw = shift;
1410 my ($parent, $key, $values) = (shift, shift, shift);
1412 foreach my $value (@$values) {
1413 $parent->{$key} = $value;
1415 if (@_) {
1416 dofr($fw, @_);
1417 } else {
1418 printrule($fw);
1423 dofr($fw, @unfold);
1426 sub filter_domains($) {
1427 my $domains = shift;
1428 my $result = [];
1430 foreach my $domain (to_array $domains) {
1431 next if exists $option{domain}
1432 and $domain ne $option{domain};
1434 eval {
1435 initialize_domain($domain);
1437 error($@) if $@;
1439 push @$result, $domain;
1442 return @$result == 1 ? $result->[0] : $result;
1445 # parse a keyword from a module definition
1446 sub parse_keyword($$$$) {
1447 my ($current, $def, $keyword, $negated_ref) = @_;
1449 my $params = $def->{params};
1451 my $value;
1453 my $negated;
1454 if ($$negated_ref && exists $def->{pre_negation}) {
1455 $negated = 1;
1456 undef $$negated_ref;
1459 unless (defined $params) {
1460 undef $value;
1461 } elsif (ref $params && ref $params eq 'CODE') {
1462 $value = &$params($current);
1463 } elsif ($params eq 'm') {
1464 $value = bless [ to_array getvalues() ], 'multi';
1465 } elsif ($params =~ /^[a-z]/) {
1466 if (exists $def->{negation} and not $negated) {
1467 my $token = peek_token();
1468 if ($token eq '!') {
1469 require_next_token;
1470 $negated = 1;
1474 my @params;
1475 foreach my $p (split(//, $params)) {
1476 if ($p eq 's') {
1477 push @params, getvar();
1478 } elsif ($p eq 'c') {
1479 my @v = to_array getvalues(undef, undef,
1480 non_empty => 1);
1481 push @params, join(',', @v);
1482 } else {
1483 die;
1487 $value = @params == 1
1488 ? $params[0]
1489 : bless \@params, 'params';
1490 } elsif ($params == 1) {
1491 if (exists $def->{negation} and not $negated) {
1492 my $token = peek_token();
1493 if ($token eq '!') {
1494 require_next_token;
1495 $negated = 1;
1499 $value = getvalues();
1501 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1502 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1503 } else {
1504 if (exists $def->{negation} and not $negated) {
1505 my $token = peek_token();
1506 if ($token eq '!') {
1507 require_next_token;
1508 $negated = 1;
1512 $value = bless [ map {
1513 getvar()
1514 } (1..$params) ], 'params';
1517 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1518 if $negated;
1520 return $value;
1523 # parse options of a module
1524 sub parse_option($$$$$) {
1525 my ($def, $current, $store, $keyword, $negated_ref) = @_;
1527 while (exists $def->{alias}) {
1528 ($keyword, $def) = @{$def->{alias}};
1529 die unless defined $def;
1532 $store->{$keyword}
1533 = parse_keyword($current, $def,
1534 $keyword, $negated_ref);
1535 $current->{has_rule} = 1;
1536 return 1;
1539 # parse options for a protocol module definition
1540 sub parse_protocol_options($$$$) {
1541 my ($current, $proto, $keyword, $negated_ref) = @_;
1543 my $domain_family = $current->{'domain_family'};
1544 my $proto_defs = $proto_defs{$domain_family};
1545 return unless defined $proto_defs;
1547 my $proto_def = $proto_defs->{$proto};
1548 return unless defined $proto_def and
1549 exists $proto_def->{keywords}{$keyword};
1551 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1552 my $module = { name => $module_name,
1553 options => {},
1554 defs => $proto_def,
1556 push @{$current->{match}}, $module;
1558 return parse_option($proto_def->{keywords}{$keyword},
1559 $current, $module->{options},
1560 $keyword, $negated_ref);
1563 sub copy_on_write($$) {
1564 my ($rule, $key) = @_;
1565 return unless exists $rule->{cow}{$key};
1566 $rule->{$key} = {%{$rule->{$key}}};
1567 delete $rule->{cow}{$key};
1570 sub clone_match($) {
1571 my $match = shift;
1572 return { name => $match->{name},
1573 options => { %{$match->{options}} },
1574 defs => $match->{defs},
1578 sub new_level(\%$) {
1579 my ($current, $prev) = @_;
1581 %$current = ();
1582 if (defined $prev) {
1583 # copy data from previous level
1584 $current->{cow} = { keywords => 1, };
1585 $current->{keywords} = $prev->{keywords};
1586 $current->{builtin} = { %{$prev->{builtin}} };
1587 $current->{match} = [ map { clone_match($_) } @{$prev->{match}} ];
1588 $current->{action} = { %{$prev->{action}} };
1589 foreach my $key (qw(domain domain_family table chain sport dport)) {
1590 $current->{$key} = $prev->{$key}
1591 if exists $prev->{$key};
1593 } else {
1594 $current->{cow} = {};
1595 $current->{keywords} = {};
1596 $current->{builtin} = {};
1597 $current->{match} = [];
1598 $current->{action} = {};
1602 sub rule_defined(\%) {
1603 my $rule = shift;
1604 return defined($rule->{domain}) or
1605 keys(%{$rule->{builtin}}) > 0 or
1606 keys(%{$rule->{match}}) > 0 or
1607 keys(%{$rule->{action}}) > 0;
1610 # the main parser loop: read tokens, convert them into internal rule
1611 # structures
1612 sub enter($$) {
1613 my $lev = shift; # current recursion depth
1614 my $prev = shift; # previous rule hash
1616 # enter is the core of the firewall setup, it is a
1617 # simple parser program that recognizes keywords and
1618 # retreives parameters to set up the kernel routing
1619 # chains
1621 my $base_level = $script->{base_level} || 0;
1622 die if $base_level > $lev;
1624 my %current;
1625 new_level(%current, $prev);
1627 # read keywords 1 by 1 and dump into parser
1628 while (defined (my $keyword = next_token())) {
1629 # check if the current rule should be negated
1630 my $negated = $keyword eq '!';
1631 if ($negated) {
1632 # negation. get the next word which contains the 'real'
1633 # rule
1634 $keyword = getvar();
1636 error('unexpected end of file after negation')
1637 unless defined $keyword;
1640 # the core: parse all data
1641 for ($keyword)
1643 # deprecated keyword?
1644 if (exists $deprecated_keywords{$keyword}) {
1645 my $new_keyword = $deprecated_keywords{$keyword};
1646 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1647 $keyword = $new_keyword;
1650 # effectuation operator
1651 if ($keyword eq ';') {
1652 if ($current{has_rule} and not $current{action}{type}) {
1653 # something is wrong when a rule was specifiedd,
1654 # but no action
1655 error('No action defined; did you mean "NOP"?');
1658 error('No chain defined') unless defined $current{chain};
1660 $current{script} = { filename => $script->{filename},
1661 line => $script->{line},
1664 mkrules(\%current);
1666 # and clean up variables set in this level
1667 new_level(%current, $prev);
1669 next;
1672 # conditional expression
1673 if ($keyword eq '@if') {
1674 unless (eval_bool(getvalues)) {
1675 collect_tokens;
1676 my $token = peek_token();
1677 require_next_token() if $token and $token eq '@else';
1680 next;
1683 if ($keyword eq '@else') {
1684 # hack: if this "else" has not been eaten by the "if"
1685 # handler above, we believe it came from an if clause
1686 # which evaluated "true" - remove the "else" part now.
1687 collect_tokens;
1688 next;
1691 # hooks for custom shell commands
1692 if ($keyword eq 'hook') {
1693 error('"hook" must be the first token in a command')
1694 if rule_defined(%current);
1696 my $position = getvar();
1697 my $hooks;
1698 if ($position eq 'pre') {
1699 $hooks = \@pre_hooks;
1700 } elsif ($position eq 'post') {
1701 $hooks = \@post_hooks;
1702 } else {
1703 error("Invalid hook position: '$position'");
1706 push @$hooks, getvar();
1708 expect_token(';');
1709 next;
1712 # recursing operators
1713 if ($keyword eq '{') {
1714 # push stack
1715 my $old_stack_depth = @stack;
1717 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1719 # recurse
1720 enter($lev + 1, \%current);
1722 # pop stack
1723 shift @stack;
1724 die unless @stack == $old_stack_depth;
1726 # after a block, the command is finished, clear this
1727 # level
1728 new_level(%current, $prev);
1730 next;
1733 if ($keyword eq '}') {
1734 error('Unmatched "}"')
1735 if $lev <= $base_level;
1737 # consistency check: check if they havn't forgotten
1738 # the ';' before the last statement
1739 error('Missing semicolon before "}"')
1740 if $current{has_rule};
1742 # and exit
1743 return;
1746 # include another file
1747 if ($keyword eq '@include' or $keyword eq 'include') {
1748 my @files = collect_filenames to_array getvalues;
1749 $keyword = next_token;
1750 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1751 unless defined $keyword and $keyword eq ';';
1753 foreach my $filename (@files) {
1754 # save old script, open new script
1755 my $old_script = $script;
1756 open_script($filename);
1757 $script->{base_level} = $lev + 1;
1759 # push stack
1760 my $old_stack_depth = @stack;
1762 my $stack = {};
1764 if (@stack > 0) {
1765 # include files may set variables for their parent
1766 $stack->{vars} = ($stack[0]{vars} ||= {});
1767 $stack->{functions} = ($stack[0]{functions} ||= {});
1768 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1771 unshift @stack, $stack;
1773 # parse the script
1774 enter($lev + 1, \%current);
1776 # pop stack
1777 shift @stack;
1778 die unless @stack == $old_stack_depth;
1780 # restore old script
1781 $script = $old_script;
1784 next;
1787 # definition of a variable or function
1788 if ($keyword eq '@def' or $keyword eq 'def') {
1789 error('"def" must be the first token in a command')
1790 if $current{has_rule};
1792 my $type = require_next_token();
1793 if ($type eq '$') {
1794 my $name = require_next_token();
1795 error('invalid variable name')
1796 unless $name =~ /^\w+$/;
1798 expect_token('=');
1800 my $value = getvalues(undef, undef, allow_negation => 1);
1802 expect_token(';');
1804 $stack[0]{vars}{$name} = $value
1805 unless exists $stack[-1]{vars}{$name};
1806 } elsif ($type eq '&') {
1807 my $name = require_next_token();
1808 error('invalid function name')
1809 unless $name =~ /^\w+$/;
1811 expect_token('(', 'function parameter list or "()" expected');
1813 my @params;
1814 while (1) {
1815 my $token = require_next_token();
1816 last if $token eq ')';
1818 if (@params > 0) {
1819 error('"," expected')
1820 unless $token eq ',';
1822 $token = require_next_token();
1825 error('"$" and parameter name expected')
1826 unless $token eq '$';
1828 $token = require_next_token();
1829 error('invalid function parameter name')
1830 unless $token =~ /^\w+$/;
1832 push @params, $token;
1835 my %function;
1837 $function{params} = \@params;
1839 expect_token('=');
1841 my $tokens = collect_tokens();
1842 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1843 $function{tokens} = $tokens;
1845 $stack[0]{functions}{$name} = \%function
1846 unless exists $stack[-1]{functions}{$name};
1847 } else {
1848 error('"$" (variable) or "&" (function) expected');
1851 next;
1854 # def references
1855 if ($keyword eq '$') {
1856 error('variable references are only allowed as keyword parameter');
1859 if ($keyword eq '&') {
1860 my $name = require_next_token;
1861 error('function name expected')
1862 unless $name =~ /^\w+$/;
1864 my $function;
1865 foreach (@stack) {
1866 $function = $_->{functions}{$name};
1867 last if defined $function;
1869 error("no such function: \&$name")
1870 unless defined $function;
1872 my $paramdef = $function->{params};
1873 die unless defined $paramdef;
1875 my @params = get_function_params(allow_negation => 1);
1877 error("Wrong number of parameters for function '\&$name': "
1878 . @$paramdef . " expected, " . @params . " given")
1879 unless @params == @$paramdef;
1881 my %vars;
1882 for (my $i = 0; $i < @params; $i++) {
1883 $vars{$paramdef->[$i]} = $params[$i];
1886 if ($function->{block}) {
1887 # block {} always ends the current rule, so if the
1888 # function contains a block, we have to require
1889 # the calling rule also ends here
1890 expect_token(';');
1893 my @tokens = @{$function->{tokens}};
1894 for (my $i = 0; $i < @tokens; $i++) {
1895 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1896 exists $vars{$tokens[$i + 1]}) {
1897 my @value = to_array($vars{$tokens[$i + 1]});
1898 @value = ('(', @value, ')')
1899 unless @tokens == 1;
1900 splice(@tokens, $i, 2, @value);
1901 $i += @value - 2;
1902 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1903 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1907 unshift @{$script->{tokens}}, @tokens;
1909 next;
1912 # where to put the rule?
1913 if ($keyword eq 'domain') {
1914 error('Domain is already specified')
1915 if exists $current{domain};
1917 my $domain = getvalues();
1918 my $filtered_domain = filter_domains($domain);
1919 my $domain_family;
1920 unless (ref $domain) {
1921 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1922 } elsif (@$domain == 0) {
1923 $domain_family = 'none';
1924 } elsif (grep { not /^ip6?$/s } @$domain) {
1925 error('Cannot combine non-IP domains');
1926 } else {
1927 $domain_family = 'ip';
1929 $current{domain_family} = $domain_family;
1930 $current{keywords} = get_builtin_keywords($domain_family);
1931 delete $current{cow}{keywords};
1933 $current{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1935 next;
1938 if ($keyword eq 'table') {
1939 error('Table is already specified')
1940 if exists $current{table};
1941 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1943 unless (exists $current{domain}) {
1944 $current{domain} = filter_domains('ip');
1945 $current{domain_family} = 'ip';
1946 $current{keywords} = get_builtin_keywords('ip');
1947 delete $current{cow}{keywords};
1950 next;
1953 if ($keyword eq 'chain') {
1954 error('Chain is already specified')
1955 if exists $current{chain};
1956 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1958 # ferm 1.1 allowed lower case built-in chain names
1959 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1960 error('Please write built-in chain names in upper case')
1961 if /^(?:input|forward|output|prerouting|postrouting)$/;
1964 unless (exists $current{domain}) {
1965 $current{domain} = filter_domains('ip');
1966 $current{domain_family} = 'ip';
1967 $current{keywords} = get_builtin_keywords('ip');
1968 delete $current{cow}{keywords};
1971 $current{table} = 'filter'
1972 unless exists $current{table};
1974 next;
1977 error('Chain must be specified')
1978 unless exists $current{chain};
1980 # policy for built-in chain
1981 if ($keyword eq 'policy') {
1982 error('Cannot specify matches for policy')
1983 if $current{has_rule};
1985 my $policy = getvar();
1986 error("Invalid policy target: $policy")
1987 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1989 expect_token(';');
1991 foreach my $domain (to_array $current{domain}) {
1992 foreach my $table (to_array $current{table}) {
1993 foreach my $chain (to_array $current{chain}) {
1994 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1999 new_level(%current, $prev);
2000 next;
2003 # create a subchain
2004 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2005 error('Chain must be specified')
2006 unless exists $current{chain};
2008 error('No rule specified before "@subchain"')
2009 unless $current{has_rule};
2011 my $subchain;
2012 $keyword = next_token();
2014 if ($keyword =~ /^(["'])(.*)\1$/s) {
2015 $subchain = $2;
2016 $keyword = next_token();
2017 } else {
2018 $subchain = 'ferm_auto_' . ++$auto_chain;
2021 error('"{" or chain name expected after "@subchain"')
2022 unless $keyword eq '{';
2024 # create a deep copy of %current, only containing values
2025 # which must be in the subchain
2026 my %inner = ( cow => { keywords => 1, },
2027 keywords => $current{keywords},
2028 builtin => {},
2029 action => {},
2031 $inner{domain} = $current{domain};
2032 $inner{domain_family} = $current{domain_family};
2033 $inner{table} = $current{table};
2034 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2035 $inner{builtin}{protocol} = $current{builtin}{protocol}
2036 if exists $current{builtin}{protocol};
2038 # enter the block
2039 enter(1, \%inner);
2041 # now handle the parent - it's a jump to the sub chain
2042 $current{action} = { type => 'jump',
2043 chain => $subchain,
2046 $current{script} = { filename => $script->{filename},
2047 line => $script->{line},
2050 mkrules(\%current);
2052 # and clean up variables set in this level
2053 new_level(%current, $prev);
2055 next;
2058 # everything else must be part of a "real" rule, not just
2059 # "policy only"
2060 $current{has_rule}++;
2062 # extended parameters:
2063 if ($keyword =~ /^mod(?:ule)?$/) {
2064 foreach my $module (to_array getvalues) {
2065 next if grep { $_->{name} eq $module } @{$current{match}};
2067 my $domain_family = $current{domain_family};
2068 my $defs = $match_defs{$domain_family}{$module};
2069 if (not defined $defs and exists $current{builtin}{protocol}) {
2070 my $proto = $current{builtin}{protocol};
2071 unless (ref $proto) {
2072 $proto = netfilter_canonical_protocol($current{builtin}{protocol});
2073 $defs = $proto_defs{$domain_family}{$proto}
2074 if netfilter_protocol_module($proto) eq $module;
2078 push @{$current{match}}, { name => $module,
2079 options => {},
2080 defs => $defs,
2083 if (defined $defs) {
2084 copy_on_write(\%current, 'keywords');
2085 while (my ($k, $def) = each %{$defs->{keywords}}) {
2086 $current{keywords}{$k} = [ 'match', $module, $def ];
2091 next;
2094 # keywords from $current{keywords}
2096 if (exists $current{keywords}{$keyword}) {
2097 my ($type, $module, $def) = @{$current{keywords}{$keyword}};
2098 my $store;
2099 if ($type eq 'builtin') {
2100 $store = $current{builtin};
2101 } elsif ($type eq 'match') {
2102 $store = (grep { $_->{name} eq $module } @{$current{match}})[-1]->{options};
2103 } elsif ($type eq 'target') {
2104 $store = $current{target_options} ||= {};
2105 } else {
2106 die;
2109 parse_option($def, \%current, $store, $keyword, \$negated);
2110 next;
2114 # actions
2117 # jump action
2118 if ($keyword eq 'jump') {
2119 error('There can only one action per rule')
2120 if defined $current{action}{type};
2121 my $chain = getvar();
2122 if (is_netfilter_core_target($chain) or
2123 is_netfilter_module_target($current{domain_family}, $chain)) {
2124 my $defs = $target_defs{$current{domain_family}} &&
2125 $target_defs{$current{domain_family}}{$chain};
2126 $current{action} = { type => 'target',
2127 target => $chain,
2128 defs => $defs,
2131 if (defined $defs) {
2132 copy_on_write(\%current, 'keywords');
2133 while (my ($k, $def) = each %{$defs->{keywords}}) {
2134 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2137 } else {
2138 $current{action} = { type => 'jump',
2139 chain => $chain,
2142 next;
2145 # goto action
2146 if ($keyword eq 'realgoto') {
2147 error('There can only one action per rule')
2148 if defined $current{action}{type};
2149 $current{action} = { type => 'goto',
2150 chain => getvar(),
2152 next;
2155 # action keywords
2156 if (is_netfilter_core_target($keyword)) {
2157 error('There can only one action per rule')
2158 if defined $current{action}{type};
2159 $current{action} = { type => 'target',
2160 target => $keyword,
2162 next;
2165 if ($keyword eq 'NOP') {
2166 error('There can only one action per rule')
2167 if defined $current{action}{type};
2168 $current{action} = { type => 'nop',
2170 next;
2173 if (is_netfilter_module_target($current{domain_family}, $keyword)) {
2174 error('There can only one action per rule')
2175 if defined $current{action}{type};
2177 if ($keyword eq 'TCPMSS') {
2178 my $protos = $current{builtin}{protocol};
2179 error('No protocol specified before TCPMSS')
2180 unless defined $protos;
2181 foreach my $proto (to_array $protos) {
2182 error('TCPMSS not available for protocol "$proto"')
2183 unless $proto eq 'tcp';
2187 my $defs = $target_defs{$current{domain_family}}{$keyword};
2189 $current{action} = { type => 'target',
2190 target => $keyword,
2191 defs => $defs,
2194 if (defined $defs) {
2195 copy_on_write(\%current, 'keywords');
2196 while (my ($k, $def) = each %{$defs->{keywords}}) {
2197 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2201 next;
2204 my $proto = $current{builtin}{protocol};
2207 # protocol specific options
2210 if (defined $proto and not ref $proto) {
2211 $proto = netfilter_canonical_protocol($proto);
2213 if ($proto eq 'icmp') {
2214 my $domains = $current{domain};
2215 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2218 parse_protocol_options(\%current, $proto, $keyword, \$negated)
2219 and next;
2222 # port switches
2223 if ($keyword =~ /^[sd]port$/) {
2224 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2225 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2227 $current{$keyword} = getvalues(undef, undef,
2228 allow_negation => 1);
2229 next;
2232 # default
2233 error("Unrecognized keyword: $keyword");
2236 # if the rule didn't reset the negated flag, it's not
2237 # supported
2238 error("Doesn't support negation: $keyword")
2239 if $negated;
2242 error('Missing "}" at end of file')
2243 if $lev > $base_level;
2245 # consistency check: check if they havn't forgotten
2246 # the ';' before the last statement
2247 error("Missing semicolon before end of file")
2248 if $current{has_rule}; # XXX
2251 sub execute_command {
2252 my ($command, $script) = @_;
2254 print LINES "$command\n"
2255 if $option{lines};
2256 return if $option{noexec};
2258 my $ret = system($_);
2259 unless ($ret == 0) {
2260 if ($? == -1) {
2261 print STDERR "failed to execute: $!\n";
2262 exit 1;
2263 } elsif ($? & 0x7f) {
2264 printf STDERR "child died with signal %d\n", $? & 0x7f;
2265 return 1;
2266 } else {
2267 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2268 if defined $script;
2269 return $? >> 8;
2273 return;
2276 sub execute_slow($$) {
2277 my ($domain, $domain_info) = @_;
2279 my $domain_cmd = $domain_info->{tools}{tables};
2281 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2282 my $table_cmd = "$domain_cmd -t $table";
2284 # reset chain policies
2285 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2286 next unless $chain_info->{builtin} or
2287 (not $table_info->{has_builtin} and
2288 is_netfilter_builtin_chain($table, $chain));
2289 $status ||= execute_command("$table_cmd -P $chain ACCEPT");
2292 # clear
2293 $status ||= execute_command("$table_cmd -F");
2294 $status ||= execute_command("$table_cmd -X");
2296 next if $option{flush};
2298 # create chains / set policy
2299 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2300 if (exists $chain_info->{policy}) {
2301 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2302 unless $chain_info->{policy} eq 'ACCEPT';
2303 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2304 $status ||= execute_command("$table_cmd -N $chain");
2308 # dump rules
2309 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2310 my $chain_cmd = "$table_cmd -A $chain";
2311 foreach my $rule (@{$chain_info->{rules}}) {
2312 $status ||= execute_command($chain_cmd . $rule->{rule});
2317 return $status;
2320 sub rules_to_save($$) {
2321 my ($domain, $domain_info) = @_;
2323 # convert this into an iptables-save text
2324 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2326 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2327 # select table
2328 $result .= '*' . $table . "\n";
2330 # create chains / set policy
2331 foreach my $chain (sort keys %{$table_info->{chains}}) {
2332 my $chain_info = $table_info->{chains}{$chain};
2333 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2334 unless (defined $policy) {
2335 if (is_netfilter_builtin_chain($table, $chain)) {
2336 $policy = 'ACCEPT';
2337 } else {
2338 $policy = '-';
2341 $result .= ":$chain $policy\ [0:0]\n";
2344 next if $option{flush};
2346 # dump rules
2347 foreach my $chain (sort keys %{$table_info->{chains}}) {
2348 my $chain_info = $table_info->{chains}{$chain};
2349 foreach my $rule (@{$chain_info->{rules}}) {
2350 $result .= "-A $chain$rule->{rule}\n";
2354 # do it
2355 $result .= "COMMIT\n";
2358 return $result;
2361 sub restore_domain($$) {
2362 my ($domain, $save) = @_;
2364 my $path = $domains{$domain}{tools}{'tables-restore'};
2366 local *RESTORE;
2367 open RESTORE, "|$path"
2368 or die "Failed to run $path: $!\n";
2370 print RESTORE $save;
2372 close RESTORE
2373 or die "Failed to run $path\n";
2376 sub execute_fast($$) {
2377 my ($domain, $domain_info) = @_;
2379 my $save = rules_to_save($domain, $domain_info);
2381 if ($option{lines}) {
2382 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2383 if $option{shell};
2384 print LINES $save;
2385 print LINES "EOT\n"
2386 if $option{shell};
2389 return if $option{noexec};
2391 eval {
2392 restore_domain($domain, $save);
2394 if ($@) {
2395 print STDERR $@;
2396 return 1;
2399 return;
2402 sub rollback() {
2403 my $error;
2404 while (my ($domain, $domain_info) = each %domains) {
2405 next unless $domain_info->{enabled};
2406 unless (defined $domain_info->{tools}{'tables-restore'}) {
2407 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2408 next;
2411 my $reset = '';
2412 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2413 my $reset_chain = '';
2414 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2415 next unless is_netfilter_builtin_chain($table, $chain);
2416 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2418 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2419 if length $reset_chain;
2422 $reset .= $domain_info->{previous}
2423 if defined $domain_info->{previous};
2425 restore_domain($domain, $reset);
2428 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2429 exit 1;
2432 sub alrm_handler {
2433 # do nothing, just interrupt a system call
2436 sub confirm_rules() {
2437 $SIG{ALRM} = \&alrm_handler;
2439 alarm(5);
2441 print STDERR "\n"
2442 . "ferm has applied the new firewall rules.\n"
2443 . "Please type 'yes' to confirm:\n";
2444 STDERR->flush();
2446 alarm(30);
2448 my $line = '';
2449 STDIN->sysread($line, 3);
2451 eval {
2452 require POSIX;
2453 POSIX::tcflush(*STDIN, 2);
2455 print STDERR "$@" if $@;
2457 $SIG{ALRM} = 'DEFAULT';
2459 return $line eq 'yes';
2462 # end of ferm
2464 __END__
2466 =head1 NAME
2468 ferm - a firewall rule parser for linux
2470 =head1 SYNOPSIS
2472 B<ferm> I<options> I<inputfiles>
2474 =head1 OPTIONS
2476 -n, --noexec Do not execute the rules, just simulate
2477 -F, --flush Flush all netfilter tables managed by ferm
2478 -l, --lines Show all rules that were created
2479 -i, --interactive Interactive mode: revert if user does not confirm
2480 --remote Remote mode; ignore host specific configuration.
2481 This implies --noexec and --lines.
2482 -V, --version Show current version number
2483 -h, --help Look at this text
2484 --fast Generate an iptables-save file, used by iptables-restore
2485 --shell Generate a shell script which calls iptables-restore
2486 --domain {ip|ip6} Handle only the specified domain
2487 --def '$name=v' Override a variable
2489 =cut