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