moved copy_on_write()
[ferm.git] / src / ferm
blobe47c839f2a1a026e4bf1b328cd04da8c0168d5b7
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 # - was_created: custom chain has been created
78 # - non_empty: are there rules for this chain?
79 use vars qw(%domains);
81 ## constants
82 use vars qw(%deprecated_keywords);
84 # keywords from ferm 1.1 which are deprecated, and the new one; these
85 # are automatically replaced, and a warning is printed
86 %deprecated_keywords = ( goto => 'jump',
89 # these hashes provide the Netfilter module definitions
90 use vars qw(%proto_defs %match_defs %target_defs);
93 # This subsubsystem allows you to support (most) new netfilter modules
94 # in ferm. Add a call to one of the "add_XY_def()" functions below.
96 # Ok, now about the cryptic syntax: the function "add_XY_def()"
97 # registers a new module. There are three kinds of modules: protocol
98 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
99 # target modules (e.g. DNAT, MARK).
101 # The first parameter is always the module name which is passed to
102 # iptables with "-p", "-m" or "-j" (depending on which kind of module
103 # this is).
105 # After that, you add an encoded string for each option the module
106 # supports. This is where it becomes tricky.
108 # foo defaults to an option with one argument (which may be a ferm
109 # array)
111 # foo*0 option without any arguments
113 # foo=s one argument which must not be a ferm array ('s' stands for
114 # 'scalar')
116 # u32=m an array which renders into multiple iptables options in one
117 # rule
119 # ctstate=c one argument, if it's an array, pass it to iptables as a
120 # single comma separated value; example:
121 # ctstate (ESTABLISHED RELATED) translates to:
122 # --ctstate ESTABLISHED,RELATED
124 # foo=sac three arguments: scalar, array, comma separated; you may
125 # concatenate more than one letter code after the '='
127 # foo&bar one argument; call the perl function '&bar()' which parses
128 # the argument
130 # !foo negation is allowed and the '!' is written before the keyword
132 # foo! same as above, but '!' is after the keyword and before the
133 # parameters
135 # to:=to-destination makes "to" an alias for "to-destination"; you have
136 # to add a declaration for option "to-destination"
139 # add a module definition
140 sub add_def_x {
141 my $defs = shift;
142 my $domain_family = 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 = 1;
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 add_def_x(\%proto_defs, @_);
175 # add a match module definition
176 sub add_match_def_x(@) {
177 add_def_x(\%match_defs, @_);
180 # add a target module definition
181 sub add_target_def_x(@) {
182 add_def_x(\%target_defs, @_);
185 sub add_def {
186 my $defs = shift;
187 add_def_x($defs, 'ip', @_);
190 # add a protocol module definition
191 sub add_proto_def(@) {
192 add_def(\%proto_defs, @_);
195 # add a match module definition
196 sub add_match_def(@) {
197 add_def(\%match_defs, @_);
200 # add a target module definition
201 sub add_target_def(@) {
202 add_def(\%target_defs, @_);
205 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
206 add_proto_def 'mh', qw(mh-type!);
207 add_proto_def 'icmp', qw(icmp-type!);
208 add_proto_def 'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
209 add_proto_def 'sctp', qw(chunk-types!=sc);
210 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
211 add_proto_def 'udp', qw();
213 add_match_def '',
214 # --protocol
215 qw(protocol! proto:=protocol),
216 # --source, --destination
217 qw(source! saddr:=source destination! daddr:=destination),
218 # --in-interface
219 qw(in-interface! interface:=in-interface if:=in-interface),
220 # --out-interface
221 qw(out-interface! outerface:=out-interface of:=out-interface),
222 # --fragment
223 qw(!fragment*0);
224 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
225 add_match_def 'addrtype', qw(src-type dst-type);
226 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
227 add_match_def 'comment', qw(comment=s);
228 add_match_def 'condition', qw(condition!);
229 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
230 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
231 add_match_def 'connmark', qw(mark);
232 add_match_def 'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
233 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
234 add_match_def 'dscp', qw(dscp dscp-class);
235 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
236 add_match_def 'esp', qw(espspi!);
237 add_match_def 'eui64';
238 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
239 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
240 add_match_def 'helper', qw(helper);
241 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
242 add_match_def 'length', qw(length!);
243 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
244 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
245 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
246 add_match_def 'iprange', qw(!src-range !dst-range);
247 add_match_def 'ipv6header', qw(header!=c soft*0);
248 add_match_def 'limit', qw(limit=s limit-burst=s);
249 add_match_def 'mac', qw(mac-source!);
250 add_match_def 'mark', qw(mark);
251 add_match_def 'multiport', qw(source-ports!&multiport_params),
252 qw(destination-ports!&multiport_params ports!&multiport_params);
253 add_match_def 'nth', qw(every counter start packet);
254 add_match_def 'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
255 add_match_def 'physdev', qw(physdev-in! physdev-out!),
256 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
257 add_match_def 'pkttype', qw(pkt-type),
258 add_match_def 'policy',
259 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
260 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
261 qw(psd-lo-ports-weight psd-hi-ports-weight);
262 add_match_def 'quota', qw(quota=s);
263 add_match_def 'random', qw(average);
264 add_match_def 'realm', qw(realm!);
265 add_match_def 'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0);
266 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
267 add_match_def 'set', qw(set=sc);
268 add_match_def 'state', qw(state=c);
269 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
270 add_match_def 'tcpmss', qw(!mss);
271 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s);
272 add_match_def 'tos', qw(!tos);
273 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
274 add_match_def 'u32', qw(u32=m);
276 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
277 add_target_def 'CLASSIFY', qw(set-class);
278 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
279 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
280 add_target_def 'DNAT', qw(to-destination to:=to-destination);
281 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
282 add_target_def 'ECN', qw(ecn-tcp-remove*0);
283 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
284 add_target_def 'LOG', qw(log-level log-prefix),
285 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
286 add_target_def 'MARK', qw(set-mark);
287 add_target_def 'MASQUERADE', qw(to-ports);
288 add_target_def 'MIRROR';
289 add_target_def 'NETMAP', qw(to);
290 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
291 add_target_def 'NFQUEUE', qw(queue-num);
292 add_target_def 'NOTRACK';
293 add_target_def 'REDIRECT', qw(to-ports);
294 add_target_def 'REJECT', qw(reject-with);
295 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
296 add_target_def 'SAME', qw(to nodst*0);
297 add_target_def 'SECMARK', qw(selctx);
298 add_target_def 'SET', qw(add-set=sc del-set=sc);
299 add_target_def 'SNAT', qw(to-source=m to:=to-source);
300 add_target_def 'TARPIT';
301 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
302 add_target_def 'TOS', qw(set-tos);
303 add_target_def 'TRACE';
304 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
305 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
307 add_match_def_x 'arp', '',
308 # ip
309 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
310 # mac
311 qw(source-mac! destination-mac!),
312 # --in-interface
313 qw(in-interface! interface:=in-interface if:=in-interface),
314 # --out-interface
315 qw(out-interface! outerface:=out-interface of:=out-interface),
316 # misc
317 qw(h-length=s opcode=s h-type=s proto-type=s),
318 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
320 add_match_def_x 'eb', '',
321 # protocol
322 qw(protocol! proto:=protocol),
323 # --in-interface
324 qw(in-interface! interface:=in-interface if:=in-interface),
325 # --out-interface
326 qw(out-interface! outerface:=out-interface of:=out-interface),
327 # logical interface
328 qw(logical-in! logical-out!),
329 # --source, --destination
330 qw(source! saddr:=source destination! daddr:=destination),
331 # 802.3
332 qw(802_3-sap! 802_3-type!),
333 # arp
334 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
335 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
336 # ip
337 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
338 # mark_m
339 qw(mark!),
340 # pkttype
341 qw(pkttype-type!),
342 # stp
343 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
344 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
345 qw(stp-hello-time! stp-forward-delay!),
346 # vlan
347 qw(vlan-id! vlan-prio! vlan-encap!),
348 # log
349 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
351 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
352 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
353 add_target_def_x 'eb', 'mark', qw(set-mark mark-target);
354 add_target_def_x 'eb', 'redirect', qw(redirect-target);
355 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
357 use vars qw(%builtin_keywords);
359 sub get_builtin_keywords($) {
360 my $domain_family = shift;
361 return {} unless defined $domain_family;
363 return {%{$builtin_keywords{$domain_family}}}
364 if exists $builtin_keywords{$domain_family};
366 return {} unless exists $match_defs{$domain_family};
367 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
368 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
370 $builtin_keywords{$domain_family} = \%keywords;
371 return {%keywords};
374 # parameter parser for ipt_multiport
375 sub multiport_params {
376 my $fw = shift;
378 # multiport only allows 15 ports at a time. For this
379 # reason, we do a little magic here: split the ports
380 # into portions of 15, and handle these portions as
381 # array elements
383 my $proto = $fw->{builtin}{protocol};
384 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
385 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
387 my $value = getvalues(undef, undef,
388 allow_negation => 1,
389 allow_array_negation => 1);
390 if (ref $value and ref $value eq 'ARRAY') {
391 my @value = @$value;
392 my @params;
394 while (@value) {
395 push @params, join(',', splice(@value, 0, 15));
398 return @params == 1
399 ? $params[0]
400 : \@params;
401 } else {
402 return join_value(',', $value);
406 # initialize stack: command line definitions
407 unshift @stack, {};
409 # Get command line stuff
410 if ($has_getopt) {
411 my ($opt_noexec, $opt_flush, $opt_lines, $opt_interactive,
412 $opt_verbose, $opt_debug,
413 $opt_help,
414 $opt_version, $opt_test, $opt_fast, $opt_shell,
415 $opt_domain);
417 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
418 'no_auto_abbrev');
420 sub opt_def {
421 my ($opt, $value) = @_;
422 die 'Invalid --def specification'
423 unless $value =~ /^\$?(\w+)=(.*)$/s;
424 my ($name, $unparsed_value) = ($1, $2);
425 my $tokens = tokenize_string($unparsed_value);
426 my $value = getvalues(\&next_array_token, $tokens);
427 die 'Extra tokens after --def'
428 if @$tokens > 0;
429 $stack[0]{vars}{$name} = $value;
432 local $SIG{__WARN__} = sub { die $_[0]; };
433 GetOptions('noexec|n' => \$opt_noexec,
434 'flush|F' => \$opt_flush,
435 'lines|l' => \$opt_lines,
436 'interactive|i' => \$opt_interactive,
437 'verbose|v' => \$opt_verbose,
438 'debug|d' => \$opt_debug,
439 'help|h' => \$opt_help,
440 'version|V' => \$opt_version,
441 test => \$opt_test,
442 remote => \$opt_test,
443 fast => \$opt_fast,
444 shell => \$opt_shell,
445 'domain=s' => \$opt_domain,
446 'def=s' => \&opt_def,
449 if (defined $opt_help) {
450 require Pod::Usage;
451 Pod::Usage::pod2usage(-exitstatus => 0);
454 if (defined $opt_version) {
455 printversion();
456 exit 0;
459 $option{'noexec'} = (defined $opt_noexec);
460 $option{flush} = defined $opt_flush;
461 $option{'lines'} = (defined $opt_lines);
462 $option{interactive} = (defined $opt_interactive);
463 $option{test} = (defined $opt_test);
465 if ($option{test}) {
466 $option{noexec} = 1;
467 $option{lines} = 1;
470 delete $option{interactive} if $option{noexec};
472 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
473 if $option{interactive} and not -t STDIN;
474 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
475 if $option{interactive} and not -t STDERR;
477 $option{fast} = 1 if defined $opt_fast;
479 if (defined $opt_shell) {
480 $option{$_} = 1 foreach qw(shell fast lines);
483 $option{domain} = $opt_domain if defined $opt_domain;
485 print STDERR "Warning: ignoring the obsolete --debug option\n"
486 if defined $opt_debug;
487 print STDERR "Warning: ignoring the obsolete --verbose option\n"
488 if defined $opt_verbose;
489 } else {
490 # tiny getopt emulation for microperl
491 my $filename;
492 foreach (@ARGV) {
493 if ($_ eq '--noexec' or $_ eq '-n') {
494 $option{noexec} = 1;
495 } elsif ($_ eq '--lines' or $_ eq '-l') {
496 $option{lines} = 1;
497 } elsif ($_ eq '--fast') {
498 $option{fast} = 1;
499 } elsif ($_ eq '--test') {
500 $option{test} = 1;
501 $option{noexec} = 1;
502 $option{lines} = 1;
503 } elsif ($_ eq '--shell') {
504 $option{$_} = 1 foreach qw(shell fast lines);
505 } elsif (/^-/) {
506 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
507 exit 1;
508 } else {
509 $filename = $_;
512 undef @ARGV;
513 push @ARGV, $filename;
516 unless (@ARGV == 1) {
517 require Pod::Usage;
518 Pod::Usage::pod2usage(-exitstatus => 1);
521 if ($has_strict) {
522 open LINES, ">&STDOUT" if $option{lines};
523 open STDOUT, ">&STDERR" if $option{shell};
524 } else {
525 # microperl can't redirect file handles
526 *LINES = *STDOUT;
528 if ($option{fast} and not $option{noexec}) {
529 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
530 exit 1
534 unshift @stack, {};
535 open_script($ARGV[0]);
537 # parse all input recursively
538 enter(0);
539 die unless @stack == 2;
541 # check consistency
542 check();
544 # execute all generated rules
545 my $status;
547 foreach my $cmd (@pre_hooks) {
548 print LINES "$cmd\n" if $option{lines};
549 system($cmd) unless $option{noexec};
552 while (my ($domain, $domain_info) = each %domains) {
553 next unless $domain_info->{enabled};
554 my $s = $option{fast} &&
555 defined $domain_info->{tools}{'tables-restore'}
556 ? execute_fast($domain, $domain_info)
557 : execute_slow($domain, $domain_info);
558 $status = $s if defined $s;
561 foreach my $cmd (@post_hooks) {
562 print "$cmd\n" if $option{lines};
563 system($cmd) unless $option{noexec};
566 if (defined $status) {
567 rollback();
568 exit $status;
571 # ask user, and rollback if there is no confirmation
573 confirm_rules() or rollback() if $option{interactive};
575 exit 0;
577 # end of program execution!
580 # funcs
582 sub printversion {
583 print "ferm $VERSION\n";
584 print "Copyright (C) 2001-2007 Auke Kok, Max Kellermann\n";
585 print "This program is free software released under GPLv2.\n";
586 print "See the included COPYING file for license details.\n";
590 sub mydie {
591 print STDERR @_;
592 print STDERR "\n";
593 exit 1;
597 sub error {
598 # returns a nice formatted error message, showing the
599 # location of the error.
600 my $tabs = 0;
601 my @lines;
602 my $l = 0;
603 my @words = map { @$_ } @{$script->{past_tokens}};
605 for my $w ( 0 .. $#words ) {
606 if ($words[$w] eq "\x29")
607 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
608 if ($words[$w] eq "\x28")
609 { $l++ ; $lines[$l] = " " x $tabs++ ;};
610 if ($words[$w] eq "\x7d")
611 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
612 if ($words[$w] eq "\x7b")
613 { $l++ ; $lines[$l] = " " x $tabs++ ;};
614 if ( $l > $#lines ) { $lines[$l] = "" };
615 $lines[$l] .= $words[$w] . " ";
616 if ($words[$w] eq "\x28")
617 { $l++ ; $lines[$l] = " " x $tabs ;};
618 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
619 { $l++ ; $lines[$l] = " " x $tabs ;};
620 if ($words[$w] eq "\x7b")
621 { $l++ ; $lines[$l] = " " x $tabs ;};
622 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
623 { $l++ ; $lines[$l] = " " x $tabs ;};
624 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
625 { $l++ ; $lines[$l] = " " x $tabs ;}
626 if ($words[$w-1] eq "option")
627 { $l++ ; $lines[$l] = " " x $tabs ;}
629 my $start = $#lines - 4;
630 if ($start < 0) { $start = 0 } ;
631 print STDERR "Error in $script->{filename} line $script->{line}:\n";
632 for $l ( $start .. $#lines)
633 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
634 print STDERR "<--\n";
635 mydie(@_);
638 # print a warning message about code from an input file
639 sub warning {
640 print STDERR "Warning in $script->{filename} line $script->{line}: "
641 . (shift) . "\n";
644 sub find_tool($) {
645 my $name = shift;
646 return $name if $option{test};
647 for my $path ('/sbin', split ':', $ENV{PATH}) {
648 my $ret = "$path/$name";
649 return $ret if -x $ret;
651 die "$name not found in PATH\n";
654 sub initialize_domain {
655 my $domain = shift;
657 return if exists $domains{$domain}{initialized};
659 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
661 my @tools = qw(tables);
662 push @tools, qw(tables-save tables-restore)
663 if $domain =~ /^ip6?$/;
665 # determine the location of this domain's tools
666 foreach my $tool (@tools) {
667 $domains{$domain}{tools}{$tool} = find_tool("${domain}${tool}");
670 # make tables-save tell us about the state of this domain
671 # (which tables and chains do exist?), also remember the old
672 # save data which may be used later by the rollback function
673 local *SAVE;
674 if (!$option{test} &&
675 exists $domains{$domain}{tools}{'tables-save'} &&
676 open(SAVE, "$domains{$domain}{tools}{'tables-save'}|")) {
677 my $save = '';
679 my $table_info;
680 while (<SAVE>) {
681 $save .= $_;
683 if (/^\*(\w+)/) {
684 my $table = $1;
685 $table_info = $domains{$domain}{tables}{$table} ||= {};
686 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
687 and $2 ne '-') {
688 $table_info->{chains}{$1}{builtin} = 1;
689 $table_info->{has_builtin} = 1;
693 # for rollback
694 $domains{$domain}{previous} = $save;
697 $domains{$domain}{initialized} = 1;
700 # split the an input string into words and delete comments
701 sub tokenize_string($) {
702 my $string = shift;
704 my @ret;
706 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
707 last if $word eq '#';
708 push @ret, $word;
711 return \@ret;
714 # shift an array; helper function to be passed to &getvar / &getvalues
715 sub next_array_token {
716 my $array = shift;
717 shift @$array;
720 # read some more tokens from the input file into a buffer
721 sub prepare_tokens() {
722 my $tokens = $script->{tokens};
723 while (@$tokens == 0) {
724 my $handle = $script->{handle};
725 my $line = <$handle>;
726 return unless defined $line;
728 $script->{line} ++;
730 # the next parser stage eats this
731 push @$tokens, @{tokenize_string($line)};
734 return 1;
737 # open a ferm sub script
738 sub open_script($) {
739 my $filename = shift;
741 for (my $s = $script; defined $s; $s = $s->{parent}) {
742 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
743 if $s->{filename} eq $filename;
746 local *FILE;
747 open FILE, "<$filename"
748 or mydie("Failed to open $filename: $!");
749 my $handle = *FILE;
751 $script = { filename => $filename,
752 handle => $handle,
753 line => 0,
754 past_tokens => [],
755 tokens => [],
756 parent => $script,
759 return $script;
762 # collect script filenames which are being included
763 sub collect_filenames(@) {
764 my @ret;
766 # determine the current script's parent directory for relative
767 # file names
768 die unless defined $script;
769 my $parent_dir = $script->{filename} =~ m,^(.*/),
770 ? $1 : './';
772 foreach my $pathname (@_) {
773 # non-absolute file names are relative to the parent script's
774 # file name
775 $pathname = $parent_dir . $pathname
776 unless $pathname =~ m,^/,;
778 if ($pathname =~ m,/$,) {
779 # include all regular files in a directory
781 error("'$pathname' is not a directory")
782 unless -d $pathname;
784 local *DIR;
785 opendir DIR, $pathname
786 or error("Failed to open directory '$pathname': $!");
787 my @names = readdir DIR;
788 closedir DIR;
790 # sort those names for a well-defined order
791 foreach my $name (sort { $a cmp $b } @names) {
792 # don't include hidden and backup files
793 next if /^\.|~$/;
795 my $filename = $pathname . $name;
796 push @ret, $filename
797 if -f $filename;
799 } elsif ($pathname =~ m,\|$,) {
800 # run a program and use its output
801 push @ret, $pathname;
802 } elsif ($pathname =~ m,^\|,) {
803 error('This kind of pipe is not allowed');
804 } else {
805 # include a regular file
807 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
808 if -d $pathname;
809 error("'$pathname' is not a file")
810 unless -f $pathname;
812 push @ret, $pathname;
816 return @ret;
819 # peek a token from the queue, but don't remove it
820 sub peek_token() {
821 return unless prepare_tokens();
822 return $script->{tokens}[0];
825 # get a token from the queue
826 sub next_token() {
827 return unless prepare_tokens();
828 my $token = shift @{$script->{tokens}};
830 # update $script->{past_tokens}
831 my $past_tokens = $script->{past_tokens};
833 if (@$past_tokens > 0) {
834 my $prev_token = $past_tokens->[-1][-1];
835 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
836 if $prev_token eq ';';
837 pop @$past_tokens
838 if $prev_token eq '}';
841 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
842 push @{$past_tokens->[-1]}, $token;
844 # return
845 return $token;
848 sub expect_token($;$) {
849 my $expect = shift;
850 my $msg = shift;
851 my $token = next_token();
852 error($msg || "'$expect' expected")
853 unless defined $token and $token eq $expect;
856 # require that another token exists, and that it's not a "special"
857 # token, e.g. ";" and "{"
858 sub require_next_token {
859 my $code = shift || \&next_token;
861 my $token = &$code(@_);
863 error('unexpected end of file')
864 unless defined $token;
866 error("'$token' not allowed here")
867 if $token =~ /^[;{}]$/;
869 return $token;
872 # return the value of a variable
873 sub variable_value($) {
874 my $name = shift;
876 foreach (@stack) {
877 return $_->{vars}{$name}
878 if exists $_->{vars}{$name};
881 return $stack[0]{auto}{$name}
882 if exists $stack[0]{auto}{$name};
884 return;
887 # determine the value of a variable, die if the value is an array
888 sub string_variable_value($) {
889 my $name = shift;
890 my $value = variable_value($name);
892 error("variable '$name' must be a string, is an array")
893 if ref $value;
895 return $value;
898 # similar to the built-in "join" function, but also handle negated
899 # values in a special way
900 sub join_value($$) {
901 my ($expr, $value) = @_;
903 unless (ref $value) {
904 return $value;
905 } elsif (ref $value eq 'ARRAY') {
906 return join($expr, @$value);
907 } elsif (ref $value eq 'negated') {
908 # bless'negated' is a special marker for negated values
909 $value = join_value($expr, $value->[0]);
910 return bless [ $value ], 'negated';
911 } else {
912 die;
916 # returns the next parameter, which may either be a scalar or an array
917 sub getvalues {
918 my ($code, $param) = (shift, shift);
919 my %options = @_;
921 my $token = require_next_token($code, $param);
923 if ($token eq '(') {
924 # read an array until ")"
925 my @wordlist;
927 for (;;) {
928 $token = getvalues($code, $param,
929 parenthesis_allowed => 1,
930 comma_allowed => 1);
932 unless (ref $token) {
933 last if $token eq ')';
935 if ($token eq ',') {
936 error('Comma is not allowed within arrays, please use only a space');
937 next;
940 push @wordlist, $token;
941 } elsif (ref $token eq 'ARRAY') {
942 push @wordlist, @$token;
943 } else {
944 error('unknown toke type');
948 error('empty array not allowed here')
949 unless @wordlist or not $options{non_empty};
951 return @wordlist == 1
952 ? $wordlist[0]
953 : \@wordlist;
954 } elsif ($token =~ /^\`(.*)\`$/s) {
955 # execute a shell command, insert output
956 my $command = $1;
957 my $output = `$command`;
958 unless ($? == 0) {
959 if ($? == -1) {
960 error("failed to execute: $!");
961 } elsif ($? & 0x7f) {
962 error("child died with signal " . ($? & 0x7f));
963 } elsif ($? >> 8) {
964 error("child exited with status " . ($? >> 8));
968 # remove comments
969 $output =~ s/#.*//mg;
971 # tokenize
972 my @tokens = grep { length } split /\s+/s, $output;
974 my @values;
975 while (@tokens) {
976 my $value = getvalues(\&next_array_token, \@tokens);
977 push @values, to_array($value);
980 # and recurse
981 return @values == 1
982 ? $values[0]
983 : \@values;
984 } elsif ($token =~ /^\'(.*)\'$/s) {
985 # single quotes: a string
986 return $1;
987 } elsif ($token =~ /^\"(.*)\"$/s) {
988 # double quotes: a string with escapes
989 $token = $1;
990 $token =~ s,\$(\w+),string_variable_value($1),eg;
991 return $token;
992 } elsif ($token eq '!') {
993 error('negation is not allowed here')
994 unless $options{allow_negation};
996 $token = getvalues($code, $param);
998 error('it is not possible to negate an array')
999 if ref $token and not $options{allow_array_negation};
1001 return bless [ $token ], 'negated';
1002 } elsif ($token eq ',') {
1003 return $token
1004 if $options{comma_allowed};
1006 error('comma is not allowed here');
1007 } elsif ($token eq '=') {
1008 error('equals operator ("=") is not allowed here');
1009 } elsif ($token eq '$') {
1010 my $name = require_next_token($code, $param);
1011 error('variable name expected - if you want to concatenate strings, try using double quotes')
1012 unless $name =~ /^\w+$/;
1014 my $value = variable_value($name);
1016 error("no such variable: \$$name")
1017 unless defined $value;
1019 return $value;
1020 } elsif ($token eq '&') {
1021 error("function calls are not allowed as keyword parameter");
1022 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1023 error('Syntax error');
1024 } elsif ($token =~ /^@/) {
1025 if ($token eq '@resolve') {
1026 my @params = get_function_params();
1027 error('Usage: @resolve((hostname ...))')
1028 unless @params == 1;
1029 eval { require Net::DNS; };
1030 error('For the @resolve() function, you need the Perl library Net::DNS')
1031 if $@;
1032 my $type = 'A';
1033 my $resolver = new Net::DNS::Resolver;
1034 my @result;
1035 foreach my $hostname (to_array($params[0])) {
1036 my $query = $resolver->search($hostname, $type);
1037 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1038 unless $query;
1039 foreach my $rr ($query->answer) {
1040 next unless $rr->type eq $type;
1041 push @result, $rr->address;
1044 return \@result;
1045 } else {
1046 error("unknown ferm built-in function");
1048 } else {
1049 return $token;
1053 # returns the next parameter, but only allow a scalar
1054 sub getvar {
1055 my $token = getvalues(@_);
1057 error('array not allowed here')
1058 if ref $token and ref $token eq 'ARRAY';
1060 return $token;
1063 sub get_function_params(%) {
1064 expect_token('(', 'function name must be followed by "()"');
1066 my $token = peek_token();
1067 if ($token eq ')') {
1068 require_next_token;
1069 return;
1072 my @params;
1074 while (1) {
1075 if (@params > 0) {
1076 $token = require_next_token();
1077 last
1078 if $token eq ')';
1080 error('"," expected')
1081 unless $token eq ',';
1084 push @params, getvalues(undef, undef, @_);
1087 return @params;
1090 # collect all tokens in a flat array reference until the end of the
1091 # command is reached
1092 sub collect_tokens() {
1093 my @level;
1094 my @tokens;
1096 while (1) {
1097 my $keyword = next_token();
1098 error('unexpected end of file within function/variable declaration')
1099 unless defined $keyword;
1101 if ($keyword =~ /^[\{\(]$/) {
1102 push @level, $keyword;
1103 } elsif ($keyword =~ /^[\}\)]$/) {
1104 my $expected = $keyword;
1105 $expected =~ tr/\}\)/\{\(/;
1106 my $opener = pop @level;
1107 error("unmatched '$keyword'")
1108 unless defined $opener and $opener eq $expected;
1109 } elsif ($keyword eq ';' and @level == 0) {
1110 last;
1113 push @tokens, $keyword;
1115 last
1116 if $keyword eq '}' and @level == 0;
1119 return \@tokens;
1123 # returns the specified value as an array. dereference arrayrefs
1124 sub to_array($) {
1125 my $value = shift;
1126 die unless wantarray;
1127 die if @_;
1128 unless (ref $value) {
1129 return $value;
1130 } elsif (ref $value eq 'ARRAY') {
1131 return @$value;
1132 } else {
1133 die;
1137 # evaluate the specified value as bool
1138 sub eval_bool($) {
1139 my $value = shift;
1140 die if wantarray;
1141 die if @_;
1142 unless (ref $value) {
1143 return $value;
1144 } elsif (ref $value eq 'ARRAY') {
1145 return @$value > 0;
1146 } else {
1147 die;
1151 sub is_netfilter_core_target($) {
1152 my $target = shift;
1153 die unless defined $target and length $target;
1155 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1158 sub is_netfilter_module_target($$) {
1159 my ($domain_family, $target) = @_;
1160 die unless defined $target and length $target;
1162 return defined $domain_family &&
1163 exists $target_defs{$domain_family} &&
1164 exists $target_defs{$domain_family}{$target};
1167 sub is_netfilter_builtin_chain($$) {
1168 my ($table, $chain) = @_;
1170 return grep { $_ eq $chain }
1171 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1174 sub netfilter_canonical_protocol($) {
1175 my $proto = shift;
1176 return 'icmpv6'
1177 if $proto eq 'ipv6-icmp';
1178 return 'mh'
1179 if $proto eq 'ipv6-mh';
1180 return $proto;
1183 sub netfilter_protocol_module($) {
1184 my $proto = shift;
1185 return unless defined $proto;
1186 return 'icmp6'
1187 if $proto eq 'icmpv6';
1188 return $proto;
1191 # escape the string in a way safe for the shell
1192 sub shell_escape($) {
1193 my $token = shift;
1195 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1197 if ($option{fast}) {
1198 # iptables-save/iptables-restore are quite buggy concerning
1199 # escaping and special characters... we're trying our best
1200 # here
1202 $token =~ s,",',g;
1203 $token = '"' . $token . '"'
1204 if $token =~ /[\s\'\\;&]/s;
1205 } else {
1206 return $token
1207 if $token =~ /^\`.*\`$/;
1208 $token =~ s/'/\\'/g;
1209 $token = '\'' . $token . '\''
1210 if $token =~ /[\s\"\\;<>&|]/s;
1213 return $token;
1216 # append an option to the shell command line, using information from
1217 # the module definition (see %match_defs etc.)
1218 sub shell_append_option($$$) {
1219 my ($ref, $keyword, $value) = @_;
1221 if (ref $value) {
1222 if (ref $value eq 'negated') {
1223 $value = $value->[0];
1224 $keyword .= ' !';
1225 } elsif (ref $value eq 'pre_negated') {
1226 $value = $value->[0];
1227 $$ref .= ' !';
1231 unless (defined $value) {
1232 $$ref .= " --$keyword";
1233 } elsif (ref $value) {
1234 if (ref $value eq 'params') {
1235 $$ref .= " --$keyword ";
1236 $$ref .= join(' ', map { shell_escape($_) } @$value);
1237 } elsif (ref $value eq 'multi') {
1238 foreach (@$value) {
1239 $$ref .= " --$keyword " . shell_escape($_);
1241 } else {
1242 die;
1244 } else {
1245 $$ref .= " --$keyword " . shell_escape($value);
1249 # convert an internal rule structure into an iptables call
1250 sub tables($) {
1251 my $rule = shift;
1253 my $domain = $rule->{domain};
1254 my $domain_info = $domains{$domain};
1255 $domain_info->{enabled} = 1;
1256 my $domain_family = $rule->{domain_family};
1258 my $table = $rule->{table};
1259 my $table_info = $domain_info->{tables}{$table} ||= {};
1261 my $chain = $rule->{chain};
1262 my $chain_info = $table_info->{chains}{$chain} ||= {};
1263 my $chain_rules = $chain_info->{rules} ||= [];
1265 return if $option{flush};
1267 my $action = $rule->{action};
1269 # mark this chain as "non-empty" because we will add stuff to
1270 # it now; this flag is later used to check if a custom chain
1271 # referenced by "jump" was actually defined
1272 $chain_info->{non_empty} = 1;
1274 # return if this is a declaration-only rule
1275 return
1276 unless $rule->{has_rule};
1278 my $rr = '';
1280 # general iptables options
1282 while (my ($keyword, $value) = each %{$rule->{builtin}}) {
1283 shell_append_option(\$rr, $keyword, $value);
1287 # match module options
1290 my %modules;
1292 if (defined $rule->{builtin}{protocol}) {
1293 my $proto = $rule->{builtin}{protocol};
1295 # special case: --dport and --sport for TCP/UDP
1296 if ($domain_family eq 'ip' and
1297 (exists $rule->{dport} or exists $rule->{sport}) and
1298 $proto =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
1299 unless (exists $modules{$proto}) {
1300 $rr .= " -m $proto";
1301 $modules{$proto} = 1;
1304 shell_append_option(\$rr, 'dport', $rule->{dport})
1305 if exists $rule->{dport};
1306 shell_append_option(\$rr, 'sport', $rule->{sport})
1307 if exists $rule->{sport};
1311 # modules stored in %match_defs
1313 foreach my $match (@{$rule->{match}}) {
1314 my $module_name = $match->{name};
1315 unless (exists $modules{$module_name}) {
1316 $rr .= " -m $module_name";
1317 $modules{$module_name} = 1;
1320 while (my ($keyword, $value) = each %{$match->{options}}) {
1321 shell_append_option(\$rr, $keyword, $value);
1326 # target options
1329 if ($action->{type} eq 'jump') {
1330 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1331 $rr .= " -j " . $action->{chain};
1332 } elsif ($action->{type} eq 'goto') {
1333 $table_info->{chains}{$action->{chain}}{rules} ||= [];
1334 $rr .= " -g " . $action->{chain};
1335 } elsif ($action->{type} eq 'target') {
1336 $rr .= " -j " . $action->{target};
1338 # targets stored in %target_defs
1340 while (my ($keyword, $value) = each %{$rule->{target_options}}) {
1341 shell_append_option(\$rr, $keyword, $value);
1343 } elsif ($action->{type} ne 'nop') {
1344 die;
1347 # this line is done
1348 push @$chain_rules, { rule => $rr,
1349 script => $rule->{script},
1353 sub transform_rule($) {
1354 my $rule = shift;
1356 $rule->{builtin}{protocol} = 'icmpv6'
1357 if $rule->{domain} eq 'ip6' and $rule->{builtin}{protocol} eq 'icmp';
1360 sub printrule($) {
1361 my $rule = shift;
1363 transform_rule($rule);
1365 # prints all rules in a hash
1366 tables($rule);
1370 sub check_unfold(\@$$) {
1371 my ($unfold, $parent, $key) = @_;
1373 return unless ref $parent->{$key} and
1374 ref $parent->{$key} eq 'ARRAY';
1376 push @$unfold, $parent, $key, $parent->{$key};
1379 # convert a bunch of internal rule structures in iptables calls,
1380 # unfold arrays during that
1381 sub mkrules($) {
1382 # compile the list hashes into rules
1383 my $fw = shift;
1385 my @unfold;
1387 foreach my $key (qw(domain table chain)) {
1388 check_unfold(@unfold, $fw, $key);
1391 foreach my $key (keys %{$fw->{builtin}}) {
1392 check_unfold(@unfold, $fw->{builtin}, $key);
1395 foreach my $match (@{$fw->{match}}) {
1396 while (my ($key, $value) = each %{$match->{options}}) {
1397 check_unfold(@unfold, $match->{options}, $key);
1401 check_unfold(@unfold, $fw, 'sport');
1402 check_unfold(@unfold, $fw, 'dport');
1404 if (@unfold == 0) {
1405 printrule($fw);
1406 return;
1409 sub dofr {
1410 my $fw = shift;
1411 my ($parent, $key, $values) = (shift, shift, shift);
1413 foreach my $value (@$values) {
1414 $parent->{$key} = $value;
1416 if (@_) {
1417 dofr($fw, @_);
1418 } else {
1419 printrule($fw);
1424 dofr($fw, @unfold);
1427 sub filter_domains($) {
1428 my $domains = shift;
1429 my $result = [];
1431 foreach my $domain (to_array $domains) {
1432 next if exists $option{domain}
1433 and $domain ne $option{domain};
1435 eval {
1436 initialize_domain($domain);
1438 error($@) if $@;
1440 push @$result, $domain;
1443 return @$result == 1 ? $result->[0] : $result;
1446 # parse a keyword from a module definition
1447 sub parse_keyword($$$$) {
1448 my ($current, $def, $keyword, $negated_ref) = @_;
1450 my $params = $def->{params};
1452 my $value;
1454 my $negated;
1455 if ($$negated_ref && exists $def->{pre_negation}) {
1456 $negated = 1;
1457 undef $$negated_ref;
1460 unless (defined $params) {
1461 undef $value;
1462 } elsif (ref $params && ref $params eq 'CODE') {
1463 $value = &$params($current);
1464 } elsif ($params eq 'm') {
1465 $value = bless [ to_array getvalues() ], 'multi';
1466 } elsif ($params =~ /^[a-z]/) {
1467 if (exists $def->{negation} and not $negated) {
1468 my $token = peek_token();
1469 if ($token eq '!') {
1470 require_next_token;
1471 $negated = 1;
1475 my @params;
1476 foreach my $p (split(//, $params)) {
1477 if ($p eq 's') {
1478 push @params, getvar();
1479 } elsif ($p eq 'c') {
1480 my @v = to_array getvalues(undef, undef,
1481 non_empty => 1);
1482 push @params, join(',', @v);
1483 } else {
1484 die;
1488 $value = @params == 1
1489 ? $params[0]
1490 : bless \@params, 'params';
1491 } elsif ($params == 1) {
1492 if (exists $def->{negation} and not $negated) {
1493 my $token = peek_token();
1494 if ($token eq '!') {
1495 require_next_token;
1496 $negated = 1;
1500 $value = getvalues();
1502 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1503 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1504 } else {
1505 if (exists $def->{negation} and not $negated) {
1506 my $token = peek_token();
1507 if ($token eq '!') {
1508 require_next_token;
1509 $negated = 1;
1513 $value = bless [ map {
1514 getvar()
1515 } (1..$params) ], 'params';
1518 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1519 if $negated;
1521 return $value;
1524 # parse options of a module
1525 sub parse_option($$$$$) {
1526 my ($def, $current, $store, $keyword, $negated_ref) = @_;
1528 while (exists $def->{alias}) {
1529 ($keyword, $def) = @{$def->{alias}};
1530 die unless defined $def;
1533 $store->{$keyword}
1534 = parse_keyword($current, $def,
1535 $keyword, $negated_ref);
1536 $current->{has_rule} = 1;
1537 return 1;
1540 # parse options for a protocol module definition
1541 sub parse_protocol_options($$$$) {
1542 my ($current, $proto, $keyword, $negated_ref) = @_;
1544 my $domain_family = $current->{'domain_family'};
1545 my $proto_defs = $proto_defs{$domain_family};
1546 return unless defined $proto_defs;
1548 my $proto_def = $proto_defs->{$proto};
1549 return unless defined $proto_def and
1550 exists $proto_def->{keywords}{$keyword};
1552 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1553 my $module = { name => $module_name,
1554 options => {},
1555 defs => $proto_def,
1557 push @{$current->{match}}, $module;
1559 return parse_option($proto_def->{keywords}{$keyword},
1560 $current, $module->{options},
1561 $keyword, $negated_ref);
1564 sub copy_on_write($$) {
1565 my ($rule, $key) = @_;
1566 return unless exists $rule->{cow}{$key};
1567 $rule->{$key} = {%{$rule->{$key}}};
1568 delete $rule->{cow}{$key};
1571 sub clone_match($) {
1572 my $match = shift;
1573 return { name => $match->{name},
1574 options => { %{$match->{options}} },
1575 defs => $match->{defs},
1579 sub new_level(\%$) {
1580 my ($current, $prev) = @_;
1582 %$current = ();
1583 if (defined $prev) {
1584 # copy data from previous level
1585 $current->{cow} = { keywords => 1, };
1586 $current->{keywords} = $prev->{keywords};
1587 $current->{builtin} = { %{$prev->{builtin}} };
1588 $current->{match} = [ map { clone_match($_) } @{$prev->{match}} ];
1589 $current->{action} = { %{$prev->{action}} };
1590 foreach my $key (qw(domain domain_family table chain sport dport)) {
1591 $current->{$key} = $prev->{$key}
1592 if exists $prev->{$key};
1594 } else {
1595 $current->{cow} = {};
1596 $current->{keywords} = {};
1597 $current->{builtin} = {};
1598 $current->{match} = [];
1599 $current->{action} = {};
1603 sub rule_defined(\%) {
1604 my $rule = shift;
1605 return defined($rule->{domain}) or
1606 keys(%{$rule->{builtin}}) > 0 or
1607 keys(%{$rule->{match}}) > 0 or
1608 keys(%{$rule->{action}}) > 0;
1611 # the main parser loop: read tokens, convert them into internal rule
1612 # structures
1613 sub enter($$) {
1614 my $lev = shift; # current recursion depth
1615 my $prev = shift; # previous rule hash
1617 # enter is the core of the firewall setup, it is a
1618 # simple parser program that recognizes keywords and
1619 # retreives parameters to set up the kernel routing
1620 # chains
1622 my $base_level = $script->{base_level} || 0;
1623 die if $base_level > $lev;
1625 my %current;
1626 new_level(%current, $prev);
1628 # read keywords 1 by 1 and dump into parser
1629 while (defined (my $keyword = next_token())) {
1630 # check if the current rule should be negated
1631 my $negated = $keyword eq '!';
1632 if ($negated) {
1633 # negation. get the next word which contains the 'real'
1634 # rule
1635 $keyword = getvar();
1637 error('unexpected end of file after negation')
1638 unless defined $keyword;
1641 # the core: parse all data
1642 for ($keyword)
1644 # deprecated keyword?
1645 if (exists $deprecated_keywords{$keyword}) {
1646 my $new_keyword = $deprecated_keywords{$keyword};
1647 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1648 $keyword = $new_keyword;
1651 # effectuation operator
1652 if ($keyword eq ';') {
1653 if ($current{has_rule} and not $current{action}{type}) {
1654 # something is wrong when a rule was specifiedd,
1655 # but no action
1656 error('No action defined; did you mean "NOP"?');
1659 error('No chain defined') unless defined $current{chain};
1661 $current{script} = { filename => $script->{filename},
1662 line => $script->{line},
1665 mkrules(\%current);
1667 # and clean up variables set in this level
1668 new_level(%current, $prev);
1670 next;
1673 # conditional expression
1674 if ($keyword eq '@if') {
1675 unless (eval_bool(getvalues)) {
1676 collect_tokens;
1677 my $token = peek_token();
1678 require_next_token() if $token and $token eq '@else';
1681 next;
1684 if ($keyword eq '@else') {
1685 # hack: if this "else" has not been eaten by the "if"
1686 # handler above, we believe it came from an if clause
1687 # which evaluated "true" - remove the "else" part now.
1688 collect_tokens;
1689 next;
1692 # hooks for custom shell commands
1693 if ($keyword eq 'hook') {
1694 error('"hook" must be the first token in a command')
1695 if rule_defined(%current);
1697 my $position = getvar();
1698 my $hooks;
1699 if ($position eq 'pre') {
1700 $hooks = \@pre_hooks;
1701 } elsif ($position eq 'post') {
1702 $hooks = \@post_hooks;
1703 } else {
1704 error("Invalid hook position: '$position'");
1707 push @$hooks, getvar();
1709 expect_token(';');
1710 next;
1713 # recursing operators
1714 if ($keyword eq '{') {
1715 # push stack
1716 my $old_stack_depth = @stack;
1718 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1720 # recurse
1721 enter($lev + 1, \%current);
1723 # pop stack
1724 shift @stack;
1725 die unless @stack == $old_stack_depth;
1727 # after a block, the command is finished, clear this
1728 # level
1729 new_level(%current, $prev);
1731 next;
1734 if ($keyword eq '}') {
1735 error('Unmatched "}"')
1736 if $lev <= $base_level;
1738 # consistency check: check if they havn't forgotten
1739 # the ';' before the last statement
1740 error('Missing semicolon before "}"')
1741 if $current{has_rule};
1743 # and exit
1744 return;
1747 # include another file
1748 if ($keyword eq '@include' or $keyword eq 'include') {
1749 my @files = collect_filenames to_array getvalues;
1750 $keyword = next_token;
1751 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1752 unless defined $keyword and $keyword eq ';';
1754 foreach my $filename (@files) {
1755 # save old script, open new script
1756 my $old_script = $script;
1757 open_script($filename);
1758 $script->{base_level} = $lev + 1;
1760 # push stack
1761 my $old_stack_depth = @stack;
1763 my $stack = {};
1765 if (@stack > 0) {
1766 # include files may set variables for their parent
1767 $stack->{vars} = ($stack[0]{vars} ||= {});
1768 $stack->{functions} = ($stack[0]{functions} ||= {});
1769 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1772 unshift @stack, $stack;
1774 # parse the script
1775 enter($lev + 1, \%current);
1777 # pop stack
1778 shift @stack;
1779 die unless @stack == $old_stack_depth;
1781 # restore old script
1782 $script = $old_script;
1785 next;
1788 # definition of a variable or function
1789 if ($keyword eq '@def' or $keyword eq 'def') {
1790 error('"def" must be the first token in a command')
1791 if $current{has_rule};
1793 my $type = require_next_token();
1794 if ($type eq '$') {
1795 my $name = require_next_token();
1796 error('invalid variable name')
1797 unless $name =~ /^\w+$/;
1799 expect_token('=');
1801 my $value = getvalues(undef, undef, allow_negation => 1);
1803 expect_token(';');
1805 $stack[0]{vars}{$name} = $value
1806 unless exists $stack[-1]{vars}{$name};
1807 } elsif ($type eq '&') {
1808 my $name = require_next_token();
1809 error('invalid function name')
1810 unless $name =~ /^\w+$/;
1812 expect_token('(', 'function parameter list or "()" expected');
1814 my @params;
1815 while (1) {
1816 my $token = require_next_token();
1817 last if $token eq ')';
1819 if (@params > 0) {
1820 error('"," expected')
1821 unless $token eq ',';
1823 $token = require_next_token();
1826 error('"$" and parameter name expected')
1827 unless $token eq '$';
1829 $token = require_next_token();
1830 error('invalid function parameter name')
1831 unless $token =~ /^\w+$/;
1833 push @params, $token;
1836 my %function;
1838 $function{params} = \@params;
1840 expect_token('=');
1842 my $tokens = collect_tokens();
1843 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1844 $function{tokens} = $tokens;
1846 $stack[0]{functions}{$name} = \%function
1847 unless exists $stack[-1]{functions}{$name};
1848 } else {
1849 error('"$" (variable) or "&" (function) expected');
1852 next;
1855 # def references
1856 if ($keyword eq '$') {
1857 error('variable references are only allowed as keyword parameter');
1860 if ($keyword eq '&') {
1861 my $name = require_next_token;
1862 error('function name expected')
1863 unless $name =~ /^\w+$/;
1865 my $function;
1866 foreach (@stack) {
1867 $function = $_->{functions}{$name};
1868 last if defined $function;
1870 error("no such function: \&$name")
1871 unless defined $function;
1873 my $paramdef = $function->{params};
1874 die unless defined $paramdef;
1876 my @params = get_function_params(allow_negation => 1);
1878 error("Wrong number of parameters for function '\&$name': "
1879 . @$paramdef . " expected, " . @params . " given")
1880 unless @params == @$paramdef;
1882 my %vars;
1883 for (my $i = 0; $i < @params; $i++) {
1884 $vars{$paramdef->[$i]} = $params[$i];
1887 if ($function->{block}) {
1888 # block {} always ends the current rule, so if the
1889 # function contains a block, we have to require
1890 # the calling rule also ends here
1891 expect_token(';');
1894 my @tokens = @{$function->{tokens}};
1895 for (my $i = 0; $i < @tokens; $i++) {
1896 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1897 exists $vars{$tokens[$i + 1]}) {
1898 my @value = to_array($vars{$tokens[$i + 1]});
1899 @value = ('(', @value, ')')
1900 unless @tokens == 1;
1901 splice(@tokens, $i, 2, @value);
1902 $i += @value - 2;
1903 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1904 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1908 unshift @{$script->{tokens}}, @tokens;
1910 next;
1913 # where to put the rule?
1914 if ($keyword eq 'domain') {
1915 error('Domain is already specified')
1916 if exists $current{domain};
1918 my $domain = getvalues();
1919 my $filtered_domain = filter_domains($domain);
1920 my $domain_family;
1921 unless (ref $domain) {
1922 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1923 } elsif (@$domain == 0) {
1924 $domain_family = 'none';
1925 } elsif (grep { not /^ip6?$/s } @$domain) {
1926 error('Cannot combine non-IP domains');
1927 } else {
1928 $domain_family = 'ip';
1930 $current{domain_family} = $domain_family;
1931 $current{keywords} = get_builtin_keywords($domain_family);
1932 delete $current{cow}{keywords};
1934 $current{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1936 next;
1939 if ($keyword eq 'table') {
1940 error('Table is already specified')
1941 if exists $current{table};
1942 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1944 unless (exists $current{domain}) {
1945 $current{domain} = filter_domains('ip');
1946 $current{domain_family} = 'ip';
1947 $current{keywords} = get_builtin_keywords('ip');
1948 delete $current{cow}{keywords};
1951 next;
1954 if ($keyword eq 'chain') {
1955 error('Chain is already specified')
1956 if exists $current{chain};
1957 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1959 # ferm 1.1 allowed lower case built-in chain names
1960 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1961 error('Please write built-in chain names in upper case')
1962 if /^(?:input|forward|output|prerouting|postrouting)$/;
1965 unless (exists $current{domain}) {
1966 $current{domain} = filter_domains('ip');
1967 $current{domain_family} = 'ip';
1968 $current{keywords} = get_builtin_keywords('ip');
1969 delete $current{cow}{keywords};
1972 $current{table} = 'filter'
1973 unless exists $current{table};
1975 next;
1978 error('Chain must be specified')
1979 unless exists $current{chain};
1981 # policy for built-in chain
1982 if ($keyword eq 'policy') {
1983 error('Cannot specify matches for policy')
1984 if $current{has_rule};
1986 my $policy = getvar();
1987 error("Invalid policy target: $policy")
1988 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1990 expect_token(';');
1992 foreach my $domain (to_array $current{domain}) {
1993 foreach my $table (to_array $current{table}) {
1994 foreach my $chain (to_array $current{chain}) {
1995 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
2000 new_level(%current, $prev);
2001 next;
2004 # create a subchain
2005 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2006 error('No rule specified before "@subchain"')
2007 unless $current{has_rule};
2009 my $subchain;
2010 $keyword = next_token();
2012 if ($keyword =~ /^(["'])(.*)\1$/s) {
2013 $subchain = $2;
2014 $keyword = next_token();
2015 } else {
2016 $subchain = 'ferm_auto_' . ++$auto_chain;
2019 error('"{" or chain name expected after "sub"')
2020 unless $keyword eq '{';
2022 # create a deep copy of %current, only containing values
2023 # which must be in the subchain
2024 my %inner = ( cow => { keywords => 1, },
2025 keywords => $current{keywords},
2026 builtin => {},
2027 action => {},
2029 $inner{domain} = $current{domain};
2030 $inner{domain_family} = $current{domain_family};
2031 $inner{table} = $current{table};
2032 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2033 $inner{builtin}{protocol} = $current{builtin}{protocol}
2034 if exists $current{builtin}{protocol};
2036 # enter the block
2037 enter(1, \%inner);
2039 # now handle the parent - it's a jump to the sub chain
2040 $current{action} = { type => 'jump',
2041 chain => $subchain,
2044 $current{script} = { filename => $script->{filename},
2045 line => $script->{line},
2048 mkrules(\%current);
2050 # and clean up variables set in this level
2051 new_level(%current, $prev);
2053 next;
2056 # everything else must be part of a "real" rule, not just
2057 # "policy only"
2058 $current{has_rule}++;
2060 # extended parameters:
2061 if ($keyword =~ /^mod(?:ule)?$/) {
2062 foreach my $module (to_array getvalues) {
2063 next if grep { $_->{name} eq $module } @{$current{match}};
2065 my $domain_family = $current{domain_family};
2066 my $defs = $match_defs{$domain_family}{$module};
2067 if (not defined $defs and exists $current{builtin}{protocol}) {
2068 my $proto = $current{builtin}{protocol};
2069 unless (ref $proto) {
2070 $proto = netfilter_canonical_protocol($current{builtin}{protocol});
2071 $defs = $proto_defs{$domain_family}{$proto}
2072 if netfilter_protocol_module($proto) eq $module;
2076 push @{$current{match}}, { name => $module,
2077 options => {},
2078 defs => $defs,
2081 if (defined $defs) {
2082 copy_on_write(\%current, 'keywords');
2083 while (my ($k, $def) = each %{$defs->{keywords}}) {
2084 $current{keywords}{$k} = [ 'match', $module, $def ];
2089 next;
2092 # keywords from $current{keywords}
2094 if (exists $current{keywords}{$keyword}) {
2095 my ($type, $module, $def) = @{$current{keywords}{$keyword}};
2096 my $store;
2097 if ($type eq 'builtin') {
2098 $store = $current{builtin};
2099 } elsif ($type eq 'match') {
2100 $store = (grep { $_->{name} eq $module } @{$current{match}})[-1]->{options};
2101 } elsif ($type eq 'target') {
2102 $store = $current{target_options} ||= {};
2103 } else {
2104 die;
2107 parse_option($def, \%current, $store, $keyword, \$negated);
2108 next;
2112 # actions
2115 # jump action
2116 if ($keyword eq 'jump') {
2117 error('There can only one action per rule')
2118 if defined $current{action}{type};
2119 my $chain = getvar();
2120 if (is_netfilter_core_target($chain) or
2121 is_netfilter_module_target($current{domain_family}, $chain)) {
2122 my $defs = $target_defs{$current{domain_family}} &&
2123 $target_defs{$current{domain_family}}{$chain};
2124 $current{action} = { type => 'target',
2125 target => $chain,
2126 defs => $defs,
2129 if (defined $defs) {
2130 copy_on_write(\%current, 'keywords');
2131 while (my ($k, $def) = each %{$defs->{keywords}}) {
2132 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2135 } else {
2136 $current{action} = { type => 'jump',
2137 chain => $chain,
2140 next;
2143 # goto action
2144 if ($keyword eq 'realgoto') {
2145 error('There can only one action per rule')
2146 if defined $current{action}{type};
2147 $current{action} = { type => 'goto',
2148 chain => getvar(),
2150 next;
2153 # action keywords
2154 if (is_netfilter_core_target($keyword)) {
2155 error('There can only one action per rule')
2156 if defined $current{action}{type};
2157 $current{action} = { type => 'target',
2158 target => $keyword,
2160 next;
2163 if ($keyword eq 'NOP') {
2164 error('There can only one action per rule')
2165 if defined $current{action}{type};
2166 $current{action} = { type => 'nop',
2168 next;
2171 if (is_netfilter_module_target($current{domain_family}, $keyword)) {
2172 error('There can only one action per rule')
2173 if defined $current{action}{type};
2175 if ($keyword eq 'TCPMSS') {
2176 my $protos = $current{builtin}{protocol};
2177 error('No protocol specified before TCPMSS')
2178 unless defined $protos;
2179 foreach my $proto (to_array $protos) {
2180 error('TCPMSS not available for protocol "$proto"')
2181 unless $proto eq 'tcp';
2185 my $defs = $target_defs{$current{domain_family}}{$keyword};
2187 $current{action} = { type => 'target',
2188 target => $keyword,
2189 defs => $defs,
2192 if (defined $defs) {
2193 copy_on_write(\%current, 'keywords');
2194 while (my ($k, $def) = each %{$defs->{keywords}}) {
2195 $current{keywords}{$k} = [ 'target', $keyword, $def ];
2199 next;
2202 my $proto = $current{builtin}{protocol};
2205 # protocol specific options
2208 if (defined $proto and not ref $proto) {
2209 $proto = netfilter_canonical_protocol($proto);
2211 if ($proto eq 'icmp') {
2212 my $domains = $current{domain};
2213 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2216 parse_protocol_options(\%current, $proto, $keyword, \$negated)
2217 and next;
2220 # port switches
2221 if ($keyword =~ /^[sd]port$/) {
2222 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2223 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2225 $current{$keyword} = getvalues(undef, undef,
2226 allow_negation => 1);
2227 next;
2230 # default
2231 error("Unrecognized keyword: $keyword");
2234 # if the rule didn't reset the negated flag, it's not
2235 # supported
2236 error("Doesn't support negation: $keyword")
2237 if $negated;
2240 error('Missing "}" at end of file')
2241 if $lev > $base_level;
2243 # consistency check: check if they havn't forgotten
2244 # the ';' before the last statement
2245 error("Missing semicolon before end of file")
2246 if $current{has_rule}; # XXX
2249 sub check() {
2250 while (my ($domain_name, $domain) = each %domains) {
2251 while (my ($table_name, $table_info) = each %{$domain->{tables}}) {
2252 while (my ($chain_name, $chain) = each %{$table_info->{chains}}) {
2253 warning("chain $chain_name (domain $domain_name, table $table_name) was referenced, but not declared")
2254 if $chain->{was_created} and not $chain->{non_empty};
2260 sub execute_command {
2261 my ($command, $script) = @_;
2263 print LINES "$command\n"
2264 if $option{lines};
2265 return if $option{noexec};
2267 my $ret = system($_);
2268 unless ($ret == 0) {
2269 if ($? == -1) {
2270 print STDERR "failed to execute: $!\n";
2271 exit 1;
2272 } elsif ($? & 0x7f) {
2273 printf STDERR "child died with signal %d\n", $? & 0x7f;
2274 return 1;
2275 } else {
2276 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2277 if defined $script;
2278 return $? >> 8;
2282 return;
2285 sub execute_slow($$) {
2286 my ($domain, $domain_info) = @_;
2288 my $domain_cmd = $domain_info->{tools}{tables};
2290 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2291 my $table_cmd = "$domain_cmd -t $table";
2293 # reset chain policies
2294 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2295 next unless $chain_info->{builtin} or
2296 (not $table_info->{has_builtin} and
2297 is_netfilter_builtin_chain($table, $chain));
2298 $status ||= execute_command("$table_cmd -P $chain ACCEPT");
2301 # clear
2302 $status ||= execute_command("$table_cmd -F");
2303 $status ||= execute_command("$table_cmd -X");
2305 next if $option{flush};
2307 # create chains / set policy
2308 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2309 if (exists $chain_info->{policy}) {
2310 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2311 unless $chain_info->{policy} eq 'ACCEPT';
2312 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2313 $status ||= execute_command("$table_cmd -N $chain");
2317 # dump rules
2318 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2319 my $chain_cmd = "$table_cmd -A $chain";
2320 foreach my $rule (@{$chain_info->{rules}}) {
2321 $status ||= execute_command($chain_cmd . $rule->{rule});
2326 return $status;
2329 sub rules_to_save($$) {
2330 my ($domain, $domain_info) = @_;
2332 # convert this into an iptables-save text
2333 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2335 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2336 # select table
2337 $result .= '*' . $table . "\n";
2339 # create chains / set policy
2340 foreach my $chain (sort keys %{$table_info->{chains}}) {
2341 my $chain_info = $table_info->{chains}{$chain};
2342 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2343 unless (defined $policy) {
2344 if (is_netfilter_builtin_chain($table, $chain)) {
2345 $policy = 'ACCEPT';
2346 } else {
2347 $policy = '-';
2350 $result .= ":$chain $policy\ [0:0]\n";
2353 next if $option{flush};
2355 # dump rules
2356 foreach my $chain (sort keys %{$table_info->{chains}}) {
2357 my $chain_info = $table_info->{chains}{$chain};
2358 foreach my $rule (@{$chain_info->{rules}}) {
2359 $result .= "-A $chain$rule->{rule}\n";
2363 # do it
2364 $result .= "COMMIT\n";
2367 return $result;
2370 sub restore_domain($$) {
2371 my ($domain, $save) = @_;
2373 my $path = $domains{$domain}{tools}{'tables-restore'};
2375 local *RESTORE;
2376 open RESTORE, "|$path"
2377 or die "Failed to run $path: $!\n";
2379 print RESTORE $save;
2381 close RESTORE
2382 or die "Failed to run $path\n";
2385 sub execute_fast($$) {
2386 my ($domain, $domain_info) = @_;
2388 my $save = rules_to_save($domain, $domain_info);
2390 if ($option{lines}) {
2391 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2392 if $option{shell};
2393 print LINES $save;
2394 print LINES "EOT\n"
2395 if $option{shell};
2398 return if $option{noexec};
2400 eval {
2401 restore_domain($domain, $save);
2403 if ($@) {
2404 print STDERR $@;
2405 return 1;
2408 return;
2411 sub rollback() {
2412 my $error;
2413 while (my ($domain, $domain_info) = each %domains) {
2414 next unless $domain_info->{enabled};
2415 unless (defined $domain_info->{tools}{'tables-restore'}) {
2416 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2417 next;
2420 my $reset = '';
2421 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2422 my $reset_chain = '';
2423 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2424 next unless is_netfilter_builtin_chain($table, $chain);
2425 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2427 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2428 if length $reset_chain;
2431 $reset .= $domain_info->{previous}
2432 if defined $domain_info->{previous};
2434 restore_domain($domain, $reset);
2437 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2438 exit 1;
2441 sub alrm_handler {
2442 # do nothing, just interrupt a system call
2445 sub confirm_rules() {
2446 $SIG{ALRM} = \&alrm_handler;
2448 alarm(5);
2450 print STDERR "\n"
2451 . "ferm has applied the new firewall rules.\n"
2452 . "Please type 'yes' to confirm:\n";
2453 STDERR->flush();
2455 alarm(30);
2457 my $line = '';
2458 STDIN->sysread($line, 3);
2460 eval {
2461 require POSIX;
2462 POSIX::tcflush(*STDIN, 2);
2464 print STDERR "$@" if $@;
2466 $SIG{ALRM} = 'DEFAULT';
2468 return $line eq 'yes';
2471 # end of ferm
2473 __END__
2475 =head1 NAME
2477 ferm - a firewall rule parser for linux
2479 =head1 SYNOPSIS
2481 B<ferm> I<options> I<inputfiles>
2483 =head1 OPTIONS
2485 -n, --noexec Do not execute the rules, just simulate
2486 -F, --flush Flush all netfilter tables managed by ferm
2487 -l, --lines Show all rules that were created
2488 -i, --interactive Interactive mode: revert if user does not confirm
2489 --remote Remote mode; ignore host specific configuration.
2490 This implies --noexec and --lines.
2491 -V, --version Show current version number
2492 -h, --help Look at this text
2493 --fast Generate an iptables-save file, used by iptables-restore
2494 --shell Generate a shell script which calls iptables-restore
2495 --domain {ip|ip6} Handle only the specified domain
2496 --def '$name=v' Override a variable
2498 =cut